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/internal.h>
39 #include <asm/idtentry.h>
41 #include <asm/irq_remapping.h>
42 #include <asm/kexec.h>
43 #include <asm/perf_event.h>
44 #include <asm/mmu_context.h>
45 #include <asm/mshyperv.h>
46 #include <asm/mwait.h>
47 #include <asm/spec-ctrl.h>
48 #include <asm/virtext.h>
51 #include "capabilities.h"
55 #include "kvm_onhyperv.h"
57 #include "kvm_cache_regs.h"
69 MODULE_AUTHOR("Qumranet");
70 MODULE_LICENSE("GPL");
73 static const struct x86_cpu_id vmx_cpu_id[] = {
74 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
77 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
80 bool __read_mostly enable_vpid = 1;
81 module_param_named(vpid, enable_vpid, bool, 0444);
83 static bool __read_mostly enable_vnmi = 1;
84 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
86 bool __read_mostly flexpriority_enabled = 1;
87 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
89 bool __read_mostly enable_ept = 1;
90 module_param_named(ept, enable_ept, bool, S_IRUGO);
92 bool __read_mostly enable_unrestricted_guest = 1;
93 module_param_named(unrestricted_guest,
94 enable_unrestricted_guest, bool, S_IRUGO);
96 bool __read_mostly enable_ept_ad_bits = 1;
97 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
99 static bool __read_mostly emulate_invalid_guest_state = true;
100 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
102 static bool __read_mostly fasteoi = 1;
103 module_param(fasteoi, bool, S_IRUGO);
105 module_param(enable_apicv, bool, S_IRUGO);
108 * If nested=1, nested virtualization is supported, i.e., guests may use
109 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
110 * use VMX instructions.
112 static bool __read_mostly nested = 1;
113 module_param(nested, bool, S_IRUGO);
115 bool __read_mostly enable_pml = 1;
116 module_param_named(pml, enable_pml, bool, S_IRUGO);
118 static bool __read_mostly dump_invalid_vmcs = 0;
119 module_param(dump_invalid_vmcs, bool, 0644);
121 #define MSR_BITMAP_MODE_X2APIC 1
122 #define MSR_BITMAP_MODE_X2APIC_APICV 2
124 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
126 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
127 static int __read_mostly cpu_preemption_timer_multi;
128 static bool __read_mostly enable_preemption_timer = 1;
130 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
133 extern bool __read_mostly allow_smaller_maxphyaddr;
134 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
136 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
137 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
138 #define KVM_VM_CR0_ALWAYS_ON \
139 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
141 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
142 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
143 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
145 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
147 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
148 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
149 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
150 RTIT_STATUS_BYTECNT))
153 * List of MSRs that can be directly passed to the guest.
154 * In addition to these x2apic and PT MSRs are handled specially.
156 static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
165 MSR_IA32_SYSENTER_CS,
166 MSR_IA32_SYSENTER_ESP,
167 MSR_IA32_SYSENTER_EIP,
169 MSR_CORE_C3_RESIDENCY,
170 MSR_CORE_C6_RESIDENCY,
171 MSR_CORE_C7_RESIDENCY,
175 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
176 * ple_gap: upper bound on the amount of time between two successive
177 * executions of PAUSE in a loop. Also indicate if ple enabled.
178 * According to test, this time is usually smaller than 128 cycles.
179 * ple_window: upper bound on the amount of time a guest is allowed to execute
180 * in a PAUSE loop. Tests indicate that most spinlocks are held for
181 * less than 2^12 cycles
182 * Time is measured based on a counter that runs at the same rate as the TSC,
183 * refer SDM volume 3b section 21.6.13 & 22.1.3.
185 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
186 module_param(ple_gap, uint, 0444);
188 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
189 module_param(ple_window, uint, 0444);
191 /* Default doubles per-vcpu window every exit. */
192 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
193 module_param(ple_window_grow, uint, 0444);
195 /* Default resets per-vcpu window every exit to ple_window. */
196 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
197 module_param(ple_window_shrink, uint, 0444);
199 /* Default is to compute the maximum so we can never overflow. */
200 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
201 module_param(ple_window_max, uint, 0444);
203 /* Default is SYSTEM mode, 1 for host-guest mode */
204 int __read_mostly pt_mode = PT_MODE_SYSTEM;
205 module_param(pt_mode, int, S_IRUGO);
207 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
208 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
209 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
211 /* Storage for pre module init parameter parsing */
212 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
214 static const struct {
217 } vmentry_l1d_param[] = {
218 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
219 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
220 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
221 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
222 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
223 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
226 #define L1D_CACHE_ORDER 4
227 static void *vmx_l1d_flush_pages;
229 /* Control for disabling CPU Fill buffer clear */
230 static bool __read_mostly vmx_fb_clear_ctrl_available;
232 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
237 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
238 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
243 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
247 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
250 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
251 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
252 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
257 /* If set to auto use the default l1tf mitigation method */
258 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
259 switch (l1tf_mitigation) {
260 case L1TF_MITIGATION_OFF:
261 l1tf = VMENTER_L1D_FLUSH_NEVER;
263 case L1TF_MITIGATION_FLUSH_NOWARN:
264 case L1TF_MITIGATION_FLUSH:
265 case L1TF_MITIGATION_FLUSH_NOSMT:
266 l1tf = VMENTER_L1D_FLUSH_COND;
268 case L1TF_MITIGATION_FULL:
269 case L1TF_MITIGATION_FULL_FORCE:
270 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
273 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
274 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
277 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
278 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
280 * This allocation for vmx_l1d_flush_pages is not tied to a VM
281 * lifetime and so should not be charged to a memcg.
283 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
286 vmx_l1d_flush_pages = page_address(page);
289 * Initialize each page with a different pattern in
290 * order to protect against KSM in the nested
291 * virtualization case.
293 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
294 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
299 l1tf_vmx_mitigation = l1tf;
301 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
302 static_branch_enable(&vmx_l1d_should_flush);
304 static_branch_disable(&vmx_l1d_should_flush);
306 if (l1tf == VMENTER_L1D_FLUSH_COND)
307 static_branch_enable(&vmx_l1d_flush_cond);
309 static_branch_disable(&vmx_l1d_flush_cond);
313 static int vmentry_l1d_flush_parse(const char *s)
318 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
319 if (vmentry_l1d_param[i].for_parse &&
320 sysfs_streq(s, vmentry_l1d_param[i].option))
327 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
331 l1tf = vmentry_l1d_flush_parse(s);
335 if (!boot_cpu_has(X86_BUG_L1TF))
339 * Has vmx_init() run already? If not then this is the pre init
340 * parameter parsing. In that case just store the value and let
341 * vmx_init() do the proper setup after enable_ept has been
344 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
345 vmentry_l1d_flush_param = l1tf;
349 mutex_lock(&vmx_l1d_flush_mutex);
350 ret = vmx_setup_l1d_flush(l1tf);
351 mutex_unlock(&vmx_l1d_flush_mutex);
355 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
357 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
358 return sprintf(s, "???\n");
360 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
363 static void vmx_setup_fb_clear_ctrl(void)
367 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES) &&
368 !boot_cpu_has_bug(X86_BUG_MDS) &&
369 !boot_cpu_has_bug(X86_BUG_TAA)) {
370 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
371 if (msr & ARCH_CAP_FB_CLEAR_CTRL)
372 vmx_fb_clear_ctrl_available = true;
376 static __always_inline void vmx_disable_fb_clear(struct vcpu_vmx *vmx)
380 if (!vmx->disable_fb_clear)
383 msr = __rdmsr(MSR_IA32_MCU_OPT_CTRL);
385 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, msr);
386 /* Cache the MSR value to avoid reading it later */
387 vmx->msr_ia32_mcu_opt_ctrl = msr;
390 static __always_inline void vmx_enable_fb_clear(struct vcpu_vmx *vmx)
392 if (!vmx->disable_fb_clear)
395 vmx->msr_ia32_mcu_opt_ctrl &= ~FB_CLEAR_DIS;
396 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, vmx->msr_ia32_mcu_opt_ctrl);
399 static void vmx_update_fb_clear_dis(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx)
401 vmx->disable_fb_clear = vmx_fb_clear_ctrl_available;
404 * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS
405 * at VMEntry. Skip the MSR read/write when a guest has no use case to
408 if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) ||
409 ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) &&
410 (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) &&
411 (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) &&
412 (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) &&
413 (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO)))
414 vmx->disable_fb_clear = false;
417 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
418 .set = vmentry_l1d_flush_set,
419 .get = vmentry_l1d_flush_get,
421 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
423 static u32 vmx_segment_access_rights(struct kvm_segment *var);
425 void vmx_vmexit(void);
427 #define vmx_insn_failed(fmt...) \
430 pr_warn_ratelimited(fmt); \
433 asmlinkage void vmread_error(unsigned long field, bool fault)
436 kvm_spurious_fault();
438 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
441 noinline void vmwrite_error(unsigned long field, unsigned long value)
443 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
444 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
447 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
449 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
452 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
454 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
457 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
459 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
463 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
465 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
469 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
470 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
472 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
473 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
475 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
477 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
478 static DEFINE_SPINLOCK(vmx_vpid_lock);
480 struct vmcs_config vmcs_config;
481 struct vmx_capability vmx_capability;
483 #define VMX_SEGMENT_FIELD(seg) \
484 [VCPU_SREG_##seg] = { \
485 .selector = GUEST_##seg##_SELECTOR, \
486 .base = GUEST_##seg##_BASE, \
487 .limit = GUEST_##seg##_LIMIT, \
488 .ar_bytes = GUEST_##seg##_AR_BYTES, \
491 static const struct kvm_vmx_segment_field {
496 } kvm_vmx_segment_fields[] = {
497 VMX_SEGMENT_FIELD(CS),
498 VMX_SEGMENT_FIELD(DS),
499 VMX_SEGMENT_FIELD(ES),
500 VMX_SEGMENT_FIELD(FS),
501 VMX_SEGMENT_FIELD(GS),
502 VMX_SEGMENT_FIELD(SS),
503 VMX_SEGMENT_FIELD(TR),
504 VMX_SEGMENT_FIELD(LDTR),
507 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
509 vmx->segment_cache.bitmask = 0;
512 static unsigned long host_idt_base;
514 #if IS_ENABLED(CONFIG_HYPERV)
515 static bool __read_mostly enlightened_vmcs = true;
516 module_param(enlightened_vmcs, bool, 0444);
518 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
520 struct hv_enlightened_vmcs *evmcs;
521 struct hv_partition_assist_pg **p_hv_pa_pg =
522 &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
524 * Synthetic VM-Exit is not enabled in current code and so All
525 * evmcs in singe VM shares same assist page.
528 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
533 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
535 evmcs->partition_assist_page =
537 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
538 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
543 #endif /* IS_ENABLED(CONFIG_HYPERV) */
546 * Comment's format: document - errata name - stepping - processor name.
548 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
550 static u32 vmx_preemption_cpu_tfms[] = {
551 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
553 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
554 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
555 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
557 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
559 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
560 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
562 * 320767.pdf - AAP86 - B1 -
563 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
566 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
568 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
570 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
572 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
573 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
574 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
576 /* Xeon E3-1220 V2 */
580 static inline bool cpu_has_broken_vmx_preemption_timer(void)
582 u32 eax = cpuid_eax(0x00000001), i;
584 /* Clear the reserved bits */
585 eax &= ~(0x3U << 14 | 0xfU << 28);
586 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
587 if (eax == vmx_preemption_cpu_tfms[i])
593 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
595 return flexpriority_enabled && lapic_in_kernel(vcpu);
598 static inline bool report_flexpriority(void)
600 return flexpriority_enabled;
603 static int possible_passthrough_msr_slot(u32 msr)
607 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
608 if (vmx_possible_passthrough_msrs[i] == msr)
614 static bool is_valid_passthrough_msr(u32 msr)
619 case 0x800 ... 0x8ff:
620 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
622 case MSR_IA32_RTIT_STATUS:
623 case MSR_IA32_RTIT_OUTPUT_BASE:
624 case MSR_IA32_RTIT_OUTPUT_MASK:
625 case MSR_IA32_RTIT_CR3_MATCH:
626 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
627 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
630 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
631 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
632 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
633 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
634 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
635 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
639 r = possible_passthrough_msr_slot(msr) != -ENOENT;
641 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
646 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
650 i = kvm_find_user_return_msr(msr);
652 return &vmx->guest_uret_msrs[i];
656 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
657 struct vmx_uret_msr *msr, u64 data)
659 unsigned int slot = msr - vmx->guest_uret_msrs;
662 u64 old_msr_data = msr->data;
664 if (msr->load_into_hardware) {
666 ret = kvm_set_user_return_msr(slot, msr->data, msr->mask);
669 msr->data = old_msr_data;
674 #ifdef CONFIG_KEXEC_CORE
675 static void crash_vmclear_local_loaded_vmcss(void)
677 int cpu = raw_smp_processor_id();
678 struct loaded_vmcs *v;
680 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
681 loaded_vmcss_on_cpu_link)
684 #endif /* CONFIG_KEXEC_CORE */
686 static void __loaded_vmcs_clear(void *arg)
688 struct loaded_vmcs *loaded_vmcs = arg;
689 int cpu = raw_smp_processor_id();
691 if (loaded_vmcs->cpu != cpu)
692 return; /* vcpu migration can race with cpu offline */
693 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
694 per_cpu(current_vmcs, cpu) = NULL;
696 vmcs_clear(loaded_vmcs->vmcs);
697 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
698 vmcs_clear(loaded_vmcs->shadow_vmcs);
700 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
703 * Ensure all writes to loaded_vmcs, including deleting it from its
704 * current percpu list, complete before setting loaded_vmcs->vcpu to
705 * -1, otherwise a different cpu can see vcpu == -1 first and add
706 * loaded_vmcs to its percpu list before it's deleted from this cpu's
707 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
711 loaded_vmcs->cpu = -1;
712 loaded_vmcs->launched = 0;
715 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
717 int cpu = loaded_vmcs->cpu;
720 smp_call_function_single(cpu,
721 __loaded_vmcs_clear, loaded_vmcs, 1);
724 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
728 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
730 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
731 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
732 vmx->segment_cache.bitmask = 0;
734 ret = vmx->segment_cache.bitmask & mask;
735 vmx->segment_cache.bitmask |= mask;
739 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
741 u16 *p = &vmx->segment_cache.seg[seg].selector;
743 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
744 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
748 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
750 ulong *p = &vmx->segment_cache.seg[seg].base;
752 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
753 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
757 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
759 u32 *p = &vmx->segment_cache.seg[seg].limit;
761 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
762 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
766 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
768 u32 *p = &vmx->segment_cache.seg[seg].ar;
770 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
771 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
775 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
779 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
780 (1u << DB_VECTOR) | (1u << AC_VECTOR);
782 * Guest access to VMware backdoor ports could legitimately
783 * trigger #GP because of TSS I/O permission bitmap.
784 * We intercept those #GP and allow access to them anyway
787 if (enable_vmware_backdoor)
788 eb |= (1u << GP_VECTOR);
789 if ((vcpu->guest_debug &
790 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
791 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
792 eb |= 1u << BP_VECTOR;
793 if (to_vmx(vcpu)->rmode.vm86_active)
795 if (!vmx_need_pf_intercept(vcpu))
796 eb &= ~(1u << PF_VECTOR);
798 /* When we are running a nested L2 guest and L1 specified for it a
799 * certain exception bitmap, we must trap the same exceptions and pass
800 * them to L1. When running L2, we will only handle the exceptions
801 * specified above if L1 did not want them.
803 if (is_guest_mode(vcpu))
804 eb |= get_vmcs12(vcpu)->exception_bitmap;
806 int mask = 0, match = 0;
808 if (enable_ept && (eb & (1u << PF_VECTOR))) {
810 * If EPT is enabled, #PF is currently only intercepted
811 * if MAXPHYADDR is smaller on the guest than on the
812 * host. In that case we only care about present,
813 * non-reserved faults. For vmcs02, however, PFEC_MASK
814 * and PFEC_MATCH are set in prepare_vmcs02_rare.
816 mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK;
817 match = PFERR_PRESENT_MASK;
819 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
820 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match);
823 vmcs_write32(EXCEPTION_BITMAP, eb);
827 * Check if MSR is intercepted for currently loaded MSR bitmap.
829 static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr)
831 if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS))
834 return vmx_test_msr_bitmap_write(vmx->loaded_vmcs->msr_bitmap,
838 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
839 unsigned long entry, unsigned long exit)
841 vm_entry_controls_clearbit(vmx, entry);
842 vm_exit_controls_clearbit(vmx, exit);
845 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
849 for (i = 0; i < m->nr; ++i) {
850 if (m->val[i].index == msr)
856 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
859 struct msr_autoload *m = &vmx->msr_autoload;
863 if (cpu_has_load_ia32_efer()) {
864 clear_atomic_switch_msr_special(vmx,
865 VM_ENTRY_LOAD_IA32_EFER,
866 VM_EXIT_LOAD_IA32_EFER);
870 case MSR_CORE_PERF_GLOBAL_CTRL:
871 if (cpu_has_load_perf_global_ctrl()) {
872 clear_atomic_switch_msr_special(vmx,
873 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
874 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
879 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
883 m->guest.val[i] = m->guest.val[m->guest.nr];
884 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
887 i = vmx_find_loadstore_msr_slot(&m->host, msr);
892 m->host.val[i] = m->host.val[m->host.nr];
893 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
896 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
897 unsigned long entry, unsigned long exit,
898 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
899 u64 guest_val, u64 host_val)
901 vmcs_write64(guest_val_vmcs, guest_val);
902 if (host_val_vmcs != HOST_IA32_EFER)
903 vmcs_write64(host_val_vmcs, host_val);
904 vm_entry_controls_setbit(vmx, entry);
905 vm_exit_controls_setbit(vmx, exit);
908 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
909 u64 guest_val, u64 host_val, bool entry_only)
912 struct msr_autoload *m = &vmx->msr_autoload;
916 if (cpu_has_load_ia32_efer()) {
917 add_atomic_switch_msr_special(vmx,
918 VM_ENTRY_LOAD_IA32_EFER,
919 VM_EXIT_LOAD_IA32_EFER,
922 guest_val, host_val);
926 case MSR_CORE_PERF_GLOBAL_CTRL:
927 if (cpu_has_load_perf_global_ctrl()) {
928 add_atomic_switch_msr_special(vmx,
929 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
930 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
931 GUEST_IA32_PERF_GLOBAL_CTRL,
932 HOST_IA32_PERF_GLOBAL_CTRL,
933 guest_val, host_val);
937 case MSR_IA32_PEBS_ENABLE:
938 /* PEBS needs a quiescent period after being disabled (to write
939 * a record). Disabling PEBS through VMX MSR swapping doesn't
940 * provide that period, so a CPU could write host's record into
943 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
946 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
948 j = vmx_find_loadstore_msr_slot(&m->host, msr);
950 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
951 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
952 printk_once(KERN_WARNING "Not enough msr switch entries. "
953 "Can't add msr %x\n", msr);
958 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
960 m->guest.val[i].index = msr;
961 m->guest.val[i].value = guest_val;
968 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
970 m->host.val[j].index = msr;
971 m->host.val[j].value = host_val;
974 static bool update_transition_efer(struct vcpu_vmx *vmx)
976 u64 guest_efer = vmx->vcpu.arch.efer;
980 /* Shadow paging assumes NX to be available. */
982 guest_efer |= EFER_NX;
985 * LMA and LME handled by hardware; SCE meaningless outside long mode.
987 ignore_bits |= EFER_SCE;
989 ignore_bits |= EFER_LMA | EFER_LME;
990 /* SCE is meaningful only in long mode on Intel */
991 if (guest_efer & EFER_LMA)
992 ignore_bits &= ~(u64)EFER_SCE;
996 * On EPT, we can't emulate NX, so we must switch EFER atomically.
997 * On CPUs that support "load IA32_EFER", always switch EFER
998 * atomically, since it's faster than switching it manually.
1000 if (cpu_has_load_ia32_efer() ||
1001 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1002 if (!(guest_efer & EFER_LMA))
1003 guest_efer &= ~EFER_LME;
1004 if (guest_efer != host_efer)
1005 add_atomic_switch_msr(vmx, MSR_EFER,
1006 guest_efer, host_efer, false);
1008 clear_atomic_switch_msr(vmx, MSR_EFER);
1012 i = kvm_find_user_return_msr(MSR_EFER);
1016 clear_atomic_switch_msr(vmx, MSR_EFER);
1018 guest_efer &= ~ignore_bits;
1019 guest_efer |= host_efer & ignore_bits;
1021 vmx->guest_uret_msrs[i].data = guest_efer;
1022 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1027 #ifdef CONFIG_X86_32
1029 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1030 * VMCS rather than the segment table. KVM uses this helper to figure
1031 * out the current bases to poke them into the VMCS before entry.
1033 static unsigned long segment_base(u16 selector)
1035 struct desc_struct *table;
1038 if (!(selector & ~SEGMENT_RPL_MASK))
1041 table = get_current_gdt_ro();
1043 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1044 u16 ldt_selector = kvm_read_ldt();
1046 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1049 table = (struct desc_struct *)segment_base(ldt_selector);
1051 v = get_desc_base(&table[selector >> 3]);
1056 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1058 return vmx_pt_mode_is_host_guest() &&
1059 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1062 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1064 /* The base must be 128-byte aligned and a legal physical address. */
1065 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1068 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1072 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1073 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1074 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1075 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1076 for (i = 0; i < addr_range; i++) {
1077 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1078 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1082 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1086 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1087 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1088 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1089 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1090 for (i = 0; i < addr_range; i++) {
1091 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1092 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1096 static void pt_guest_enter(struct vcpu_vmx *vmx)
1098 if (vmx_pt_mode_is_system())
1102 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1103 * Save host state before VM entry.
1105 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1106 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1107 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1108 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1109 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1113 static void pt_guest_exit(struct vcpu_vmx *vmx)
1115 if (vmx_pt_mode_is_system())
1118 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1119 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1120 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1123 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1124 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1127 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1128 unsigned long fs_base, unsigned long gs_base)
1130 if (unlikely(fs_sel != host->fs_sel)) {
1132 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1134 vmcs_write16(HOST_FS_SELECTOR, 0);
1135 host->fs_sel = fs_sel;
1137 if (unlikely(gs_sel != host->gs_sel)) {
1139 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1141 vmcs_write16(HOST_GS_SELECTOR, 0);
1142 host->gs_sel = gs_sel;
1144 if (unlikely(fs_base != host->fs_base)) {
1145 vmcs_writel(HOST_FS_BASE, fs_base);
1146 host->fs_base = fs_base;
1148 if (unlikely(gs_base != host->gs_base)) {
1149 vmcs_writel(HOST_GS_BASE, gs_base);
1150 host->gs_base = gs_base;
1154 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1156 struct vcpu_vmx *vmx = to_vmx(vcpu);
1157 struct vmcs_host_state *host_state;
1158 #ifdef CONFIG_X86_64
1159 int cpu = raw_smp_processor_id();
1161 unsigned long fs_base, gs_base;
1165 vmx->req_immediate_exit = false;
1168 * Note that guest MSRs to be saved/restored can also be changed
1169 * when guest state is loaded. This happens when guest transitions
1170 * to/from long-mode by setting MSR_EFER.LMA.
1172 if (!vmx->guest_uret_msrs_loaded) {
1173 vmx->guest_uret_msrs_loaded = true;
1174 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
1175 if (!vmx->guest_uret_msrs[i].load_into_hardware)
1178 kvm_set_user_return_msr(i,
1179 vmx->guest_uret_msrs[i].data,
1180 vmx->guest_uret_msrs[i].mask);
1184 if (vmx->nested.need_vmcs12_to_shadow_sync)
1185 nested_sync_vmcs12_to_shadow(vcpu);
1187 if (vmx->guest_state_loaded)
1190 host_state = &vmx->loaded_vmcs->host_state;
1193 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1194 * allow segment selectors with cpl > 0 or ti == 1.
1196 host_state->ldt_sel = kvm_read_ldt();
1198 #ifdef CONFIG_X86_64
1199 savesegment(ds, host_state->ds_sel);
1200 savesegment(es, host_state->es_sel);
1202 gs_base = cpu_kernelmode_gs_base(cpu);
1203 if (likely(is_64bit_mm(current->mm))) {
1204 current_save_fsgs();
1205 fs_sel = current->thread.fsindex;
1206 gs_sel = current->thread.gsindex;
1207 fs_base = current->thread.fsbase;
1208 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1210 savesegment(fs, fs_sel);
1211 savesegment(gs, gs_sel);
1212 fs_base = read_msr(MSR_FS_BASE);
1213 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1216 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1218 savesegment(fs, fs_sel);
1219 savesegment(gs, gs_sel);
1220 fs_base = segment_base(fs_sel);
1221 gs_base = segment_base(gs_sel);
1224 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1225 vmx->guest_state_loaded = true;
1228 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1230 struct vmcs_host_state *host_state;
1232 if (!vmx->guest_state_loaded)
1235 host_state = &vmx->loaded_vmcs->host_state;
1237 ++vmx->vcpu.stat.host_state_reload;
1239 #ifdef CONFIG_X86_64
1240 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1242 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1243 kvm_load_ldt(host_state->ldt_sel);
1244 #ifdef CONFIG_X86_64
1245 load_gs_index(host_state->gs_sel);
1247 loadsegment(gs, host_state->gs_sel);
1250 if (host_state->fs_sel & 7)
1251 loadsegment(fs, host_state->fs_sel);
1252 #ifdef CONFIG_X86_64
1253 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1254 loadsegment(ds, host_state->ds_sel);
1255 loadsegment(es, host_state->es_sel);
1258 invalidate_tss_limit();
1259 #ifdef CONFIG_X86_64
1260 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1262 load_fixmap_gdt(raw_smp_processor_id());
1263 vmx->guest_state_loaded = false;
1264 vmx->guest_uret_msrs_loaded = false;
1267 #ifdef CONFIG_X86_64
1268 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1271 if (vmx->guest_state_loaded)
1272 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1274 return vmx->msr_guest_kernel_gs_base;
1277 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1280 if (vmx->guest_state_loaded)
1281 wrmsrl(MSR_KERNEL_GS_BASE, data);
1283 vmx->msr_guest_kernel_gs_base = data;
1287 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1288 struct loaded_vmcs *buddy)
1290 struct vcpu_vmx *vmx = to_vmx(vcpu);
1291 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1294 if (!already_loaded) {
1295 loaded_vmcs_clear(vmx->loaded_vmcs);
1296 local_irq_disable();
1299 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1300 * this cpu's percpu list, otherwise it may not yet be deleted
1301 * from its previous cpu's percpu list. Pairs with the
1302 * smb_wmb() in __loaded_vmcs_clear().
1306 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1307 &per_cpu(loaded_vmcss_on_cpu, cpu));
1311 prev = per_cpu(current_vmcs, cpu);
1312 if (prev != vmx->loaded_vmcs->vmcs) {
1313 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1314 vmcs_load(vmx->loaded_vmcs->vmcs);
1317 * No indirect branch prediction barrier needed when switching
1318 * the active VMCS within a guest, e.g. on nested VM-Enter.
1319 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1321 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1322 indirect_branch_prediction_barrier();
1325 if (!already_loaded) {
1326 void *gdt = get_current_gdt_ro();
1327 unsigned long sysenter_esp;
1330 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1331 * TLB entries from its previous association with the vCPU.
1333 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1336 * Linux uses per-cpu TSS and GDT, so set these when switching
1337 * processors. See 22.2.4.
1339 vmcs_writel(HOST_TR_BASE,
1340 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1341 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1343 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1344 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1346 vmx->loaded_vmcs->cpu = cpu;
1351 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1352 * vcpu mutex is already taken.
1354 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1356 struct vcpu_vmx *vmx = to_vmx(vcpu);
1358 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1360 vmx_vcpu_pi_load(vcpu, cpu);
1362 vmx->host_debugctlmsr = get_debugctlmsr();
1365 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1367 vmx_vcpu_pi_put(vcpu);
1369 vmx_prepare_switch_to_host(to_vmx(vcpu));
1372 bool vmx_emulation_required(struct kvm_vcpu *vcpu)
1374 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1377 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1379 struct vcpu_vmx *vmx = to_vmx(vcpu);
1380 unsigned long rflags, save_rflags;
1382 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1383 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1384 rflags = vmcs_readl(GUEST_RFLAGS);
1385 if (vmx->rmode.vm86_active) {
1386 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1387 save_rflags = vmx->rmode.save_rflags;
1388 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1390 vmx->rflags = rflags;
1395 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1397 struct vcpu_vmx *vmx = to_vmx(vcpu);
1398 unsigned long old_rflags;
1400 if (is_unrestricted_guest(vcpu)) {
1401 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1402 vmx->rflags = rflags;
1403 vmcs_writel(GUEST_RFLAGS, rflags);
1407 old_rflags = vmx_get_rflags(vcpu);
1408 vmx->rflags = rflags;
1409 if (vmx->rmode.vm86_active) {
1410 vmx->rmode.save_rflags = rflags;
1411 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1413 vmcs_writel(GUEST_RFLAGS, rflags);
1415 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1416 vmx->emulation_required = vmx_emulation_required(vcpu);
1419 static bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
1421 return vmx_get_rflags(vcpu) & X86_EFLAGS_IF;
1424 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1426 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1429 if (interruptibility & GUEST_INTR_STATE_STI)
1430 ret |= KVM_X86_SHADOW_INT_STI;
1431 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1432 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1437 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1439 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1440 u32 interruptibility = interruptibility_old;
1442 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1444 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1445 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1446 else if (mask & KVM_X86_SHADOW_INT_STI)
1447 interruptibility |= GUEST_INTR_STATE_STI;
1449 if ((interruptibility != interruptibility_old))
1450 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1453 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1455 struct vcpu_vmx *vmx = to_vmx(vcpu);
1456 unsigned long value;
1459 * Any MSR write that attempts to change bits marked reserved will
1462 if (data & vmx->pt_desc.ctl_bitmask)
1466 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1467 * result in a #GP unless the same write also clears TraceEn.
1469 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1470 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1474 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1475 * and FabricEn would cause #GP, if
1476 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1478 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1479 !(data & RTIT_CTL_FABRIC_EN) &&
1480 !intel_pt_validate_cap(vmx->pt_desc.caps,
1481 PT_CAP_single_range_output))
1485 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1486 * utilize encodings marked reserved will cause a #GP fault.
1488 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1489 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1490 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1491 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1493 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1494 PT_CAP_cycle_thresholds);
1495 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1496 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1497 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1499 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1500 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1501 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1502 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1506 * If ADDRx_CFG is reserved or the encodings is >2 will
1507 * cause a #GP fault.
1509 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1510 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1512 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1513 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1515 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1516 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1518 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1519 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1525 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
1528 * Emulation of instructions in SGX enclaves is impossible as RIP does
1529 * not point tthe failing instruction, and even if it did, the code
1530 * stream is inaccessible. Inject #UD instead of exiting to userspace
1531 * so that guest userspace can't DoS the guest simply by triggering
1532 * emulation (enclaves are CPL3 only).
1534 if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1535 kvm_queue_exception(vcpu, UD_VECTOR);
1541 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1543 union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1544 unsigned long rip, orig_rip;
1548 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1549 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1550 * set when EPT misconfig occurs. In practice, real hardware updates
1551 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1552 * (namely Hyper-V) don't set it due to it being undefined behavior,
1553 * i.e. we end up advancing IP with some random value.
1555 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1556 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1557 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1560 * Emulating an enclave's instructions isn't supported as KVM
1561 * cannot access the enclave's memory or its true RIP, e.g. the
1562 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1563 * the RIP that actually triggered the VM-Exit. But, because
1564 * most instructions that cause VM-Exit will #UD in an enclave,
1565 * most instruction-based VM-Exits simply do not occur.
1567 * There are a few exceptions, notably the debug instructions
1568 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1569 * and generate #DB/#BP as expected, which KVM might intercept.
1570 * But again, the CPU does the dirty work and saves an instr
1571 * length of zero so VMMs don't shoot themselves in the foot.
1572 * WARN if KVM tries to skip a non-zero length instruction on
1573 * a VM-Exit from an enclave.
1578 WARN(exit_reason.enclave_mode,
1579 "KVM: skipping instruction after SGX enclave VM-Exit");
1581 orig_rip = kvm_rip_read(vcpu);
1582 rip = orig_rip + instr_len;
1583 #ifdef CONFIG_X86_64
1585 * We need to mask out the high 32 bits of RIP if not in 64-bit
1586 * mode, but just finding out that we are in 64-bit mode is
1587 * quite expensive. Only do it if there was a carry.
1589 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1592 kvm_rip_write(vcpu, rip);
1594 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1599 /* skipping an emulated instruction also counts */
1600 vmx_set_interrupt_shadow(vcpu, 0);
1606 * Recognizes a pending MTF VM-exit and records the nested state for later
1609 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1611 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1612 struct vcpu_vmx *vmx = to_vmx(vcpu);
1614 if (!is_guest_mode(vcpu))
1618 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1619 * T-bit traps. As instruction emulation is completed (i.e. at the
1620 * instruction boundary), any #DB exception pending delivery must be a
1621 * debug-trap. Record the pending MTF state to be delivered in
1622 * vmx_check_nested_events().
1624 if (nested_cpu_has_mtf(vmcs12) &&
1625 (!vcpu->arch.exception.pending ||
1626 vcpu->arch.exception.nr == DB_VECTOR))
1627 vmx->nested.mtf_pending = true;
1629 vmx->nested.mtf_pending = false;
1632 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1634 vmx_update_emulated_instruction(vcpu);
1635 return skip_emulated_instruction(vcpu);
1638 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1641 * Ensure that we clear the HLT state in the VMCS. We don't need to
1642 * explicitly skip the instruction because if the HLT state is set,
1643 * then the instruction is already executing and RIP has already been
1646 if (kvm_hlt_in_guest(vcpu->kvm) &&
1647 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1648 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1651 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1653 struct vcpu_vmx *vmx = to_vmx(vcpu);
1654 unsigned nr = vcpu->arch.exception.nr;
1655 bool has_error_code = vcpu->arch.exception.has_error_code;
1656 u32 error_code = vcpu->arch.exception.error_code;
1657 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1659 kvm_deliver_exception_payload(vcpu);
1661 if (has_error_code) {
1662 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1663 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1666 if (vmx->rmode.vm86_active) {
1668 if (kvm_exception_is_soft(nr))
1669 inc_eip = vcpu->arch.event_exit_inst_len;
1670 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1674 WARN_ON_ONCE(vmx->emulation_required);
1676 if (kvm_exception_is_soft(nr)) {
1677 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1678 vmx->vcpu.arch.event_exit_inst_len);
1679 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1681 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1683 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1685 vmx_clear_hlt(vcpu);
1688 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
1689 bool load_into_hardware)
1691 struct vmx_uret_msr *uret_msr;
1693 uret_msr = vmx_find_uret_msr(vmx, msr);
1697 uret_msr->load_into_hardware = load_into_hardware;
1701 * Configuring user return MSRs to automatically save, load, and restore MSRs
1702 * that need to be shoved into hardware when running the guest. Note, omitting
1703 * an MSR here does _NOT_ mean it's not emulated, only that it will not be
1704 * loaded into hardware when running the guest.
1706 static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx)
1708 #ifdef CONFIG_X86_64
1709 bool load_syscall_msrs;
1712 * The SYSCALL MSRs are only needed on long mode guests, and only
1713 * when EFER.SCE is set.
1715 load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
1716 (vmx->vcpu.arch.efer & EFER_SCE);
1718 vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
1719 vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
1720 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
1722 vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
1724 vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
1725 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
1726 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
1729 * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
1730 * kernel and old userspace. If those guests run on a tsx=off host, do
1731 * allow guests to use TSX_CTRL, but don't change the value in hardware
1732 * so that TSX remains always disabled.
1734 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
1737 * The set of MSRs to load may have changed, reload MSRs before the
1740 vmx->guest_uret_msrs_loaded = false;
1743 u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1745 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1747 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING))
1748 return vmcs12->tsc_offset;
1753 u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1755 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1757 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) &&
1758 nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
1759 return vmcs12->tsc_multiplier;
1761 return kvm_default_tsc_scaling_ratio;
1764 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1766 vmcs_write64(TSC_OFFSET, offset);
1769 static void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1771 vmcs_write64(TSC_MULTIPLIER, multiplier);
1775 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1776 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1777 * all guests if the "nested" module option is off, and can also be disabled
1778 * for a single guest by disabling its VMX cpuid bit.
1780 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1782 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1785 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1788 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1790 return !(val & ~valid_bits);
1793 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1795 switch (msr->index) {
1796 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1799 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1800 case MSR_IA32_PERF_CAPABILITIES:
1801 msr->data = vmx_get_perf_capabilities();
1804 return KVM_MSR_RET_INVALID;
1809 * Reads an msr value (of 'msr_index') into 'pdata'.
1810 * Returns 0 on success, non-0 otherwise.
1811 * Assumes vcpu_load() was already called.
1813 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1815 struct vcpu_vmx *vmx = to_vmx(vcpu);
1816 struct vmx_uret_msr *msr;
1819 switch (msr_info->index) {
1820 #ifdef CONFIG_X86_64
1822 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1825 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1827 case MSR_KERNEL_GS_BASE:
1828 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1832 return kvm_get_msr_common(vcpu, msr_info);
1833 case MSR_IA32_TSX_CTRL:
1834 if (!msr_info->host_initiated &&
1835 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1838 case MSR_IA32_UMWAIT_CONTROL:
1839 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1842 msr_info->data = vmx->msr_ia32_umwait_control;
1844 case MSR_IA32_SPEC_CTRL:
1845 if (!msr_info->host_initiated &&
1846 !guest_has_spec_ctrl_msr(vcpu))
1849 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1851 case MSR_IA32_SYSENTER_CS:
1852 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1854 case MSR_IA32_SYSENTER_EIP:
1855 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1857 case MSR_IA32_SYSENTER_ESP:
1858 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1860 case MSR_IA32_BNDCFGS:
1861 if (!kvm_mpx_supported() ||
1862 (!msr_info->host_initiated &&
1863 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1865 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1867 case MSR_IA32_MCG_EXT_CTL:
1868 if (!msr_info->host_initiated &&
1869 !(vmx->msr_ia32_feature_control &
1870 FEAT_CTL_LMCE_ENABLED))
1872 msr_info->data = vcpu->arch.mcg_ext_ctl;
1874 case MSR_IA32_FEAT_CTL:
1875 msr_info->data = vmx->msr_ia32_feature_control;
1877 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
1878 if (!msr_info->host_initiated &&
1879 !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
1881 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
1882 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
1884 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1885 if (!nested_vmx_allowed(vcpu))
1887 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1891 * Enlightened VMCS v1 doesn't have certain VMCS fields but
1892 * instead of just ignoring the features, different Hyper-V
1893 * versions are either trying to use them and fail or do some
1894 * sanity checking and refuse to boot. Filter all unsupported
1897 if (!msr_info->host_initiated &&
1898 vmx->nested.enlightened_vmcs_enabled)
1899 nested_evmcs_filter_control_msr(msr_info->index,
1902 case MSR_IA32_RTIT_CTL:
1903 if (!vmx_pt_mode_is_host_guest())
1905 msr_info->data = vmx->pt_desc.guest.ctl;
1907 case MSR_IA32_RTIT_STATUS:
1908 if (!vmx_pt_mode_is_host_guest())
1910 msr_info->data = vmx->pt_desc.guest.status;
1912 case MSR_IA32_RTIT_CR3_MATCH:
1913 if (!vmx_pt_mode_is_host_guest() ||
1914 !intel_pt_validate_cap(vmx->pt_desc.caps,
1915 PT_CAP_cr3_filtering))
1917 msr_info->data = vmx->pt_desc.guest.cr3_match;
1919 case MSR_IA32_RTIT_OUTPUT_BASE:
1920 if (!vmx_pt_mode_is_host_guest() ||
1921 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1922 PT_CAP_topa_output) &&
1923 !intel_pt_validate_cap(vmx->pt_desc.caps,
1924 PT_CAP_single_range_output)))
1926 msr_info->data = vmx->pt_desc.guest.output_base;
1928 case MSR_IA32_RTIT_OUTPUT_MASK:
1929 if (!vmx_pt_mode_is_host_guest() ||
1930 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1931 PT_CAP_topa_output) &&
1932 !intel_pt_validate_cap(vmx->pt_desc.caps,
1933 PT_CAP_single_range_output)))
1935 msr_info->data = vmx->pt_desc.guest.output_mask;
1937 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1938 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1939 if (!vmx_pt_mode_is_host_guest() ||
1940 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1941 PT_CAP_num_address_ranges)))
1944 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1946 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1948 case MSR_IA32_DEBUGCTLMSR:
1949 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
1953 msr = vmx_find_uret_msr(vmx, msr_info->index);
1955 msr_info->data = msr->data;
1958 return kvm_get_msr_common(vcpu, msr_info);
1964 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
1967 #ifdef CONFIG_X86_64
1968 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
1971 return (unsigned long)data;
1974 static u64 vcpu_supported_debugctl(struct kvm_vcpu *vcpu)
1976 u64 debugctl = vmx_supported_debugctl();
1978 if (!intel_pmu_lbr_is_enabled(vcpu))
1979 debugctl &= ~DEBUGCTLMSR_LBR_MASK;
1981 if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1982 debugctl &= ~DEBUGCTLMSR_BUS_LOCK_DETECT;
1988 * Writes msr value into the appropriate "register".
1989 * Returns 0 on success, non-0 otherwise.
1990 * Assumes vcpu_load() was already called.
1992 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1994 struct vcpu_vmx *vmx = to_vmx(vcpu);
1995 struct vmx_uret_msr *msr;
1997 u32 msr_index = msr_info->index;
1998 u64 data = msr_info->data;
2001 switch (msr_index) {
2003 ret = kvm_set_msr_common(vcpu, msr_info);
2005 #ifdef CONFIG_X86_64
2007 vmx_segment_cache_clear(vmx);
2008 vmcs_writel(GUEST_FS_BASE, data);
2011 vmx_segment_cache_clear(vmx);
2012 vmcs_writel(GUEST_GS_BASE, data);
2014 case MSR_KERNEL_GS_BASE:
2015 vmx_write_guest_kernel_gs_base(vmx, data);
2018 case MSR_IA32_SYSENTER_CS:
2019 if (is_guest_mode(vcpu))
2020 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2021 vmcs_write32(GUEST_SYSENTER_CS, data);
2023 case MSR_IA32_SYSENTER_EIP:
2024 if (is_guest_mode(vcpu)) {
2025 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2026 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2028 vmcs_writel(GUEST_SYSENTER_EIP, data);
2030 case MSR_IA32_SYSENTER_ESP:
2031 if (is_guest_mode(vcpu)) {
2032 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2033 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2035 vmcs_writel(GUEST_SYSENTER_ESP, data);
2037 case MSR_IA32_DEBUGCTLMSR: {
2038 u64 invalid = data & ~vcpu_supported_debugctl(vcpu);
2039 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2040 if (report_ignored_msrs)
2041 vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
2043 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2044 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2050 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2051 VM_EXIT_SAVE_DEBUG_CONTROLS)
2052 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2054 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2055 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2056 (data & DEBUGCTLMSR_LBR))
2057 intel_pmu_create_guest_lbr_event(vcpu);
2060 case MSR_IA32_BNDCFGS:
2061 if (!kvm_mpx_supported() ||
2062 (!msr_info->host_initiated &&
2063 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2065 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2066 (data & MSR_IA32_BNDCFGS_RSVD))
2068 vmcs_write64(GUEST_BNDCFGS, data);
2070 case MSR_IA32_UMWAIT_CONTROL:
2071 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2074 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2075 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2078 vmx->msr_ia32_umwait_control = data;
2080 case MSR_IA32_SPEC_CTRL:
2081 if (!msr_info->host_initiated &&
2082 !guest_has_spec_ctrl_msr(vcpu))
2085 if (kvm_spec_ctrl_test_value(data))
2088 vmx->spec_ctrl = data;
2094 * When it's written (to non-zero) for the first time, pass
2098 * The handling of the MSR bitmap for L2 guests is done in
2099 * nested_vmx_prepare_msr_bitmap. We should not touch the
2100 * vmcs02.msr_bitmap here since it gets completely overwritten
2101 * in the merging. We update the vmcs01 here for L1 as well
2102 * since it will end up touching the MSR anyway now.
2104 vmx_disable_intercept_for_msr(vcpu,
2108 case MSR_IA32_TSX_CTRL:
2109 if (!msr_info->host_initiated &&
2110 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2112 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2115 case MSR_IA32_PRED_CMD:
2116 if (!msr_info->host_initiated &&
2117 !guest_has_pred_cmd_msr(vcpu))
2120 if (data & ~PRED_CMD_IBPB)
2122 if (!boot_cpu_has(X86_FEATURE_IBPB))
2127 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2131 * When it's written (to non-zero) for the first time, pass
2135 * The handling of the MSR bitmap for L2 guests is done in
2136 * nested_vmx_prepare_msr_bitmap. We should not touch the
2137 * vmcs02.msr_bitmap here since it gets completely overwritten
2140 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
2142 case MSR_IA32_CR_PAT:
2143 if (!kvm_pat_valid(data))
2146 if (is_guest_mode(vcpu) &&
2147 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2148 get_vmcs12(vcpu)->guest_ia32_pat = data;
2150 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2151 vmcs_write64(GUEST_IA32_PAT, data);
2152 vcpu->arch.pat = data;
2155 ret = kvm_set_msr_common(vcpu, msr_info);
2157 case MSR_IA32_TSC_ADJUST:
2158 ret = kvm_set_msr_common(vcpu, msr_info);
2160 case MSR_IA32_MCG_EXT_CTL:
2161 if ((!msr_info->host_initiated &&
2162 !(to_vmx(vcpu)->msr_ia32_feature_control &
2163 FEAT_CTL_LMCE_ENABLED)) ||
2164 (data & ~MCG_EXT_CTL_LMCE_EN))
2166 vcpu->arch.mcg_ext_ctl = data;
2168 case MSR_IA32_FEAT_CTL:
2169 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2170 (to_vmx(vcpu)->msr_ia32_feature_control &
2171 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2173 vmx->msr_ia32_feature_control = data;
2174 if (msr_info->host_initiated && data == 0)
2175 vmx_leave_nested(vcpu);
2177 /* SGX may be enabled/disabled by guest's firmware */
2178 vmx_write_encls_bitmap(vcpu, NULL);
2180 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2182 * On real hardware, the LE hash MSRs are writable before
2183 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2184 * at which point SGX related bits in IA32_FEATURE_CONTROL
2187 * KVM does not emulate SGX activation for simplicity, so
2188 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2189 * is unlocked. This is technically not architectural
2190 * behavior, but it's close enough.
2192 if (!msr_info->host_initiated &&
2193 (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2194 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2195 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2197 vmx->msr_ia32_sgxlepubkeyhash
2198 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2200 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2201 if (!msr_info->host_initiated)
2202 return 1; /* they are read-only */
2203 if (!nested_vmx_allowed(vcpu))
2205 return vmx_set_vmx_msr(vcpu, msr_index, data);
2206 case MSR_IA32_RTIT_CTL:
2207 if (!vmx_pt_mode_is_host_guest() ||
2208 vmx_rtit_ctl_check(vcpu, data) ||
2211 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2212 vmx->pt_desc.guest.ctl = data;
2213 pt_update_intercept_for_msr(vcpu);
2215 case MSR_IA32_RTIT_STATUS:
2216 if (!pt_can_write_msr(vmx))
2218 if (data & MSR_IA32_RTIT_STATUS_MASK)
2220 vmx->pt_desc.guest.status = data;
2222 case MSR_IA32_RTIT_CR3_MATCH:
2223 if (!pt_can_write_msr(vmx))
2225 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2226 PT_CAP_cr3_filtering))
2228 vmx->pt_desc.guest.cr3_match = data;
2230 case MSR_IA32_RTIT_OUTPUT_BASE:
2231 if (!pt_can_write_msr(vmx))
2233 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2234 PT_CAP_topa_output) &&
2235 !intel_pt_validate_cap(vmx->pt_desc.caps,
2236 PT_CAP_single_range_output))
2238 if (!pt_output_base_valid(vcpu, data))
2240 vmx->pt_desc.guest.output_base = data;
2242 case MSR_IA32_RTIT_OUTPUT_MASK:
2243 if (!pt_can_write_msr(vmx))
2245 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2246 PT_CAP_topa_output) &&
2247 !intel_pt_validate_cap(vmx->pt_desc.caps,
2248 PT_CAP_single_range_output))
2250 vmx->pt_desc.guest.output_mask = data;
2252 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2253 if (!pt_can_write_msr(vmx))
2255 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2256 if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2257 PT_CAP_num_address_ranges))
2259 if (is_noncanonical_address(data, vcpu))
2262 vmx->pt_desc.guest.addr_b[index / 2] = data;
2264 vmx->pt_desc.guest.addr_a[index / 2] = data;
2266 case MSR_IA32_PERF_CAPABILITIES:
2267 if (data && !vcpu_to_pmu(vcpu)->version)
2269 if (data & PMU_CAP_LBR_FMT) {
2270 if ((data & PMU_CAP_LBR_FMT) !=
2271 (vmx_get_perf_capabilities() & PMU_CAP_LBR_FMT))
2273 if (!intel_pmu_lbr_is_compatible(vcpu))
2276 ret = kvm_set_msr_common(vcpu, msr_info);
2281 msr = vmx_find_uret_msr(vmx, msr_index);
2283 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2285 ret = kvm_set_msr_common(vcpu, msr_info);
2288 /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */
2289 if (msr_index == MSR_IA32_ARCH_CAPABILITIES)
2290 vmx_update_fb_clear_dis(vcpu, vmx);
2295 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2297 unsigned long guest_owned_bits;
2299 kvm_register_mark_available(vcpu, reg);
2303 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2306 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2308 case VCPU_EXREG_PDPTR:
2310 ept_save_pdptrs(vcpu);
2312 case VCPU_EXREG_CR0:
2313 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2315 vcpu->arch.cr0 &= ~guest_owned_bits;
2316 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2318 case VCPU_EXREG_CR3:
2320 * When intercepting CR3 loads, e.g. for shadowing paging, KVM's
2321 * CR3 is loaded into hardware, not the guest's CR3.
2323 if (!(exec_controls_get(to_vmx(vcpu)) & CPU_BASED_CR3_LOAD_EXITING))
2324 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2326 case VCPU_EXREG_CR4:
2327 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2329 vcpu->arch.cr4 &= ~guest_owned_bits;
2330 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2333 KVM_BUG_ON(1, vcpu->kvm);
2338 static __init int cpu_has_kvm_support(void)
2340 return cpu_has_vmx();
2343 static __init int vmx_disabled_by_bios(void)
2345 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2346 !boot_cpu_has(X86_FEATURE_VMX);
2349 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2353 cr4_set_bits(X86_CR4_VMXE);
2355 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2356 _ASM_EXTABLE(1b, %l[fault])
2357 : : [vmxon_pointer] "m"(vmxon_pointer)
2362 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2363 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2364 cr4_clear_bits(X86_CR4_VMXE);
2369 static int hardware_enable(void)
2371 int cpu = raw_smp_processor_id();
2372 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2375 if (cr4_read_shadow() & X86_CR4_VMXE)
2379 * This can happen if we hot-added a CPU but failed to allocate
2380 * VP assist page for it.
2382 if (static_branch_unlikely(&enable_evmcs) &&
2383 !hv_get_vp_assist_page(cpu))
2386 intel_pt_handle_vmx(1);
2388 r = kvm_cpu_vmxon(phys_addr);
2390 intel_pt_handle_vmx(0);
2400 static void vmclear_local_loaded_vmcss(void)
2402 int cpu = raw_smp_processor_id();
2403 struct loaded_vmcs *v, *n;
2405 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2406 loaded_vmcss_on_cpu_link)
2407 __loaded_vmcs_clear(v);
2410 static void hardware_disable(void)
2412 vmclear_local_loaded_vmcss();
2415 kvm_spurious_fault();
2417 intel_pt_handle_vmx(0);
2421 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2422 * directly instead of going through cpu_has(), to ensure KVM is trapping
2423 * ENCLS whenever it's supported in hardware. It does not matter whether
2424 * the host OS supports or has enabled SGX.
2426 static bool cpu_has_sgx(void)
2428 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2431 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2432 u32 msr, u32 *result)
2434 u32 vmx_msr_low, vmx_msr_high;
2435 u32 ctl = ctl_min | ctl_opt;
2437 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2439 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2440 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2442 /* Ensure minimum (required) set of control bits are supported. */
2450 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2451 struct vmx_capability *vmx_cap)
2453 u32 vmx_msr_low, vmx_msr_high;
2454 u32 min, opt, min2, opt2;
2455 u32 _pin_based_exec_control = 0;
2456 u32 _cpu_based_exec_control = 0;
2457 u32 _cpu_based_2nd_exec_control = 0;
2458 u32 _vmexit_control = 0;
2459 u32 _vmentry_control = 0;
2461 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2462 min = CPU_BASED_HLT_EXITING |
2463 #ifdef CONFIG_X86_64
2464 CPU_BASED_CR8_LOAD_EXITING |
2465 CPU_BASED_CR8_STORE_EXITING |
2467 CPU_BASED_CR3_LOAD_EXITING |
2468 CPU_BASED_CR3_STORE_EXITING |
2469 CPU_BASED_UNCOND_IO_EXITING |
2470 CPU_BASED_MOV_DR_EXITING |
2471 CPU_BASED_USE_TSC_OFFSETTING |
2472 CPU_BASED_MWAIT_EXITING |
2473 CPU_BASED_MONITOR_EXITING |
2474 CPU_BASED_INVLPG_EXITING |
2475 CPU_BASED_RDPMC_EXITING;
2477 opt = CPU_BASED_TPR_SHADOW |
2478 CPU_BASED_USE_MSR_BITMAPS |
2479 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2480 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2481 &_cpu_based_exec_control) < 0)
2483 #ifdef CONFIG_X86_64
2484 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2485 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2486 ~CPU_BASED_CR8_STORE_EXITING;
2488 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2490 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2491 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2492 SECONDARY_EXEC_WBINVD_EXITING |
2493 SECONDARY_EXEC_ENABLE_VPID |
2494 SECONDARY_EXEC_ENABLE_EPT |
2495 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2496 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2497 SECONDARY_EXEC_DESC |
2498 SECONDARY_EXEC_ENABLE_RDTSCP |
2499 SECONDARY_EXEC_ENABLE_INVPCID |
2500 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2501 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2502 SECONDARY_EXEC_SHADOW_VMCS |
2503 SECONDARY_EXEC_XSAVES |
2504 SECONDARY_EXEC_RDSEED_EXITING |
2505 SECONDARY_EXEC_RDRAND_EXITING |
2506 SECONDARY_EXEC_ENABLE_PML |
2507 SECONDARY_EXEC_TSC_SCALING |
2508 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2509 SECONDARY_EXEC_PT_USE_GPA |
2510 SECONDARY_EXEC_PT_CONCEAL_VMX |
2511 SECONDARY_EXEC_ENABLE_VMFUNC |
2512 SECONDARY_EXEC_BUS_LOCK_DETECTION;
2514 opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2515 if (adjust_vmx_controls(min2, opt2,
2516 MSR_IA32_VMX_PROCBASED_CTLS2,
2517 &_cpu_based_2nd_exec_control) < 0)
2520 #ifndef CONFIG_X86_64
2521 if (!(_cpu_based_2nd_exec_control &
2522 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2523 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2526 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2527 _cpu_based_2nd_exec_control &= ~(
2528 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2529 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2530 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2532 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2533 &vmx_cap->ept, &vmx_cap->vpid);
2535 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2536 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2538 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2539 CPU_BASED_CR3_STORE_EXITING |
2540 CPU_BASED_INVLPG_EXITING);
2541 } else if (vmx_cap->ept) {
2543 pr_warn_once("EPT CAP should not exist if not support "
2544 "1-setting enable EPT VM-execution control\n");
2546 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2549 pr_warn_once("VPID CAP should not exist if not support "
2550 "1-setting enable VPID VM-execution control\n");
2553 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2554 #ifdef CONFIG_X86_64
2555 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2557 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2558 VM_EXIT_LOAD_IA32_PAT |
2559 VM_EXIT_LOAD_IA32_EFER |
2560 VM_EXIT_CLEAR_BNDCFGS |
2561 VM_EXIT_PT_CONCEAL_PIP |
2562 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2563 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2564 &_vmexit_control) < 0)
2567 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2568 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2569 PIN_BASED_VMX_PREEMPTION_TIMER;
2570 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2571 &_pin_based_exec_control) < 0)
2574 if (cpu_has_broken_vmx_preemption_timer())
2575 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2576 if (!(_cpu_based_2nd_exec_control &
2577 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2578 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2580 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2581 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2582 VM_ENTRY_LOAD_IA32_PAT |
2583 VM_ENTRY_LOAD_IA32_EFER |
2584 VM_ENTRY_LOAD_BNDCFGS |
2585 VM_ENTRY_PT_CONCEAL_PIP |
2586 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2587 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2588 &_vmentry_control) < 0)
2592 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2593 * can't be used due to an errata where VM Exit may incorrectly clear
2594 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2595 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2597 if (boot_cpu_data.x86 == 0x6) {
2598 switch (boot_cpu_data.x86_model) {
2599 case 26: /* AAK155 */
2600 case 30: /* AAP115 */
2601 case 37: /* AAT100 */
2602 case 44: /* BC86,AAY89,BD102 */
2604 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2605 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2606 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2607 "does not work properly. Using workaround\n");
2615 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2617 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2618 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2621 #ifdef CONFIG_X86_64
2622 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2623 if (vmx_msr_high & (1u<<16))
2627 /* Require Write-Back (WB) memory type for VMCS accesses. */
2628 if (((vmx_msr_high >> 18) & 15) != 6)
2631 vmcs_conf->size = vmx_msr_high & 0x1fff;
2632 vmcs_conf->order = get_order(vmcs_conf->size);
2633 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2635 vmcs_conf->revision_id = vmx_msr_low;
2637 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2638 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2639 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2640 vmcs_conf->vmexit_ctrl = _vmexit_control;
2641 vmcs_conf->vmentry_ctrl = _vmentry_control;
2643 #if IS_ENABLED(CONFIG_HYPERV)
2644 if (enlightened_vmcs)
2645 evmcs_sanitize_exec_ctrls(vmcs_conf);
2651 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2653 int node = cpu_to_node(cpu);
2657 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2660 vmcs = page_address(pages);
2661 memset(vmcs, 0, vmcs_config.size);
2663 /* KVM supports Enlightened VMCS v1 only */
2664 if (static_branch_unlikely(&enable_evmcs))
2665 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2667 vmcs->hdr.revision_id = vmcs_config.revision_id;
2670 vmcs->hdr.shadow_vmcs = 1;
2674 void free_vmcs(struct vmcs *vmcs)
2676 free_pages((unsigned long)vmcs, vmcs_config.order);
2680 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2682 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2684 if (!loaded_vmcs->vmcs)
2686 loaded_vmcs_clear(loaded_vmcs);
2687 free_vmcs(loaded_vmcs->vmcs);
2688 loaded_vmcs->vmcs = NULL;
2689 if (loaded_vmcs->msr_bitmap)
2690 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2691 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2694 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2696 loaded_vmcs->vmcs = alloc_vmcs(false);
2697 if (!loaded_vmcs->vmcs)
2700 vmcs_clear(loaded_vmcs->vmcs);
2702 loaded_vmcs->shadow_vmcs = NULL;
2703 loaded_vmcs->hv_timer_soft_disabled = false;
2704 loaded_vmcs->cpu = -1;
2705 loaded_vmcs->launched = 0;
2707 if (cpu_has_vmx_msr_bitmap()) {
2708 loaded_vmcs->msr_bitmap = (unsigned long *)
2709 __get_free_page(GFP_KERNEL_ACCOUNT);
2710 if (!loaded_vmcs->msr_bitmap)
2712 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2714 if (IS_ENABLED(CONFIG_HYPERV) &&
2715 static_branch_unlikely(&enable_evmcs) &&
2716 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2717 struct hv_enlightened_vmcs *evmcs =
2718 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2720 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2724 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2725 memset(&loaded_vmcs->controls_shadow, 0,
2726 sizeof(struct vmcs_controls_shadow));
2731 free_loaded_vmcs(loaded_vmcs);
2735 static void free_kvm_area(void)
2739 for_each_possible_cpu(cpu) {
2740 free_vmcs(per_cpu(vmxarea, cpu));
2741 per_cpu(vmxarea, cpu) = NULL;
2745 static __init int alloc_kvm_area(void)
2749 for_each_possible_cpu(cpu) {
2752 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2759 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2760 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2761 * revision_id reported by MSR_IA32_VMX_BASIC.
2763 * However, even though not explicitly documented by
2764 * TLFS, VMXArea passed as VMXON argument should
2765 * still be marked with revision_id reported by
2768 if (static_branch_unlikely(&enable_evmcs))
2769 vmcs->hdr.revision_id = vmcs_config.revision_id;
2771 per_cpu(vmxarea, cpu) = vmcs;
2776 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2777 struct kvm_segment *save)
2779 if (!emulate_invalid_guest_state) {
2781 * CS and SS RPL should be equal during guest entry according
2782 * to VMX spec, but in reality it is not always so. Since vcpu
2783 * is in the middle of the transition from real mode to
2784 * protected mode it is safe to assume that RPL 0 is a good
2787 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2788 save->selector &= ~SEGMENT_RPL_MASK;
2789 save->dpl = save->selector & SEGMENT_RPL_MASK;
2792 __vmx_set_segment(vcpu, save, seg);
2795 static void enter_pmode(struct kvm_vcpu *vcpu)
2797 unsigned long flags;
2798 struct vcpu_vmx *vmx = to_vmx(vcpu);
2801 * Update real mode segment cache. It may be not up-to-date if segment
2802 * register was written while vcpu was in a guest mode.
2804 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2805 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2806 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2807 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2808 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2809 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2811 vmx->rmode.vm86_active = 0;
2813 __vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2815 flags = vmcs_readl(GUEST_RFLAGS);
2816 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2817 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2818 vmcs_writel(GUEST_RFLAGS, flags);
2820 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2821 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2823 vmx_update_exception_bitmap(vcpu);
2825 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2826 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2827 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2828 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2829 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2830 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2833 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2835 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2836 struct kvm_segment var = *save;
2839 if (seg == VCPU_SREG_CS)
2842 if (!emulate_invalid_guest_state) {
2843 var.selector = var.base >> 4;
2844 var.base = var.base & 0xffff0;
2854 if (save->base & 0xf)
2855 printk_once(KERN_WARNING "kvm: segment base is not "
2856 "paragraph aligned when entering "
2857 "protected mode (seg=%d)", seg);
2860 vmcs_write16(sf->selector, var.selector);
2861 vmcs_writel(sf->base, var.base);
2862 vmcs_write32(sf->limit, var.limit);
2863 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2866 static void enter_rmode(struct kvm_vcpu *vcpu)
2868 unsigned long flags;
2869 struct vcpu_vmx *vmx = to_vmx(vcpu);
2870 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2872 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2873 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2874 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2875 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2876 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2877 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2878 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2880 vmx->rmode.vm86_active = 1;
2883 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2884 * vcpu. Warn the user that an update is overdue.
2886 if (!kvm_vmx->tss_addr)
2887 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2888 "called before entering vcpu\n");
2890 vmx_segment_cache_clear(vmx);
2892 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2893 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2894 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2896 flags = vmcs_readl(GUEST_RFLAGS);
2897 vmx->rmode.save_rflags = flags;
2899 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2901 vmcs_writel(GUEST_RFLAGS, flags);
2902 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2903 vmx_update_exception_bitmap(vcpu);
2905 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2906 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2907 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2908 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2909 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2910 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2913 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2915 struct vcpu_vmx *vmx = to_vmx(vcpu);
2916 struct vmx_uret_msr *msr = vmx_find_uret_msr(vmx, MSR_EFER);
2918 /* Nothing to do if hardware doesn't support EFER. */
2922 vcpu->arch.efer = efer;
2923 if (efer & EFER_LMA) {
2924 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2927 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2929 msr->data = efer & ~EFER_LME;
2931 vmx_setup_uret_msrs(vmx);
2935 #ifdef CONFIG_X86_64
2937 static void enter_lmode(struct kvm_vcpu *vcpu)
2941 vmx_segment_cache_clear(to_vmx(vcpu));
2943 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2944 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2945 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2947 vmcs_write32(GUEST_TR_AR_BYTES,
2948 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2949 | VMX_AR_TYPE_BUSY_64_TSS);
2951 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2954 static void exit_lmode(struct kvm_vcpu *vcpu)
2956 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2957 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2962 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
2964 struct vcpu_vmx *vmx = to_vmx(vcpu);
2967 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
2968 * the CPU is not required to invalidate guest-physical mappings on
2969 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
2970 * associated with the root EPT structure and not any particular VPID
2971 * (INVVPID also isn't required to invalidate guest-physical mappings).
2975 } else if (enable_vpid) {
2976 if (cpu_has_vmx_invvpid_global()) {
2977 vpid_sync_vcpu_global();
2979 vpid_sync_vcpu_single(vmx->vpid);
2980 vpid_sync_vcpu_single(vmx->nested.vpid02);
2985 static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu)
2987 if (is_guest_mode(vcpu))
2988 return nested_get_vpid02(vcpu);
2989 return to_vmx(vcpu)->vpid;
2992 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
2994 struct kvm_mmu *mmu = vcpu->arch.mmu;
2995 u64 root_hpa = mmu->root_hpa;
2997 /* No flush required if the current context is invalid. */
2998 if (!VALID_PAGE(root_hpa))
3002 ept_sync_context(construct_eptp(vcpu, root_hpa,
3003 mmu->shadow_root_level));
3005 vpid_sync_context(vmx_get_current_vpid(vcpu));
3008 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3011 * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in
3012 * vmx_flush_tlb_guest() for an explanation of why this is ok.
3014 vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
3017 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3020 * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
3021 * vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit are
3022 * required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3023 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3024 * i.e. no explicit INVVPID is necessary.
3026 vpid_sync_context(vmx_get_current_vpid(vcpu));
3029 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3031 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3033 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3036 if (is_pae_paging(vcpu)) {
3037 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3038 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3039 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3040 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3044 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3046 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3048 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3051 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3052 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3053 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3054 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3056 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
3059 #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \
3060 CPU_BASED_CR3_STORE_EXITING)
3062 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3064 struct vcpu_vmx *vmx = to_vmx(vcpu);
3065 unsigned long hw_cr0, old_cr0_pg;
3068 old_cr0_pg = kvm_read_cr0_bits(vcpu, X86_CR0_PG);
3070 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3071 if (is_unrestricted_guest(vcpu))
3072 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3074 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3076 hw_cr0 |= X86_CR0_WP;
3078 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3081 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3085 vmcs_writel(CR0_READ_SHADOW, cr0);
3086 vmcs_writel(GUEST_CR0, hw_cr0);
3087 vcpu->arch.cr0 = cr0;
3088 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3090 #ifdef CONFIG_X86_64
3091 if (vcpu->arch.efer & EFER_LME) {
3092 if (!old_cr0_pg && (cr0 & X86_CR0_PG))
3094 else if (old_cr0_pg && !(cr0 & X86_CR0_PG))
3099 if (enable_ept && !is_unrestricted_guest(vcpu)) {
3101 * Ensure KVM has an up-to-date snapshot of the guest's CR3. If
3102 * the below code _enables_ CR3 exiting, vmx_cache_reg() will
3103 * (correctly) stop reading vmcs.GUEST_CR3 because it thinks
3104 * KVM's CR3 is installed.
3106 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3107 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3110 * When running with EPT but not unrestricted guest, KVM must
3111 * intercept CR3 accesses when paging is _disabled_. This is
3112 * necessary because restricted guests can't actually run with
3113 * paging disabled, and so KVM stuffs its own CR3 in order to
3114 * run the guest when identity mapped page tables.
3116 * Do _NOT_ check the old CR0.PG, e.g. to optimize away the
3117 * update, it may be stale with respect to CR3 interception,
3118 * e.g. after nested VM-Enter.
3120 * Lastly, honor L1's desires, i.e. intercept CR3 loads and/or
3121 * stores to forward them to L1, even if KVM does not need to
3122 * intercept them to preserve its identity mapped page tables.
3124 if (!(cr0 & X86_CR0_PG)) {
3125 exec_controls_setbit(vmx, CR3_EXITING_BITS);
3126 } else if (!is_guest_mode(vcpu)) {
3127 exec_controls_clearbit(vmx, CR3_EXITING_BITS);
3129 tmp = exec_controls_get(vmx);
3130 tmp &= ~CR3_EXITING_BITS;
3131 tmp |= get_vmcs12(vcpu)->cpu_based_vm_exec_control & CR3_EXITING_BITS;
3132 exec_controls_set(vmx, tmp);
3135 /* Note, vmx_set_cr4() consumes the new vcpu->arch.cr0. */
3136 if ((old_cr0_pg ^ cr0) & X86_CR0_PG)
3137 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3140 /* depends on vcpu->arch.cr0 to be set to a new value */
3141 vmx->emulation_required = vmx_emulation_required(vcpu);
3144 static int vmx_get_max_tdp_level(void)
3146 if (cpu_has_vmx_ept_5levels())
3151 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3153 u64 eptp = VMX_EPTP_MT_WB;
3155 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3157 if (enable_ept_ad_bits &&
3158 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3159 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3165 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3168 struct kvm *kvm = vcpu->kvm;
3169 bool update_guest_cr3 = true;
3170 unsigned long guest_cr3;
3174 eptp = construct_eptp(vcpu, root_hpa, root_level);
3175 vmcs_write64(EPT_POINTER, eptp);
3177 hv_track_root_tdp(vcpu, root_hpa);
3179 if (!enable_unrestricted_guest && !is_paging(vcpu))
3180 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3181 else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3182 guest_cr3 = vcpu->arch.cr3;
3183 else /* vmcs01.GUEST_CR3 is already up-to-date. */
3184 update_guest_cr3 = false;
3185 vmx_ept_load_pdptrs(vcpu);
3187 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3190 if (update_guest_cr3)
3191 vmcs_writel(GUEST_CR3, guest_cr3);
3194 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3197 * We operate under the default treatment of SMM, so VMX cannot be
3198 * enabled under SMM. Note, whether or not VMXE is allowed at all is
3199 * handled by kvm_is_valid_cr4().
3201 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3204 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3210 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3212 unsigned long old_cr4 = vcpu->arch.cr4;
3213 struct vcpu_vmx *vmx = to_vmx(vcpu);
3215 * Pass through host's Machine Check Enable value to hw_cr4, which
3216 * is in force while we are in guest mode. Do not let guests control
3217 * this bit, even if host CR4.MCE == 0.
3219 unsigned long hw_cr4;
3221 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3222 if (is_unrestricted_guest(vcpu))
3223 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3224 else if (vmx->rmode.vm86_active)
3225 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3227 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3229 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3230 if (cr4 & X86_CR4_UMIP) {
3231 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3232 hw_cr4 &= ~X86_CR4_UMIP;
3233 } else if (!is_guest_mode(vcpu) ||
3234 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3235 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3239 vcpu->arch.cr4 = cr4;
3240 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3242 if (!is_unrestricted_guest(vcpu)) {
3244 if (!is_paging(vcpu)) {
3245 hw_cr4 &= ~X86_CR4_PAE;
3246 hw_cr4 |= X86_CR4_PSE;
3247 } else if (!(cr4 & X86_CR4_PAE)) {
3248 hw_cr4 &= ~X86_CR4_PAE;
3253 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3254 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3255 * to be manually disabled when guest switches to non-paging
3258 * If !enable_unrestricted_guest, the CPU is always running
3259 * with CR0.PG=1 and CR4 needs to be modified.
3260 * If enable_unrestricted_guest, the CPU automatically
3261 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3263 if (!is_paging(vcpu))
3264 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3267 vmcs_writel(CR4_READ_SHADOW, cr4);
3268 vmcs_writel(GUEST_CR4, hw_cr4);
3270 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3271 kvm_update_cpuid_runtime(vcpu);
3274 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3276 struct vcpu_vmx *vmx = to_vmx(vcpu);
3279 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3280 *var = vmx->rmode.segs[seg];
3281 if (seg == VCPU_SREG_TR
3282 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3284 var->base = vmx_read_guest_seg_base(vmx, seg);
3285 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3288 var->base = vmx_read_guest_seg_base(vmx, seg);
3289 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3290 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3291 ar = vmx_read_guest_seg_ar(vmx, seg);
3292 var->unusable = (ar >> 16) & 1;
3293 var->type = ar & 15;
3294 var->s = (ar >> 4) & 1;
3295 var->dpl = (ar >> 5) & 3;
3297 * Some userspaces do not preserve unusable property. Since usable
3298 * segment has to be present according to VMX spec we can use present
3299 * property to amend userspace bug by making unusable segment always
3300 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3301 * segment as unusable.
3303 var->present = !var->unusable;
3304 var->avl = (ar >> 12) & 1;
3305 var->l = (ar >> 13) & 1;
3306 var->db = (ar >> 14) & 1;
3307 var->g = (ar >> 15) & 1;
3310 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3312 struct kvm_segment s;
3314 if (to_vmx(vcpu)->rmode.vm86_active) {
3315 vmx_get_segment(vcpu, &s, seg);
3318 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3321 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3323 struct vcpu_vmx *vmx = to_vmx(vcpu);
3325 if (unlikely(vmx->rmode.vm86_active))
3328 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3329 return VMX_AR_DPL(ar);
3333 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3337 if (var->unusable || !var->present)
3340 ar = var->type & 15;
3341 ar |= (var->s & 1) << 4;
3342 ar |= (var->dpl & 3) << 5;
3343 ar |= (var->present & 1) << 7;
3344 ar |= (var->avl & 1) << 12;
3345 ar |= (var->l & 1) << 13;
3346 ar |= (var->db & 1) << 14;
3347 ar |= (var->g & 1) << 15;
3353 void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3355 struct vcpu_vmx *vmx = to_vmx(vcpu);
3356 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3358 vmx_segment_cache_clear(vmx);
3360 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3361 vmx->rmode.segs[seg] = *var;
3362 if (seg == VCPU_SREG_TR)
3363 vmcs_write16(sf->selector, var->selector);
3365 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3369 vmcs_writel(sf->base, var->base);
3370 vmcs_write32(sf->limit, var->limit);
3371 vmcs_write16(sf->selector, var->selector);
3374 * Fix the "Accessed" bit in AR field of segment registers for older
3376 * IA32 arch specifies that at the time of processor reset the
3377 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3378 * is setting it to 0 in the userland code. This causes invalid guest
3379 * state vmexit when "unrestricted guest" mode is turned on.
3380 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3381 * tree. Newer qemu binaries with that qemu fix would not need this
3384 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3385 var->type |= 0x1; /* Accessed */
3387 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3390 static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3392 __vmx_set_segment(vcpu, var, seg);
3394 to_vmx(vcpu)->emulation_required = vmx_emulation_required(vcpu);
3397 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3399 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3401 *db = (ar >> 14) & 1;
3402 *l = (ar >> 13) & 1;
3405 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3407 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3408 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3411 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3413 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3414 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3417 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3419 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3420 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3423 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3425 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3426 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3429 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3431 struct kvm_segment var;
3434 vmx_get_segment(vcpu, &var, seg);
3436 if (seg == VCPU_SREG_CS)
3438 ar = vmx_segment_access_rights(&var);
3440 if (var.base != (var.selector << 4))
3442 if (var.limit != 0xffff)
3450 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3452 struct kvm_segment cs;
3453 unsigned int cs_rpl;
3455 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3456 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3460 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3464 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3465 if (cs.dpl > cs_rpl)
3468 if (cs.dpl != cs_rpl)
3474 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3478 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3480 struct kvm_segment ss;
3481 unsigned int ss_rpl;
3483 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3484 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3488 if (ss.type != 3 && ss.type != 7)
3492 if (ss.dpl != ss_rpl) /* DPL != RPL */
3500 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3502 struct kvm_segment var;
3505 vmx_get_segment(vcpu, &var, seg);
3506 rpl = var.selector & SEGMENT_RPL_MASK;
3514 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3515 if (var.dpl < rpl) /* DPL < RPL */
3519 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3525 static bool tr_valid(struct kvm_vcpu *vcpu)
3527 struct kvm_segment tr;
3529 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3533 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3535 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3543 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3545 struct kvm_segment ldtr;
3547 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3551 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3561 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3563 struct kvm_segment cs, ss;
3565 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3566 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3568 return ((cs.selector & SEGMENT_RPL_MASK) ==
3569 (ss.selector & SEGMENT_RPL_MASK));
3573 * Check if guest state is valid. Returns true if valid, false if
3575 * We assume that registers are always usable
3577 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3579 /* real mode guest state checks */
3580 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3581 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3583 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3585 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3587 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3589 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3591 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3594 /* protected mode guest state checks */
3595 if (!cs_ss_rpl_check(vcpu))
3597 if (!code_segment_valid(vcpu))
3599 if (!stack_segment_valid(vcpu))
3601 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3603 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3605 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3607 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3609 if (!tr_valid(vcpu))
3611 if (!ldtr_valid(vcpu))
3615 * - Add checks on RIP
3616 * - Add checks on RFLAGS
3622 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3624 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3628 for (i = 0; i < 3; i++) {
3629 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3633 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3634 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3638 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3644 static int init_rmode_identity_map(struct kvm *kvm)
3646 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3651 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3652 mutex_lock(&kvm->slots_lock);
3654 if (likely(kvm_vmx->ept_identity_pagetable_done))
3657 if (!kvm_vmx->ept_identity_map_addr)
3658 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3660 uaddr = __x86_set_memory_region(kvm,
3661 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3662 kvm_vmx->ept_identity_map_addr,
3664 if (IS_ERR(uaddr)) {
3669 /* Set up identity-mapping pagetable for EPT in real mode */
3670 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3671 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3672 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3673 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3678 kvm_vmx->ept_identity_pagetable_done = true;
3681 mutex_unlock(&kvm->slots_lock);
3685 static void seg_setup(int seg)
3687 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3690 vmcs_write16(sf->selector, 0);
3691 vmcs_writel(sf->base, 0);
3692 vmcs_write32(sf->limit, 0xffff);
3694 if (seg == VCPU_SREG_CS)
3695 ar |= 0x08; /* code segment */
3697 vmcs_write32(sf->ar_bytes, ar);
3700 static int alloc_apic_access_page(struct kvm *kvm)
3706 mutex_lock(&kvm->slots_lock);
3707 if (kvm->arch.apic_access_memslot_enabled)
3709 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3710 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3716 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3717 if (is_error_page(page)) {
3723 * Do not pin the page in memory, so that memory hot-unplug
3724 * is able to migrate it.
3727 kvm->arch.apic_access_memslot_enabled = true;
3729 mutex_unlock(&kvm->slots_lock);
3733 int allocate_vpid(void)
3739 spin_lock(&vmx_vpid_lock);
3740 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3741 if (vpid < VMX_NR_VPIDS)
3742 __set_bit(vpid, vmx_vpid_bitmap);
3745 spin_unlock(&vmx_vpid_lock);
3749 void free_vpid(int vpid)
3751 if (!enable_vpid || vpid == 0)
3753 spin_lock(&vmx_vpid_lock);
3754 __clear_bit(vpid, vmx_vpid_bitmap);
3755 spin_unlock(&vmx_vpid_lock);
3758 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3760 struct vcpu_vmx *vmx = to_vmx(vcpu);
3761 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3763 if (!cpu_has_vmx_msr_bitmap())
3766 if (static_branch_unlikely(&enable_evmcs))
3767 evmcs_touch_msr_bitmap();
3770 * Mark the desired intercept state in shadow bitmap, this is needed
3771 * for resync when the MSR filters change.
3773 if (is_valid_passthrough_msr(msr)) {
3774 int idx = possible_passthrough_msr_slot(msr);
3776 if (idx != -ENOENT) {
3777 if (type & MSR_TYPE_R)
3778 clear_bit(idx, vmx->shadow_msr_intercept.read);
3779 if (type & MSR_TYPE_W)
3780 clear_bit(idx, vmx->shadow_msr_intercept.write);
3784 if ((type & MSR_TYPE_R) &&
3785 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3786 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3787 type &= ~MSR_TYPE_R;
3790 if ((type & MSR_TYPE_W) &&
3791 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3792 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3793 type &= ~MSR_TYPE_W;
3796 if (type & MSR_TYPE_R)
3797 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3799 if (type & MSR_TYPE_W)
3800 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3803 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3805 struct vcpu_vmx *vmx = to_vmx(vcpu);
3806 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3808 if (!cpu_has_vmx_msr_bitmap())
3811 if (static_branch_unlikely(&enable_evmcs))
3812 evmcs_touch_msr_bitmap();
3815 * Mark the desired intercept state in shadow bitmap, this is needed
3816 * for resync when the MSR filter changes.
3818 if (is_valid_passthrough_msr(msr)) {
3819 int idx = possible_passthrough_msr_slot(msr);
3821 if (idx != -ENOENT) {
3822 if (type & MSR_TYPE_R)
3823 set_bit(idx, vmx->shadow_msr_intercept.read);
3824 if (type & MSR_TYPE_W)
3825 set_bit(idx, vmx->shadow_msr_intercept.write);
3829 if (type & MSR_TYPE_R)
3830 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3832 if (type & MSR_TYPE_W)
3833 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3836 static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
3838 unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3839 unsigned long read_intercept;
3842 read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3844 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3845 unsigned int read_idx = msr / BITS_PER_LONG;
3846 unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3848 msr_bitmap[read_idx] = read_intercept;
3849 msr_bitmap[write_idx] = ~0ul;
3853 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu)
3855 struct vcpu_vmx *vmx = to_vmx(vcpu);
3858 if (!cpu_has_vmx_msr_bitmap())
3861 if (cpu_has_secondary_exec_ctrls() &&
3862 (secondary_exec_controls_get(vmx) &
3863 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3864 mode = MSR_BITMAP_MODE_X2APIC;
3865 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3866 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3871 if (mode == vmx->x2apic_msr_bitmap_mode)
3874 vmx->x2apic_msr_bitmap_mode = mode;
3876 vmx_reset_x2apic_msrs(vcpu, mode);
3879 * TPR reads and writes can be virtualized even if virtual interrupt
3880 * delivery is not in use.
3882 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
3883 !(mode & MSR_BITMAP_MODE_X2APIC));
3885 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3886 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
3887 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3888 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3892 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
3894 struct vcpu_vmx *vmx = to_vmx(vcpu);
3895 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3898 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
3899 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
3900 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
3901 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
3902 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3903 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3904 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3908 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3910 struct vcpu_vmx *vmx = to_vmx(vcpu);
3915 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3916 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3917 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3920 rvi = vmx_get_rvi();
3922 vapic_page = vmx->nested.virtual_apic_map.hva;
3923 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3925 return ((rvi & 0xf0) > (vppr & 0xf0));
3928 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
3930 struct vcpu_vmx *vmx = to_vmx(vcpu);
3934 * Set intercept permissions for all potentially passed through MSRs
3935 * again. They will automatically get filtered through the MSR filter,
3936 * so we are back in sync after this.
3938 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
3939 u32 msr = vmx_possible_passthrough_msrs[i];
3940 bool read = test_bit(i, vmx->shadow_msr_intercept.read);
3941 bool write = test_bit(i, vmx->shadow_msr_intercept.write);
3943 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_R, read);
3944 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_W, write);
3947 pt_update_intercept_for_msr(vcpu);
3950 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3954 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3956 if (vcpu->mode == IN_GUEST_MODE) {
3958 * The vector of interrupt to be delivered to vcpu had
3959 * been set in PIR before this function.
3961 * Following cases will be reached in this block, and
3962 * we always send a notification event in all cases as
3965 * Case 1: vcpu keeps in non-root mode. Sending a
3966 * notification event posts the interrupt to vcpu.
3968 * Case 2: vcpu exits to root mode and is still
3969 * runnable. PIR will be synced to vIRR before the
3970 * next vcpu entry. Sending a notification event in
3971 * this case has no effect, as vcpu is not in root
3974 * Case 3: vcpu exits to root mode and is blocked.
3975 * vcpu_block() has already synced PIR to vIRR and
3976 * never blocks vcpu if vIRR is not cleared. Therefore,
3977 * a blocked vcpu here does not wait for any requested
3978 * interrupts in PIR, and sending a notification event
3979 * which has no effect is safe here.
3982 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3989 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3992 struct vcpu_vmx *vmx = to_vmx(vcpu);
3994 if (is_guest_mode(vcpu) &&
3995 vector == vmx->nested.posted_intr_nv) {
3997 * If a posted intr is not recognized by hardware,
3998 * we will accomplish it in the next vmentry.
4000 vmx->nested.pi_pending = true;
4001 kvm_make_request(KVM_REQ_EVENT, vcpu);
4002 /* the PIR and ON have been set by L1. */
4003 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
4004 kvm_vcpu_kick(vcpu);
4010 * Send interrupt to vcpu via posted interrupt way.
4011 * 1. If target vcpu is running(non-root mode), send posted interrupt
4012 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4013 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4014 * interrupt from PIR in next vmentry.
4016 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4018 struct vcpu_vmx *vmx = to_vmx(vcpu);
4021 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4025 if (!vcpu->arch.apicv_active)
4028 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4031 /* If a previous notification has sent the IPI, nothing to do. */
4032 if (pi_test_and_set_on(&vmx->pi_desc))
4035 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
4036 kvm_vcpu_kick(vcpu);
4042 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4043 * will not change in the lifetime of the guest.
4044 * Note that host-state that does change is set elsewhere. E.g., host-state
4045 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4047 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4051 unsigned long cr0, cr3, cr4;
4054 WARN_ON(cr0 & X86_CR0_TS);
4055 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4058 * Save the most likely value for this task's CR3 in the VMCS.
4059 * We can't use __get_current_cr3_fast() because we're not atomic.
4062 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4063 vmx->loaded_vmcs->host_state.cr3 = cr3;
4065 /* Save the most likely value for this task's CR4 in the VMCS. */
4066 cr4 = cr4_read_shadow();
4067 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4068 vmx->loaded_vmcs->host_state.cr4 = cr4;
4070 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4071 #ifdef CONFIG_X86_64
4073 * Load null selectors, so we can avoid reloading them in
4074 * vmx_prepare_switch_to_host(), in case userspace uses
4075 * the null selectors too (the expected case).
4077 vmcs_write16(HOST_DS_SELECTOR, 0);
4078 vmcs_write16(HOST_ES_SELECTOR, 0);
4080 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4081 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4083 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4084 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4086 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4088 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4090 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4091 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4092 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4093 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4095 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4096 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4097 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4100 if (cpu_has_load_ia32_efer())
4101 vmcs_write64(HOST_IA32_EFER, host_efer);
4104 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4106 struct kvm_vcpu *vcpu = &vmx->vcpu;
4108 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4109 ~vcpu->arch.cr4_guest_rsvd_bits;
4111 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PGE;
4112 if (is_guest_mode(&vmx->vcpu))
4113 vcpu->arch.cr4_guest_owned_bits &=
4114 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4115 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4118 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4120 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4122 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4123 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4126 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4128 if (!enable_preemption_timer)
4129 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4131 return pin_based_exec_ctrl;
4134 static u32 vmx_vmentry_ctrl(void)
4136 u32 vmentry_ctrl = vmcs_config.vmentry_ctrl;
4138 if (vmx_pt_mode_is_system())
4139 vmentry_ctrl &= ~(VM_ENTRY_PT_CONCEAL_PIP |
4140 VM_ENTRY_LOAD_IA32_RTIT_CTL);
4141 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
4142 return vmentry_ctrl &
4143 ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL | VM_ENTRY_LOAD_IA32_EFER);
4146 static u32 vmx_vmexit_ctrl(void)
4148 u32 vmexit_ctrl = vmcs_config.vmexit_ctrl;
4150 if (vmx_pt_mode_is_system())
4151 vmexit_ctrl &= ~(VM_EXIT_PT_CONCEAL_PIP |
4152 VM_EXIT_CLEAR_IA32_RTIT_CTL);
4153 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
4154 return vmexit_ctrl &
4155 ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
4158 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4160 struct vcpu_vmx *vmx = to_vmx(vcpu);
4162 if (is_guest_mode(vcpu)) {
4163 vmx->nested.update_vmcs01_apicv_status = true;
4167 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4168 if (cpu_has_secondary_exec_ctrls()) {
4169 if (kvm_vcpu_apicv_active(vcpu))
4170 secondary_exec_controls_setbit(vmx,
4171 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4172 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4174 secondary_exec_controls_clearbit(vmx,
4175 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4176 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4179 vmx_update_msr_bitmap_x2apic(vcpu);
4182 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4184 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4186 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4187 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4189 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4190 exec_control &= ~CPU_BASED_TPR_SHADOW;
4191 #ifdef CONFIG_X86_64
4192 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4193 CPU_BASED_CR8_LOAD_EXITING;
4197 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4198 CPU_BASED_CR3_LOAD_EXITING |
4199 CPU_BASED_INVLPG_EXITING;
4200 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4201 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4202 CPU_BASED_MONITOR_EXITING);
4203 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4204 exec_control &= ~CPU_BASED_HLT_EXITING;
4205 return exec_control;
4209 * Adjust a single secondary execution control bit to intercept/allow an
4210 * instruction in the guest. This is usually done based on whether or not a
4211 * feature has been exposed to the guest in order to correctly emulate faults.
4214 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4215 u32 control, bool enabled, bool exiting)
4218 * If the control is for an opt-in feature, clear the control if the
4219 * feature is not exposed to the guest, i.e. not enabled. If the
4220 * control is opt-out, i.e. an exiting control, clear the control if
4221 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4222 * disabled for the associated instruction. Note, the caller is
4223 * responsible presetting exec_control to set all supported bits.
4225 if (enabled == exiting)
4226 *exec_control &= ~control;
4229 * Update the nested MSR settings so that a nested VMM can/can't set
4230 * controls for features that are/aren't exposed to the guest.
4234 vmx->nested.msrs.secondary_ctls_high |= control;
4236 vmx->nested.msrs.secondary_ctls_high &= ~control;
4241 * Wrapper macro for the common case of adjusting a secondary execution control
4242 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4243 * verifies that the control is actually supported by KVM and hardware.
4245 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4249 if (cpu_has_vmx_##name()) { \
4250 __enabled = guest_cpuid_has(&(vmx)->vcpu, \
4251 X86_FEATURE_##feat_name); \
4252 vmx_adjust_secondary_exec_control(vmx, exec_control, \
4253 SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4257 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4258 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4259 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4261 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4262 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4264 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4266 struct kvm_vcpu *vcpu = &vmx->vcpu;
4268 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4270 if (vmx_pt_mode_is_system())
4271 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4272 if (!cpu_need_virtualize_apic_accesses(vcpu))
4273 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4275 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4277 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4278 enable_unrestricted_guest = 0;
4280 if (!enable_unrestricted_guest)
4281 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4282 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4283 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4284 if (!kvm_vcpu_apicv_active(vcpu))
4285 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4286 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4287 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4289 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4290 * in vmx_set_cr4. */
4291 exec_control &= ~SECONDARY_EXEC_DESC;
4293 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4295 We can NOT enable shadow_vmcs here because we don't have yet
4298 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4301 * PML is enabled/disabled when dirty logging of memsmlots changes, but
4302 * it needs to be set here when dirty logging is already active, e.g.
4303 * if this vCPU was created after dirty logging was enabled.
4305 if (!vcpu->kvm->arch.cpu_dirty_logging_count)
4306 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4308 if (cpu_has_vmx_xsaves()) {
4309 /* Exposing XSAVES only when XSAVE is exposed */
4310 bool xsaves_enabled =
4311 boot_cpu_has(X86_FEATURE_XSAVE) &&
4312 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4313 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4315 vcpu->arch.xsaves_enabled = xsaves_enabled;
4317 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4318 SECONDARY_EXEC_XSAVES,
4319 xsaves_enabled, false);
4323 * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
4324 * feature is exposed to the guest. This creates a virtualization hole
4325 * if both are supported in hardware but only one is exposed to the
4326 * guest, but letting the guest execute RDTSCP or RDPID when either one
4327 * is advertised is preferable to emulating the advertised instruction
4328 * in KVM on #UD, and obviously better than incorrectly injecting #UD.
4330 if (cpu_has_vmx_rdtscp()) {
4331 bool rdpid_or_rdtscp_enabled =
4332 guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
4333 guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
4335 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4336 SECONDARY_EXEC_ENABLE_RDTSCP,
4337 rdpid_or_rdtscp_enabled, false);
4339 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4341 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4342 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4344 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4345 ENABLE_USR_WAIT_PAUSE, false);
4347 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4348 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4350 return exec_control;
4353 #define VMX_XSS_EXIT_BITMAP 0
4356 * Noting that the initialization of Guest-state Area of VMCS is in
4359 static void init_vmcs(struct vcpu_vmx *vmx)
4362 nested_vmx_set_vmcs_shadowing_bitmap();
4364 if (cpu_has_vmx_msr_bitmap())
4365 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4367 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4370 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4372 exec_controls_set(vmx, vmx_exec_control(vmx));
4374 if (cpu_has_secondary_exec_ctrls())
4375 secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx));
4377 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4378 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4379 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4380 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4381 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4383 vmcs_write16(GUEST_INTR_STATUS, 0);
4385 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4386 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4389 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4390 vmcs_write32(PLE_GAP, ple_gap);
4391 vmx->ple_window = ple_window;
4392 vmx->ple_window_dirty = true;
4395 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4396 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4397 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4399 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4400 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4401 vmx_set_constant_host_state(vmx);
4402 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4403 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4405 if (cpu_has_vmx_vmfunc())
4406 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4408 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4409 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4410 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4411 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4412 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4414 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4415 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4417 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4419 /* 22.2.1, 20.8.1 */
4420 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4422 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4423 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4425 set_cr4_guest_host_mask(vmx);
4428 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4430 if (cpu_has_vmx_xsaves())
4431 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4434 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4435 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4438 vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4440 if (vmx_pt_mode_is_host_guest()) {
4441 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4442 /* Bit[6~0] are forced to 1, writes are ignored. */
4443 vmx->pt_desc.guest.output_mask = 0x7F;
4444 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4447 vmcs_write32(GUEST_SYSENTER_CS, 0);
4448 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4449 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4450 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4452 if (cpu_has_vmx_tpr_shadow()) {
4453 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4454 if (cpu_need_tpr_shadow(&vmx->vcpu))
4455 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4456 __pa(vmx->vcpu.arch.apic->regs));
4457 vmcs_write32(TPR_THRESHOLD, 0);
4460 vmx_setup_uret_msrs(vmx);
4463 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4465 struct vcpu_vmx *vmx = to_vmx(vcpu);
4467 vmx->rmode.vm86_active = 0;
4470 vmx->msr_ia32_umwait_control = 0;
4472 vmx->hv_deadline_tsc = -1;
4473 kvm_set_cr8(vcpu, 0);
4475 vmx_segment_cache_clear(vmx);
4477 seg_setup(VCPU_SREG_CS);
4478 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4479 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4481 seg_setup(VCPU_SREG_DS);
4482 seg_setup(VCPU_SREG_ES);
4483 seg_setup(VCPU_SREG_FS);
4484 seg_setup(VCPU_SREG_GS);
4485 seg_setup(VCPU_SREG_SS);
4487 vmcs_write16(GUEST_TR_SELECTOR, 0);
4488 vmcs_writel(GUEST_TR_BASE, 0);
4489 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4490 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4492 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4493 vmcs_writel(GUEST_LDTR_BASE, 0);
4494 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4495 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4497 vmcs_writel(GUEST_GDTR_BASE, 0);
4498 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4500 vmcs_writel(GUEST_IDTR_BASE, 0);
4501 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4503 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4504 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4505 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4506 if (kvm_mpx_supported())
4507 vmcs_write64(GUEST_BNDCFGS, 0);
4509 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4511 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4513 vpid_sync_context(vmx->vpid);
4515 vmx_update_fb_clear_dis(vcpu, vmx);
4518 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4520 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4523 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4526 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4527 vmx_enable_irq_window(vcpu);
4531 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4534 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4536 struct vcpu_vmx *vmx = to_vmx(vcpu);
4538 int irq = vcpu->arch.interrupt.nr;
4540 trace_kvm_inj_virq(irq);
4542 ++vcpu->stat.irq_injections;
4543 if (vmx->rmode.vm86_active) {
4545 if (vcpu->arch.interrupt.soft)
4546 inc_eip = vcpu->arch.event_exit_inst_len;
4547 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4550 intr = irq | INTR_INFO_VALID_MASK;
4551 if (vcpu->arch.interrupt.soft) {
4552 intr |= INTR_TYPE_SOFT_INTR;
4553 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4554 vmx->vcpu.arch.event_exit_inst_len);
4556 intr |= INTR_TYPE_EXT_INTR;
4557 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4559 vmx_clear_hlt(vcpu);
4562 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4564 struct vcpu_vmx *vmx = to_vmx(vcpu);
4568 * Tracking the NMI-blocked state in software is built upon
4569 * finding the next open IRQ window. This, in turn, depends on
4570 * well-behaving guests: They have to keep IRQs disabled at
4571 * least as long as the NMI handler runs. Otherwise we may
4572 * cause NMI nesting, maybe breaking the guest. But as this is
4573 * highly unlikely, we can live with the residual risk.
4575 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4576 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4579 ++vcpu->stat.nmi_injections;
4580 vmx->loaded_vmcs->nmi_known_unmasked = false;
4582 if (vmx->rmode.vm86_active) {
4583 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4587 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4588 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4590 vmx_clear_hlt(vcpu);
4593 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4595 struct vcpu_vmx *vmx = to_vmx(vcpu);
4599 return vmx->loaded_vmcs->soft_vnmi_blocked;
4600 if (vmx->loaded_vmcs->nmi_known_unmasked)
4602 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4603 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4607 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4609 struct vcpu_vmx *vmx = to_vmx(vcpu);
4612 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4613 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4614 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4617 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4619 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4620 GUEST_INTR_STATE_NMI);
4622 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4623 GUEST_INTR_STATE_NMI);
4627 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4629 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4632 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4635 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4636 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4637 GUEST_INTR_STATE_NMI));
4640 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4642 if (to_vmx(vcpu)->nested.nested_run_pending)
4645 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4646 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4649 return !vmx_nmi_blocked(vcpu);
4652 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4654 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4657 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4658 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4659 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4662 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4664 if (to_vmx(vcpu)->nested.nested_run_pending)
4668 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4669 * e.g. if the IRQ arrived asynchronously after checking nested events.
4671 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4674 return !vmx_interrupt_blocked(vcpu);
4677 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4681 if (enable_unrestricted_guest)
4684 mutex_lock(&kvm->slots_lock);
4685 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4687 mutex_unlock(&kvm->slots_lock);
4690 return PTR_ERR(ret);
4692 to_kvm_vmx(kvm)->tss_addr = addr;
4694 return init_rmode_tss(kvm, ret);
4697 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4699 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4703 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4708 * Update instruction length as we may reinject the exception
4709 * from user space while in guest debugging mode.
4711 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4712 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4713 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4717 return !(vcpu->guest_debug &
4718 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4732 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4733 int vec, u32 err_code)
4736 * Instruction with address size override prefix opcode 0x67
4737 * Cause the #SS fault with 0 error code in VM86 mode.
4739 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4740 if (kvm_emulate_instruction(vcpu, 0)) {
4741 if (vcpu->arch.halt_request) {
4742 vcpu->arch.halt_request = 0;
4743 return kvm_vcpu_halt(vcpu);
4751 * Forward all other exceptions that are valid in real mode.
4752 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4753 * the required debugging infrastructure rework.
4755 kvm_queue_exception(vcpu, vec);
4759 static int handle_machine_check(struct kvm_vcpu *vcpu)
4761 /* handled by vmx_vcpu_run() */
4766 * If the host has split lock detection disabled, then #AC is
4767 * unconditionally injected into the guest, which is the pre split lock
4768 * detection behaviour.
4770 * If the host has split lock detection enabled then #AC is
4771 * only injected into the guest when:
4772 * - Guest CPL == 3 (user mode)
4773 * - Guest has #AC detection enabled in CR0
4774 * - Guest EFLAGS has AC bit set
4776 bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu)
4778 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4781 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4782 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4785 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4787 struct vcpu_vmx *vmx = to_vmx(vcpu);
4788 struct kvm_run *kvm_run = vcpu->run;
4789 u32 intr_info, ex_no, error_code;
4790 unsigned long cr2, dr6;
4793 vect_info = vmx->idt_vectoring_info;
4794 intr_info = vmx_get_intr_info(vcpu);
4796 if (is_machine_check(intr_info) || is_nmi(intr_info))
4797 return 1; /* handled by handle_exception_nmi_irqoff() */
4799 if (is_invalid_opcode(intr_info))
4800 return handle_ud(vcpu);
4803 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4804 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4806 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4807 WARN_ON_ONCE(!enable_vmware_backdoor);
4810 * VMware backdoor emulation on #GP interception only handles
4811 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4812 * error code on #GP.
4815 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4818 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4822 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4823 * MMIO, it is better to report an internal error.
4824 * See the comments in vmx_handle_exit.
4826 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4827 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4828 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4829 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4830 vcpu->run->internal.ndata = 4;
4831 vcpu->run->internal.data[0] = vect_info;
4832 vcpu->run->internal.data[1] = intr_info;
4833 vcpu->run->internal.data[2] = error_code;
4834 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
4838 if (is_page_fault(intr_info)) {
4839 cr2 = vmx_get_exit_qual(vcpu);
4840 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
4842 * EPT will cause page fault only if we need to
4843 * detect illegal GPAs.
4845 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
4846 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
4849 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4852 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4854 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4855 return handle_rmode_exception(vcpu, ex_no, error_code);
4859 dr6 = vmx_get_exit_qual(vcpu);
4860 if (!(vcpu->guest_debug &
4861 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4863 * If the #DB was due to ICEBP, a.k.a. INT1, skip the
4864 * instruction. ICEBP generates a trap-like #DB, but
4865 * despite its interception control being tied to #DB,
4866 * is an instruction intercept, i.e. the VM-Exit occurs
4867 * on the ICEBP itself. Note, skipping ICEBP also
4868 * clears STI and MOVSS blocking.
4870 * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
4871 * if single-step is enabled in RFLAGS and STI or MOVSS
4872 * blocking is active, as the CPU doesn't set the bit
4873 * on VM-Exit due to #DB interception. VM-Entry has a
4874 * consistency check that a single-step #DB is pending
4875 * in this scenario as the previous instruction cannot
4876 * have toggled RFLAGS.TF 0=>1 (because STI and POP/MOV
4877 * don't modify RFLAGS), therefore the one instruction
4878 * delay when activating single-step breakpoints must
4879 * have already expired. Note, the CPU sets/clears BS
4880 * as appropriate for all other VM-Exits types.
4882 if (is_icebp(intr_info))
4883 WARN_ON(!skip_emulated_instruction(vcpu));
4884 else if ((vmx_get_rflags(vcpu) & X86_EFLAGS_TF) &&
4885 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4886 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)))
4887 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
4888 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS) | DR6_BS);
4890 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
4893 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
4894 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4898 * Update instruction length as we may reinject #BP from
4899 * user space while in guest debugging mode. Reading it for
4900 * #DB as well causes no harm, it is not used in that case.
4902 vmx->vcpu.arch.event_exit_inst_len =
4903 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4904 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4905 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
4906 kvm_run->debug.arch.exception = ex_no;
4909 if (vmx_guest_inject_ac(vcpu)) {
4910 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4915 * Handle split lock. Depending on detection mode this will
4916 * either warn and disable split lock detection for this
4917 * task or force SIGBUS on it.
4919 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4923 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4924 kvm_run->ex.exception = ex_no;
4925 kvm_run->ex.error_code = error_code;
4931 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4933 ++vcpu->stat.irq_exits;
4937 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4939 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4940 vcpu->mmio_needed = 0;
4944 static int handle_io(struct kvm_vcpu *vcpu)
4946 unsigned long exit_qualification;
4947 int size, in, string;
4950 exit_qualification = vmx_get_exit_qual(vcpu);
4951 string = (exit_qualification & 16) != 0;
4953 ++vcpu->stat.io_exits;
4956 return kvm_emulate_instruction(vcpu, 0);
4958 port = exit_qualification >> 16;
4959 size = (exit_qualification & 7) + 1;
4960 in = (exit_qualification & 8) != 0;
4962 return kvm_fast_pio(vcpu, size, port, in);
4966 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4969 * Patch in the VMCALL instruction:
4971 hypercall[0] = 0x0f;
4972 hypercall[1] = 0x01;
4973 hypercall[2] = 0xc1;
4976 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4977 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4979 if (is_guest_mode(vcpu)) {
4980 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4981 unsigned long orig_val = val;
4984 * We get here when L2 changed cr0 in a way that did not change
4985 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4986 * but did change L0 shadowed bits. So we first calculate the
4987 * effective cr0 value that L1 would like to write into the
4988 * hardware. It consists of the L2-owned bits from the new
4989 * value combined with the L1-owned bits from L1's guest_cr0.
4991 val = (val & ~vmcs12->cr0_guest_host_mask) |
4992 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4994 if (!nested_guest_cr0_valid(vcpu, val))
4997 if (kvm_set_cr0(vcpu, val))
4999 vmcs_writel(CR0_READ_SHADOW, orig_val);
5002 if (to_vmx(vcpu)->nested.vmxon &&
5003 !nested_host_cr0_valid(vcpu, val))
5006 return kvm_set_cr0(vcpu, val);
5010 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5012 if (is_guest_mode(vcpu)) {
5013 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5014 unsigned long orig_val = val;
5016 /* analogously to handle_set_cr0 */
5017 val = (val & ~vmcs12->cr4_guest_host_mask) |
5018 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5019 if (kvm_set_cr4(vcpu, val))
5021 vmcs_writel(CR4_READ_SHADOW, orig_val);
5024 return kvm_set_cr4(vcpu, val);
5027 static int handle_desc(struct kvm_vcpu *vcpu)
5029 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
5030 return kvm_emulate_instruction(vcpu, 0);
5033 static int handle_cr(struct kvm_vcpu *vcpu)
5035 unsigned long exit_qualification, val;
5041 exit_qualification = vmx_get_exit_qual(vcpu);
5042 cr = exit_qualification & 15;
5043 reg = (exit_qualification >> 8) & 15;
5044 switch ((exit_qualification >> 4) & 3) {
5045 case 0: /* mov to cr */
5046 val = kvm_register_read(vcpu, reg);
5047 trace_kvm_cr_write(cr, val);
5050 err = handle_set_cr0(vcpu, val);
5051 return kvm_complete_insn_gp(vcpu, err);
5053 WARN_ON_ONCE(enable_unrestricted_guest);
5055 err = kvm_set_cr3(vcpu, val);
5056 return kvm_complete_insn_gp(vcpu, err);
5058 err = handle_set_cr4(vcpu, val);
5059 return kvm_complete_insn_gp(vcpu, err);
5061 u8 cr8_prev = kvm_get_cr8(vcpu);
5063 err = kvm_set_cr8(vcpu, cr8);
5064 ret = kvm_complete_insn_gp(vcpu, err);
5065 if (lapic_in_kernel(vcpu))
5067 if (cr8_prev <= cr8)
5070 * TODO: we might be squashing a
5071 * KVM_GUESTDBG_SINGLESTEP-triggered
5072 * KVM_EXIT_DEBUG here.
5074 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5080 KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS");
5082 case 1: /*mov from cr*/
5085 WARN_ON_ONCE(enable_unrestricted_guest);
5087 val = kvm_read_cr3(vcpu);
5088 kvm_register_write(vcpu, reg, val);
5089 trace_kvm_cr_read(cr, val);
5090 return kvm_skip_emulated_instruction(vcpu);
5092 val = kvm_get_cr8(vcpu);
5093 kvm_register_write(vcpu, reg, val);
5094 trace_kvm_cr_read(cr, val);
5095 return kvm_skip_emulated_instruction(vcpu);
5099 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5100 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5101 kvm_lmsw(vcpu, val);
5103 return kvm_skip_emulated_instruction(vcpu);
5107 vcpu->run->exit_reason = 0;
5108 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5109 (int)(exit_qualification >> 4) & 3, cr);
5113 static int handle_dr(struct kvm_vcpu *vcpu)
5115 unsigned long exit_qualification;
5119 exit_qualification = vmx_get_exit_qual(vcpu);
5120 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5122 /* First, if DR does not exist, trigger UD */
5123 if (!kvm_require_dr(vcpu, dr))
5126 if (kvm_x86_ops.get_cpl(vcpu) > 0)
5129 dr7 = vmcs_readl(GUEST_DR7);
5132 * As the vm-exit takes precedence over the debug trap, we
5133 * need to emulate the latter, either for the host or the
5134 * guest debugging itself.
5136 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5137 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5138 vcpu->run->debug.arch.dr7 = dr7;
5139 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5140 vcpu->run->debug.arch.exception = DB_VECTOR;
5141 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5144 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5149 if (vcpu->guest_debug == 0) {
5150 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5153 * No more DR vmexits; force a reload of the debug registers
5154 * and reenter on this instruction. The next vmexit will
5155 * retrieve the full state of the debug registers.
5157 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5161 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5162 if (exit_qualification & TYPE_MOV_FROM_DR) {
5165 kvm_get_dr(vcpu, dr, &val);
5166 kvm_register_write(vcpu, reg, val);
5169 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5173 return kvm_complete_insn_gp(vcpu, err);
5176 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5178 get_debugreg(vcpu->arch.db[0], 0);
5179 get_debugreg(vcpu->arch.db[1], 1);
5180 get_debugreg(vcpu->arch.db[2], 2);
5181 get_debugreg(vcpu->arch.db[3], 3);
5182 get_debugreg(vcpu->arch.dr6, 6);
5183 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5185 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5186 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5189 * exc_debug expects dr6 to be cleared after it runs, avoid that it sees
5190 * a stale dr6 from the guest.
5192 set_debugreg(DR6_RESERVED, 6);
5195 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5197 vmcs_writel(GUEST_DR7, val);
5200 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5202 kvm_apic_update_ppr(vcpu);
5206 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5208 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5210 kvm_make_request(KVM_REQ_EVENT, vcpu);
5212 ++vcpu->stat.irq_window_exits;
5216 static int handle_invlpg(struct kvm_vcpu *vcpu)
5218 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5220 kvm_mmu_invlpg(vcpu, exit_qualification);
5221 return kvm_skip_emulated_instruction(vcpu);
5224 static int handle_apic_access(struct kvm_vcpu *vcpu)
5226 if (likely(fasteoi)) {
5227 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5228 int access_type, offset;
5230 access_type = exit_qualification & APIC_ACCESS_TYPE;
5231 offset = exit_qualification & APIC_ACCESS_OFFSET;
5233 * Sane guest uses MOV to write EOI, with written value
5234 * not cared. So make a short-circuit here by avoiding
5235 * heavy instruction emulation.
5237 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5238 (offset == APIC_EOI)) {
5239 kvm_lapic_set_eoi(vcpu);
5240 return kvm_skip_emulated_instruction(vcpu);
5243 return kvm_emulate_instruction(vcpu, 0);
5246 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5248 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5249 int vector = exit_qualification & 0xff;
5251 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5252 kvm_apic_set_eoi_accelerated(vcpu, vector);
5256 static int handle_apic_write(struct kvm_vcpu *vcpu)
5258 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5259 u32 offset = exit_qualification & 0xfff;
5261 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5262 kvm_apic_write_nodecode(vcpu, offset);
5266 static int handle_task_switch(struct kvm_vcpu *vcpu)
5268 struct vcpu_vmx *vmx = to_vmx(vcpu);
5269 unsigned long exit_qualification;
5270 bool has_error_code = false;
5273 int reason, type, idt_v, idt_index;
5275 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5276 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5277 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5279 exit_qualification = vmx_get_exit_qual(vcpu);
5281 reason = (u32)exit_qualification >> 30;
5282 if (reason == TASK_SWITCH_GATE && idt_v) {
5284 case INTR_TYPE_NMI_INTR:
5285 vcpu->arch.nmi_injected = false;
5286 vmx_set_nmi_mask(vcpu, true);
5288 case INTR_TYPE_EXT_INTR:
5289 case INTR_TYPE_SOFT_INTR:
5290 kvm_clear_interrupt_queue(vcpu);
5292 case INTR_TYPE_HARD_EXCEPTION:
5293 if (vmx->idt_vectoring_info &
5294 VECTORING_INFO_DELIVER_CODE_MASK) {
5295 has_error_code = true;
5297 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5300 case INTR_TYPE_SOFT_EXCEPTION:
5301 kvm_clear_exception_queue(vcpu);
5307 tss_selector = exit_qualification;
5309 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5310 type != INTR_TYPE_EXT_INTR &&
5311 type != INTR_TYPE_NMI_INTR))
5312 WARN_ON(!skip_emulated_instruction(vcpu));
5315 * TODO: What about debug traps on tss switch?
5316 * Are we supposed to inject them and update dr6?
5318 return kvm_task_switch(vcpu, tss_selector,
5319 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5320 reason, has_error_code, error_code);
5323 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5325 unsigned long exit_qualification;
5329 exit_qualification = vmx_get_exit_qual(vcpu);
5332 * EPT violation happened while executing iret from NMI,
5333 * "blocked by NMI" bit has to be set before next VM entry.
5334 * There are errata that may cause this bit to not be set:
5337 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5339 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5340 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5342 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5343 trace_kvm_page_fault(gpa, exit_qualification);
5345 /* Is it a read fault? */
5346 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5347 ? PFERR_USER_MASK : 0;
5348 /* Is it a write fault? */
5349 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5350 ? PFERR_WRITE_MASK : 0;
5351 /* Is it a fetch fault? */
5352 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5353 ? PFERR_FETCH_MASK : 0;
5354 /* ept page table entry is present? */
5355 error_code |= (exit_qualification &
5356 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5357 EPT_VIOLATION_EXECUTABLE))
5358 ? PFERR_PRESENT_MASK : 0;
5360 error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
5361 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5363 vcpu->arch.exit_qualification = exit_qualification;
5366 * Check that the GPA doesn't exceed physical memory limits, as that is
5367 * a guest page fault. We have to emulate the instruction here, because
5368 * if the illegal address is that of a paging structure, then
5369 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5370 * would also use advanced VM-exit information for EPT violations to
5371 * reconstruct the page fault error code.
5373 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5374 return kvm_emulate_instruction(vcpu, 0);
5376 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5379 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5383 if (!vmx_can_emulate_instruction(vcpu, NULL, 0))
5387 * A nested guest cannot optimize MMIO vmexits, because we have an
5388 * nGPA here instead of the required GPA.
5390 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5391 if (!is_guest_mode(vcpu) &&
5392 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5393 trace_kvm_fast_mmio(gpa);
5394 return kvm_skip_emulated_instruction(vcpu);
5397 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5400 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5402 if (KVM_BUG_ON(!enable_vnmi, vcpu->kvm))
5405 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5406 ++vcpu->stat.nmi_window_exits;
5407 kvm_make_request(KVM_REQ_EVENT, vcpu);
5412 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5414 struct vcpu_vmx *vmx = to_vmx(vcpu);
5415 bool intr_window_requested;
5416 unsigned count = 130;
5418 intr_window_requested = exec_controls_get(vmx) &
5419 CPU_BASED_INTR_WINDOW_EXITING;
5421 while (vmx->emulation_required && count-- != 0) {
5422 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5423 return handle_interrupt_window(&vmx->vcpu);
5425 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5428 if (!kvm_emulate_instruction(vcpu, 0))
5431 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5432 vcpu->arch.exception.pending) {
5433 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5434 vcpu->run->internal.suberror =
5435 KVM_INTERNAL_ERROR_EMULATION;
5436 vcpu->run->internal.ndata = 0;
5440 if (vcpu->arch.halt_request) {
5441 vcpu->arch.halt_request = 0;
5442 return kvm_vcpu_halt(vcpu);
5446 * Note, return 1 and not 0, vcpu_run() will invoke
5447 * xfer_to_guest_mode() which will create a proper return
5450 if (__xfer_to_guest_mode_work_pending())
5457 static void grow_ple_window(struct kvm_vcpu *vcpu)
5459 struct vcpu_vmx *vmx = to_vmx(vcpu);
5460 unsigned int old = vmx->ple_window;
5462 vmx->ple_window = __grow_ple_window(old, ple_window,
5466 if (vmx->ple_window != old) {
5467 vmx->ple_window_dirty = true;
5468 trace_kvm_ple_window_update(vcpu->vcpu_id,
5469 vmx->ple_window, old);
5473 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5475 struct vcpu_vmx *vmx = to_vmx(vcpu);
5476 unsigned int old = vmx->ple_window;
5478 vmx->ple_window = __shrink_ple_window(old, ple_window,
5482 if (vmx->ple_window != old) {
5483 vmx->ple_window_dirty = true;
5484 trace_kvm_ple_window_update(vcpu->vcpu_id,
5485 vmx->ple_window, old);
5490 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5491 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5493 static int handle_pause(struct kvm_vcpu *vcpu)
5495 if (!kvm_pause_in_guest(vcpu->kvm))
5496 grow_ple_window(vcpu);
5499 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5500 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5501 * never set PAUSE_EXITING and just set PLE if supported,
5502 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5504 kvm_vcpu_on_spin(vcpu, true);
5505 return kvm_skip_emulated_instruction(vcpu);
5508 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5513 static int handle_invpcid(struct kvm_vcpu *vcpu)
5515 u32 vmx_instruction_info;
5523 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5524 kvm_queue_exception(vcpu, UD_VECTOR);
5528 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5529 type = kvm_register_read(vcpu, (vmx_instruction_info >> 28) & 0xf);
5532 kvm_inject_gp(vcpu, 0);
5536 /* According to the Intel instruction reference, the memory operand
5537 * is read even if it isn't needed (e.g., for type==all)
5539 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5540 vmx_instruction_info, false,
5541 sizeof(operand), &gva))
5544 return kvm_handle_invpcid(vcpu, type, gva);
5547 static int handle_pml_full(struct kvm_vcpu *vcpu)
5549 unsigned long exit_qualification;
5551 trace_kvm_pml_full(vcpu->vcpu_id);
5553 exit_qualification = vmx_get_exit_qual(vcpu);
5556 * PML buffer FULL happened while executing iret from NMI,
5557 * "blocked by NMI" bit has to be set before next VM entry.
5559 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5561 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5562 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5563 GUEST_INTR_STATE_NMI);
5566 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5567 * here.., and there's no userspace involvement needed for PML.
5572 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5574 struct vcpu_vmx *vmx = to_vmx(vcpu);
5576 if (!vmx->req_immediate_exit &&
5577 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5578 kvm_lapic_expired_hv_timer(vcpu);
5579 return EXIT_FASTPATH_REENTER_GUEST;
5582 return EXIT_FASTPATH_NONE;
5585 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5587 handle_fastpath_preemption_timer(vcpu);
5592 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5593 * are overwritten by nested_vmx_setup() when nested=1.
5595 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5597 kvm_queue_exception(vcpu, UD_VECTOR);
5601 #ifndef CONFIG_X86_SGX_KVM
5602 static int handle_encls(struct kvm_vcpu *vcpu)
5605 * SGX virtualization is disabled. There is no software enable bit for
5606 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
5607 * the guest from executing ENCLS (when SGX is supported by hardware).
5609 kvm_queue_exception(vcpu, UD_VECTOR);
5612 #endif /* CONFIG_X86_SGX_KVM */
5614 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
5617 * Hardware may or may not set the BUS_LOCK_DETECTED flag on BUS_LOCK
5618 * VM-Exits. Unconditionally set the flag here and leave the handling to
5619 * vmx_handle_exit().
5621 to_vmx(vcpu)->exit_reason.bus_lock_detected = true;
5626 * The exit handlers return 1 if the exit was handled fully and guest execution
5627 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5628 * to be done to userspace and return 0.
5630 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5631 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5632 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5633 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5634 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5635 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5636 [EXIT_REASON_CR_ACCESS] = handle_cr,
5637 [EXIT_REASON_DR_ACCESS] = handle_dr,
5638 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5639 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5640 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5641 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5642 [EXIT_REASON_HLT] = kvm_emulate_halt,
5643 [EXIT_REASON_INVD] = kvm_emulate_invd,
5644 [EXIT_REASON_INVLPG] = handle_invlpg,
5645 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
5646 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
5647 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5648 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5649 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5650 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5651 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5652 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5653 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5654 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5655 [EXIT_REASON_VMON] = handle_vmx_instruction,
5656 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5657 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5658 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5659 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5660 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
5661 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
5662 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5663 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5664 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5665 [EXIT_REASON_LDTR_TR] = handle_desc,
5666 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5667 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5668 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5669 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
5670 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5671 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
5672 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5673 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5674 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
5675 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
5676 [EXIT_REASON_PML_FULL] = handle_pml_full,
5677 [EXIT_REASON_INVPCID] = handle_invpcid,
5678 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5679 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5680 [EXIT_REASON_ENCLS] = handle_encls,
5681 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
5684 static const int kvm_vmx_max_exit_handlers =
5685 ARRAY_SIZE(kvm_vmx_exit_handlers);
5687 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2,
5688 u32 *intr_info, u32 *error_code)
5690 struct vcpu_vmx *vmx = to_vmx(vcpu);
5692 *info1 = vmx_get_exit_qual(vcpu);
5693 if (!(vmx->exit_reason.failed_vmentry)) {
5694 *info2 = vmx->idt_vectoring_info;
5695 *intr_info = vmx_get_intr_info(vcpu);
5696 if (is_exception_with_error_code(*intr_info))
5697 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5707 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5710 __free_page(vmx->pml_pg);
5715 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5717 struct vcpu_vmx *vmx = to_vmx(vcpu);
5721 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5723 /* Do nothing if PML buffer is empty */
5724 if (pml_idx == (PML_ENTITY_NUM - 1))
5727 /* PML index always points to next available PML buffer entity */
5728 if (pml_idx >= PML_ENTITY_NUM)
5733 pml_buf = page_address(vmx->pml_pg);
5734 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5737 gpa = pml_buf[pml_idx];
5738 WARN_ON(gpa & (PAGE_SIZE - 1));
5739 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5742 /* reset PML index */
5743 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5746 static void vmx_dump_sel(char *name, uint32_t sel)
5748 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5749 name, vmcs_read16(sel),
5750 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5751 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5752 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5755 static void vmx_dump_dtsel(char *name, uint32_t limit)
5757 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5758 name, vmcs_read32(limit),
5759 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5762 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
5765 struct vmx_msr_entry *e;
5767 pr_err("MSR %s:\n", name);
5768 for (i = 0, e = m->val; i < m->nr; ++i, ++e)
5769 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
5772 void dump_vmcs(struct kvm_vcpu *vcpu)
5774 struct vcpu_vmx *vmx = to_vmx(vcpu);
5775 u32 vmentry_ctl, vmexit_ctl;
5776 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5780 if (!dump_invalid_vmcs) {
5781 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5785 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5786 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5787 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5788 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5789 cr4 = vmcs_readl(GUEST_CR4);
5790 secondary_exec_control = 0;
5791 if (cpu_has_secondary_exec_ctrls())
5792 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5794 pr_err("VMCS %p, last attempted VM-entry on CPU %d\n",
5795 vmx->loaded_vmcs->vmcs, vcpu->arch.last_vmentry_cpu);
5796 pr_err("*** Guest State ***\n");
5797 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5798 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5799 vmcs_readl(CR0_GUEST_HOST_MASK));
5800 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5801 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5802 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5803 if (cpu_has_vmx_ept()) {
5804 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5805 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5806 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5807 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5809 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5810 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5811 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5812 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5813 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5814 vmcs_readl(GUEST_SYSENTER_ESP),
5815 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5816 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5817 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5818 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5819 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5820 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5821 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5822 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5823 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5824 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5825 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5826 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
5827 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
5828 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
5829 else if (efer_slot >= 0)
5830 pr_err("EFER= 0x%016llx (autoload)\n",
5831 vmx->msr_autoload.guest.val[efer_slot].value);
5832 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
5833 pr_err("EFER= 0x%016llx (effective)\n",
5834 vcpu->arch.efer | (EFER_LMA | EFER_LME));
5836 pr_err("EFER= 0x%016llx (effective)\n",
5837 vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
5838 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
5839 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
5840 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5841 vmcs_read64(GUEST_IA32_DEBUGCTL),
5842 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5843 if (cpu_has_load_perf_global_ctrl() &&
5844 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5845 pr_err("PerfGlobCtl = 0x%016llx\n",
5846 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5847 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5848 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5849 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5850 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5851 vmcs_read32(GUEST_ACTIVITY_STATE));
5852 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5853 pr_err("InterruptStatus = %04x\n",
5854 vmcs_read16(GUEST_INTR_STATUS));
5855 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
5856 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
5857 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
5858 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
5860 pr_err("*** Host State ***\n");
5861 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5862 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5863 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5864 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5865 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5866 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5867 vmcs_read16(HOST_TR_SELECTOR));
5868 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5869 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5870 vmcs_readl(HOST_TR_BASE));
5871 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5872 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5873 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5874 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5875 vmcs_readl(HOST_CR4));
5876 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5877 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5878 vmcs_read32(HOST_IA32_SYSENTER_CS),
5879 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5880 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
5881 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
5882 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
5883 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
5884 if (cpu_has_load_perf_global_ctrl() &&
5885 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5886 pr_err("PerfGlobCtl = 0x%016llx\n",
5887 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5888 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
5889 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
5891 pr_err("*** Control State ***\n");
5892 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5893 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5894 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5895 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5896 vmcs_read32(EXCEPTION_BITMAP),
5897 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5898 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5899 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5900 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5901 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5902 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5903 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5904 vmcs_read32(VM_EXIT_INTR_INFO),
5905 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5906 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5907 pr_err(" reason=%08x qualification=%016lx\n",
5908 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5909 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5910 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5911 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5912 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5913 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5914 pr_err("TSC Multiplier = 0x%016llx\n",
5915 vmcs_read64(TSC_MULTIPLIER));
5916 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5917 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5918 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5919 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5921 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5922 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5923 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5924 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5926 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5927 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5928 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5929 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5930 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5931 pr_err("PLE Gap=%08x Window=%08x\n",
5932 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5933 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5934 pr_err("Virtual processor ID = 0x%04x\n",
5935 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5939 * The guest has exited. See if we can fix it or if we need userspace
5942 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
5944 struct vcpu_vmx *vmx = to_vmx(vcpu);
5945 union vmx_exit_reason exit_reason = vmx->exit_reason;
5946 u32 vectoring_info = vmx->idt_vectoring_info;
5947 u16 exit_handler_index;
5950 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5951 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5952 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5953 * mode as if vcpus is in root mode, the PML buffer must has been
5954 * flushed already. Note, PML is never enabled in hardware while
5957 if (enable_pml && !is_guest_mode(vcpu))
5958 vmx_flush_pml_buffer(vcpu);
5961 * KVM should never reach this point with a pending nested VM-Enter.
5962 * More specifically, short-circuiting VM-Entry to emulate L2 due to
5963 * invalid guest state should never happen as that means KVM knowingly
5964 * allowed a nested VM-Enter with an invalid vmcs12. More below.
5966 if (KVM_BUG_ON(vmx->nested.nested_run_pending, vcpu->kvm))
5969 if (is_guest_mode(vcpu)) {
5971 * PML is never enabled when running L2, bail immediately if a
5972 * PML full exit occurs as something is horribly wrong.
5974 if (exit_reason.basic == EXIT_REASON_PML_FULL)
5975 goto unexpected_vmexit;
5978 * The host physical addresses of some pages of guest memory
5979 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
5980 * Page). The CPU may write to these pages via their host
5981 * physical address while L2 is running, bypassing any
5982 * address-translation-based dirty tracking (e.g. EPT write
5985 * Mark them dirty on every exit from L2 to prevent them from
5986 * getting out of sync with dirty tracking.
5988 nested_mark_vmcs12_pages_dirty(vcpu);
5991 * Synthesize a triple fault if L2 state is invalid. In normal
5992 * operation, nested VM-Enter rejects any attempt to enter L2
5993 * with invalid state. However, those checks are skipped if
5994 * state is being stuffed via RSM or KVM_SET_NESTED_STATE. If
5995 * L2 state is invalid, it means either L1 modified SMRAM state
5996 * or userspace provided bad state. Synthesize TRIPLE_FAULT as
5997 * doing so is architecturally allowed in the RSM case, and is
5998 * the least awful solution for the userspace case without
5999 * risking false positives.
6001 if (vmx->emulation_required) {
6002 nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
6006 if (nested_vmx_reflect_vmexit(vcpu))
6010 /* If guest state is invalid, start emulating. L2 is handled above. */
6011 if (vmx->emulation_required)
6012 return handle_invalid_guest_state(vcpu);
6014 if (exit_reason.failed_vmentry) {
6016 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6017 vcpu->run->fail_entry.hardware_entry_failure_reason
6019 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6023 if (unlikely(vmx->fail)) {
6025 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6026 vcpu->run->fail_entry.hardware_entry_failure_reason
6027 = vmcs_read32(VM_INSTRUCTION_ERROR);
6028 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6034 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6035 * delivery event since it indicates guest is accessing MMIO.
6036 * The vm-exit can be triggered again after return to guest that
6037 * will cause infinite loop.
6039 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6040 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6041 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6042 exit_reason.basic != EXIT_REASON_PML_FULL &&
6043 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6044 exit_reason.basic != EXIT_REASON_TASK_SWITCH)) {
6047 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6048 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6049 vcpu->run->internal.data[0] = vectoring_info;
6050 vcpu->run->internal.data[1] = exit_reason.full;
6051 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6052 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6053 vcpu->run->internal.data[ndata++] =
6054 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6056 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6057 vcpu->run->internal.ndata = ndata;
6061 if (unlikely(!enable_vnmi &&
6062 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6063 if (!vmx_interrupt_blocked(vcpu)) {
6064 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6065 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6066 vcpu->arch.nmi_pending) {
6068 * This CPU don't support us in finding the end of an
6069 * NMI-blocked window if the guest runs with IRQs
6070 * disabled. So we pull the trigger after 1 s of
6071 * futile waiting, but inform the user about this.
6073 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6074 "state on VCPU %d after 1 s timeout\n",
6075 __func__, vcpu->vcpu_id);
6076 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6080 if (exit_fastpath != EXIT_FASTPATH_NONE)
6083 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6084 goto unexpected_vmexit;
6085 #ifdef CONFIG_RETPOLINE
6086 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6087 return kvm_emulate_wrmsr(vcpu);
6088 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6089 return handle_preemption_timer(vcpu);
6090 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6091 return handle_interrupt_window(vcpu);
6092 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6093 return handle_external_interrupt(vcpu);
6094 else if (exit_reason.basic == EXIT_REASON_HLT)
6095 return kvm_emulate_halt(vcpu);
6096 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6097 return handle_ept_misconfig(vcpu);
6100 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6101 kvm_vmx_max_exit_handlers);
6102 if (!kvm_vmx_exit_handlers[exit_handler_index])
6103 goto unexpected_vmexit;
6105 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6108 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6111 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6112 vcpu->run->internal.suberror =
6113 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6114 vcpu->run->internal.ndata = 2;
6115 vcpu->run->internal.data[0] = exit_reason.full;
6116 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6120 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6122 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6125 * Exit to user space when bus lock detected to inform that there is
6126 * a bus lock in guest.
6128 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6130 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6132 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6139 * Software based L1D cache flush which is used when microcode providing
6140 * the cache control MSR is not loaded.
6142 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6143 * flush it is required to read in 64 KiB because the replacement algorithm
6144 * is not exactly LRU. This could be sized at runtime via topology
6145 * information but as all relevant affected CPUs have 32KiB L1D cache size
6146 * there is no point in doing so.
6148 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6150 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6153 * This code is only executed when the the flush mode is 'cond' or
6156 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6160 * Clear the per-vcpu flush bit, it gets set again
6161 * either from vcpu_run() or from one of the unsafe
6164 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6165 vcpu->arch.l1tf_flush_l1d = false;
6168 * Clear the per-cpu flush bit, it gets set again from
6169 * the interrupt handlers.
6171 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6172 kvm_clear_cpu_l1tf_flush_l1d();
6178 vcpu->stat.l1d_flush++;
6180 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6181 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6186 /* First ensure the pages are in the TLB */
6187 "xorl %%eax, %%eax\n"
6188 ".Lpopulate_tlb:\n\t"
6189 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6190 "addl $4096, %%eax\n\t"
6191 "cmpl %%eax, %[size]\n\t"
6192 "jne .Lpopulate_tlb\n\t"
6193 "xorl %%eax, %%eax\n\t"
6195 /* Now fill the cache */
6196 "xorl %%eax, %%eax\n"
6198 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6199 "addl $64, %%eax\n\t"
6200 "cmpl %%eax, %[size]\n\t"
6201 "jne .Lfill_cache\n\t"
6203 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6205 : "eax", "ebx", "ecx", "edx");
6208 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6210 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6213 if (is_guest_mode(vcpu) &&
6214 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6217 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6218 if (is_guest_mode(vcpu))
6219 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6221 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6224 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6226 struct vcpu_vmx *vmx = to_vmx(vcpu);
6227 u32 sec_exec_control;
6229 if (!lapic_in_kernel(vcpu))
6232 if (!flexpriority_enabled &&
6233 !cpu_has_vmx_virtualize_x2apic_mode())
6236 /* Postpone execution until vmcs01 is the current VMCS. */
6237 if (is_guest_mode(vcpu)) {
6238 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6242 sec_exec_control = secondary_exec_controls_get(vmx);
6243 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6244 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6246 switch (kvm_get_apic_mode(vcpu)) {
6247 case LAPIC_MODE_INVALID:
6248 WARN_ONCE(true, "Invalid local APIC state");
6250 case LAPIC_MODE_DISABLED:
6252 case LAPIC_MODE_XAPIC:
6253 if (flexpriority_enabled) {
6255 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6256 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6259 * Flush the TLB, reloading the APIC access page will
6260 * only do so if its physical address has changed, but
6261 * the guest may have inserted a non-APIC mapping into
6262 * the TLB while the APIC access page was disabled.
6264 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6267 case LAPIC_MODE_X2APIC:
6268 if (cpu_has_vmx_virtualize_x2apic_mode())
6270 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6273 secondary_exec_controls_set(vmx, sec_exec_control);
6275 vmx_update_msr_bitmap_x2apic(vcpu);
6278 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6282 /* Defer reload until vmcs01 is the current VMCS. */
6283 if (is_guest_mode(vcpu)) {
6284 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6288 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6289 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6292 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6293 if (is_error_page(page))
6296 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6297 vmx_flush_tlb_current(vcpu);
6300 * Do not pin apic access page in memory, the MMU notifier
6301 * will call us again if it is migrated or swapped out.
6306 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6314 status = vmcs_read16(GUEST_INTR_STATUS);
6316 if (max_isr != old) {
6318 status |= max_isr << 8;
6319 vmcs_write16(GUEST_INTR_STATUS, status);
6323 static void vmx_set_rvi(int vector)
6331 status = vmcs_read16(GUEST_INTR_STATUS);
6332 old = (u8)status & 0xff;
6333 if ((u8)vector != old) {
6335 status |= (u8)vector;
6336 vmcs_write16(GUEST_INTR_STATUS, status);
6340 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6343 * When running L2, updating RVI is only relevant when
6344 * vmcs12 virtual-interrupt-delivery enabled.
6345 * However, it can be enabled only when L1 also
6346 * intercepts external-interrupts and in that case
6347 * we should not update vmcs02 RVI but instead intercept
6348 * interrupt. Therefore, do nothing when running L2.
6350 if (!is_guest_mode(vcpu))
6351 vmx_set_rvi(max_irr);
6354 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6356 struct vcpu_vmx *vmx = to_vmx(vcpu);
6358 bool got_posted_interrupt;
6360 if (KVM_BUG_ON(!enable_apicv, vcpu->kvm))
6363 if (pi_test_on(&vmx->pi_desc)) {
6364 pi_clear_on(&vmx->pi_desc);
6366 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6367 * But on x86 this is just a compiler barrier anyway.
6369 smp_mb__after_atomic();
6370 got_posted_interrupt =
6371 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6373 max_irr = kvm_lapic_find_highest_irr(vcpu);
6374 got_posted_interrupt = false;
6378 * Newly recognized interrupts are injected via either virtual interrupt
6379 * delivery (RVI) or KVM_REQ_EVENT. Virtual interrupt delivery is
6380 * disabled in two cases:
6382 * 1) If L2 is running and the vCPU has a new pending interrupt. If L1
6383 * wants to exit on interrupts, KVM_REQ_EVENT is needed to synthesize a
6384 * VM-Exit to L1. If L1 doesn't want to exit, the interrupt is injected
6385 * into L2, but KVM doesn't use virtual interrupt delivery to inject
6386 * interrupts into L2, and so KVM_REQ_EVENT is again needed.
6388 * 2) If APICv is disabled for this vCPU, assigned devices may still
6389 * attempt to post interrupts. The posted interrupt vector will cause
6390 * a VM-Exit and the subsequent entry will call sync_pir_to_irr.
6392 if (!is_guest_mode(vcpu) && kvm_vcpu_apicv_active(vcpu))
6393 vmx_set_rvi(max_irr);
6394 else if (got_posted_interrupt)
6395 kvm_make_request(KVM_REQ_EVENT, vcpu);
6400 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6402 if (!kvm_vcpu_apicv_active(vcpu))
6405 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6406 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6407 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6408 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6411 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6413 struct vcpu_vmx *vmx = to_vmx(vcpu);
6415 pi_clear_on(&vmx->pi_desc);
6416 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6419 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6421 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu,
6422 unsigned long entry)
6424 kvm_before_interrupt(vcpu);
6425 vmx_do_interrupt_nmi_irqoff(entry);
6426 kvm_after_interrupt(vcpu);
6429 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6431 const unsigned long nmi_entry = (unsigned long)asm_exc_nmi_noist;
6432 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6434 /* if exit due to PF check for async PF */
6435 if (is_page_fault(intr_info))
6436 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6437 /* Handle machine checks before interrupts are enabled */
6438 else if (is_machine_check(intr_info))
6439 kvm_machine_check();
6440 /* We need to handle NMIs before interrupts are enabled */
6441 else if (is_nmi(intr_info))
6442 handle_interrupt_nmi_irqoff(&vmx->vcpu, nmi_entry);
6445 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6447 u32 intr_info = vmx_get_intr_info(vcpu);
6448 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6449 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6451 if (KVM_BUG(!is_external_intr(intr_info), vcpu->kvm,
6452 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6455 handle_interrupt_nmi_irqoff(vcpu, gate_offset(desc));
6458 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6460 struct vcpu_vmx *vmx = to_vmx(vcpu);
6462 if (vmx->emulation_required)
6465 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6466 handle_external_interrupt_irqoff(vcpu);
6467 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
6468 handle_exception_nmi_irqoff(vmx);
6472 * The kvm parameter can be NULL (module initialization, or invocation before
6473 * VM creation). Be sure to check the kvm parameter before using it.
6475 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
6478 case MSR_IA32_SMBASE:
6480 * We cannot do SMM unless we can run the guest in big
6483 return enable_unrestricted_guest || emulate_invalid_guest_state;
6484 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6486 case MSR_AMD64_VIRT_SPEC_CTRL:
6487 /* This is AMD only. */
6494 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6499 bool idtv_info_valid;
6501 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6504 if (vmx->loaded_vmcs->nmi_known_unmasked)
6507 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6508 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6509 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6511 * SDM 3: 27.7.1.2 (September 2008)
6512 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6513 * a guest IRET fault.
6514 * SDM 3: 23.2.2 (September 2008)
6515 * Bit 12 is undefined in any of the following cases:
6516 * If the VM exit sets the valid bit in the IDT-vectoring
6517 * information field.
6518 * If the VM exit is due to a double fault.
6520 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6521 vector != DF_VECTOR && !idtv_info_valid)
6522 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6523 GUEST_INTR_STATE_NMI);
6525 vmx->loaded_vmcs->nmi_known_unmasked =
6526 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6527 & GUEST_INTR_STATE_NMI);
6528 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6529 vmx->loaded_vmcs->vnmi_blocked_time +=
6530 ktime_to_ns(ktime_sub(ktime_get(),
6531 vmx->loaded_vmcs->entry_time));
6534 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6535 u32 idt_vectoring_info,
6536 int instr_len_field,
6537 int error_code_field)
6541 bool idtv_info_valid;
6543 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6545 vcpu->arch.nmi_injected = false;
6546 kvm_clear_exception_queue(vcpu);
6547 kvm_clear_interrupt_queue(vcpu);
6549 if (!idtv_info_valid)
6552 kvm_make_request(KVM_REQ_EVENT, vcpu);
6554 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6555 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6558 case INTR_TYPE_NMI_INTR:
6559 vcpu->arch.nmi_injected = true;
6561 * SDM 3: 27.7.1.2 (September 2008)
6562 * Clear bit "block by NMI" before VM entry if a NMI
6565 vmx_set_nmi_mask(vcpu, false);
6567 case INTR_TYPE_SOFT_EXCEPTION:
6568 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6570 case INTR_TYPE_HARD_EXCEPTION:
6571 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6572 u32 err = vmcs_read32(error_code_field);
6573 kvm_requeue_exception_e(vcpu, vector, err);
6575 kvm_requeue_exception(vcpu, vector);
6577 case INTR_TYPE_SOFT_INTR:
6578 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6580 case INTR_TYPE_EXT_INTR:
6581 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6588 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6590 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6591 VM_EXIT_INSTRUCTION_LEN,
6592 IDT_VECTORING_ERROR_CODE);
6595 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6597 __vmx_complete_interrupts(vcpu,
6598 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6599 VM_ENTRY_INSTRUCTION_LEN,
6600 VM_ENTRY_EXCEPTION_ERROR_CODE);
6602 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6605 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6608 struct perf_guest_switch_msr *msrs;
6610 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
6611 msrs = perf_guest_get_msrs(&nr_msrs);
6615 for (i = 0; i < nr_msrs; i++)
6616 if (msrs[i].host == msrs[i].guest)
6617 clear_atomic_switch_msr(vmx, msrs[i].msr);
6619 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6620 msrs[i].host, false);
6623 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6625 struct vcpu_vmx *vmx = to_vmx(vcpu);
6629 if (vmx->req_immediate_exit) {
6630 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6631 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6632 } else if (vmx->hv_deadline_tsc != -1) {
6634 if (vmx->hv_deadline_tsc > tscl)
6635 /* set_hv_timer ensures the delta fits in 32-bits */
6636 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6637 cpu_preemption_timer_multi);
6641 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6642 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6643 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6644 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6645 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6649 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6651 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6652 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6653 vmcs_writel(HOST_RSP, host_rsp);
6657 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6659 switch (to_vmx(vcpu)->exit_reason.basic) {
6660 case EXIT_REASON_MSR_WRITE:
6661 return handle_fastpath_set_msr_irqoff(vcpu);
6662 case EXIT_REASON_PREEMPTION_TIMER:
6663 return handle_fastpath_preemption_timer(vcpu);
6665 return EXIT_FASTPATH_NONE;
6669 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6670 struct vcpu_vmx *vmx)
6672 kvm_guest_enter_irqoff();
6674 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6675 if (static_branch_unlikely(&vmx_l1d_should_flush))
6676 vmx_l1d_flush(vcpu);
6677 else if (static_branch_unlikely(&mds_user_clear))
6678 mds_clear_cpu_buffers();
6679 else if (static_branch_unlikely(&mmio_stale_data_clear) &&
6680 kvm_arch_has_assigned_device(vcpu->kvm))
6681 mds_clear_cpu_buffers();
6683 vmx_disable_fb_clear(vmx);
6685 if (vcpu->arch.cr2 != native_read_cr2())
6686 native_write_cr2(vcpu->arch.cr2);
6688 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6689 vmx->loaded_vmcs->launched);
6691 vcpu->arch.cr2 = native_read_cr2();
6693 vmx_enable_fb_clear(vmx);
6695 kvm_guest_exit_irqoff();
6698 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6700 struct vcpu_vmx *vmx = to_vmx(vcpu);
6701 unsigned long cr3, cr4;
6703 /* Record the guest's net vcpu time for enforced NMI injections. */
6704 if (unlikely(!enable_vnmi &&
6705 vmx->loaded_vmcs->soft_vnmi_blocked))
6706 vmx->loaded_vmcs->entry_time = ktime_get();
6709 * Don't enter VMX if guest state is invalid, let the exit handler
6710 * start emulation until we arrive back to a valid state. Synthesize a
6711 * consistency check VM-Exit due to invalid guest state and bail.
6713 if (unlikely(vmx->emulation_required)) {
6716 vmx->exit_reason.full = EXIT_REASON_INVALID_STATE;
6717 vmx->exit_reason.failed_vmentry = 1;
6718 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_1);
6719 vmx->exit_qualification = ENTRY_FAIL_DEFAULT;
6720 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_2);
6721 vmx->exit_intr_info = 0;
6722 return EXIT_FASTPATH_NONE;
6725 trace_kvm_entry(vcpu);
6727 if (vmx->ple_window_dirty) {
6728 vmx->ple_window_dirty = false;
6729 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6733 * We did this in prepare_switch_to_guest, because it needs to
6734 * be within srcu_read_lock.
6736 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6738 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6739 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6740 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6741 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6743 cr3 = __get_current_cr3_fast();
6744 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6745 vmcs_writel(HOST_CR3, cr3);
6746 vmx->loaded_vmcs->host_state.cr3 = cr3;
6749 cr4 = cr4_read_shadow();
6750 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6751 vmcs_writel(HOST_CR4, cr4);
6752 vmx->loaded_vmcs->host_state.cr4 = cr4;
6755 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
6756 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
6757 set_debugreg(vcpu->arch.dr6, 6);
6759 /* When single-stepping over STI and MOV SS, we must clear the
6760 * corresponding interruptibility bits in the guest state. Otherwise
6761 * vmentry fails as it then expects bit 14 (BS) in pending debug
6762 * exceptions being set, but that's not correct for the guest debugging
6764 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6765 vmx_set_interrupt_shadow(vcpu, 0);
6767 kvm_load_guest_xsave_state(vcpu);
6769 pt_guest_enter(vmx);
6771 atomic_switch_perf_msrs(vmx);
6772 if (intel_pmu_lbr_is_enabled(vcpu))
6773 vmx_passthrough_lbr_msrs(vcpu);
6775 if (enable_preemption_timer)
6776 vmx_update_hv_timer(vcpu);
6778 kvm_wait_lapic_expire(vcpu);
6781 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6782 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6783 * is no need to worry about the conditional branch over the wrmsr
6784 * being speculatively taken.
6786 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6788 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6789 vmx_vcpu_enter_exit(vcpu, vmx);
6792 * We do not use IBRS in the kernel. If this vCPU has used the
6793 * SPEC_CTRL MSR it may have left it on; save the value and
6794 * turn it off. This is much more efficient than blindly adding
6795 * it to the atomic save/restore list. Especially as the former
6796 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6798 * For non-nested case:
6799 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6803 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6806 if (unlikely(!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL)))
6807 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6809 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6811 /* All fields are clean at this point */
6812 if (static_branch_unlikely(&enable_evmcs)) {
6813 current_evmcs->hv_clean_fields |=
6814 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6816 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
6819 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6820 if (vmx->host_debugctlmsr)
6821 update_debugctlmsr(vmx->host_debugctlmsr);
6823 #ifndef CONFIG_X86_64
6825 * The sysexit path does not restore ds/es, so we must set them to
6826 * a reasonable value ourselves.
6828 * We can't defer this to vmx_prepare_switch_to_host() since that
6829 * function may be executed in interrupt context, which saves and
6830 * restore segments around it, nullifying its effect.
6832 loadsegment(ds, __USER_DS);
6833 loadsegment(es, __USER_DS);
6836 vmx_register_cache_reset(vcpu);
6840 kvm_load_host_xsave_state(vcpu);
6842 if (is_guest_mode(vcpu)) {
6844 * Track VMLAUNCH/VMRESUME that have made past guest state
6847 if (vmx->nested.nested_run_pending &&
6848 !vmx->exit_reason.failed_vmentry)
6849 ++vcpu->stat.nested_run;
6851 vmx->nested.nested_run_pending = 0;
6854 vmx->idt_vectoring_info = 0;
6856 if (unlikely(vmx->fail)) {
6857 vmx->exit_reason.full = 0xdead;
6858 return EXIT_FASTPATH_NONE;
6861 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
6862 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
6863 kvm_machine_check();
6865 if (likely(!vmx->exit_reason.failed_vmentry))
6866 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6868 trace_kvm_exit(vmx->exit_reason.full, vcpu, KVM_ISA_VMX);
6870 if (unlikely(vmx->exit_reason.failed_vmentry))
6871 return EXIT_FASTPATH_NONE;
6873 vmx->loaded_vmcs->launched = 1;
6875 vmx_recover_nmi_blocking(vmx);
6876 vmx_complete_interrupts(vmx);
6878 if (is_guest_mode(vcpu))
6879 return EXIT_FASTPATH_NONE;
6881 return vmx_exit_handlers_fastpath(vcpu);
6884 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6886 struct vcpu_vmx *vmx = to_vmx(vcpu);
6889 vmx_destroy_pml_buffer(vmx);
6890 free_vpid(vmx->vpid);
6891 nested_vmx_free_vcpu(vcpu);
6892 free_loaded_vmcs(vmx->loaded_vmcs);
6895 static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
6897 struct vmx_uret_msr *tsx_ctrl;
6898 struct vcpu_vmx *vmx;
6901 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6906 vmx->vpid = allocate_vpid();
6909 * If PML is turned on, failure on enabling PML just results in failure
6910 * of creating the vcpu, therefore we can simplify PML logic (by
6911 * avoiding dealing with cases, such as enabling PML partially on vcpus
6912 * for the guest), etc.
6915 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6920 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
6921 vmx->guest_uret_msrs[i].data = 0;
6922 vmx->guest_uret_msrs[i].mask = -1ull;
6924 if (boot_cpu_has(X86_FEATURE_RTM)) {
6926 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception.
6927 * Keep the host value unchanged to avoid changing CPUID bits
6928 * under the host kernel's feet.
6930 tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
6932 tsx_ctrl->mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6935 err = alloc_loaded_vmcs(&vmx->vmcs01);
6939 /* The MSR bitmap starts with all ones */
6940 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6941 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6943 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
6944 #ifdef CONFIG_X86_64
6945 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
6946 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
6947 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6949 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6950 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6951 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6952 if (kvm_cstate_in_guest(vcpu->kvm)) {
6953 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
6954 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6955 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6956 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6959 vmx->loaded_vmcs = &vmx->vmcs01;
6961 vmx_vcpu_load(vcpu, cpu);
6966 if (cpu_need_virtualize_apic_accesses(vcpu)) {
6967 err = alloc_apic_access_page(vcpu->kvm);
6972 if (enable_ept && !enable_unrestricted_guest) {
6973 err = init_rmode_identity_map(vcpu->kvm);
6979 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
6981 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6983 vcpu_setup_sgx_lepubkeyhash(vcpu);
6985 vmx->nested.posted_intr_nv = -1;
6986 vmx->nested.current_vmptr = -1ull;
6987 vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
6989 vcpu->arch.microcode_version = 0x100000000ULL;
6990 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
6993 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6994 * or POSTED_INTR_WAKEUP_VECTOR.
6996 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6997 vmx->pi_desc.sn = 1;
7002 free_loaded_vmcs(vmx->loaded_vmcs);
7004 vmx_destroy_pml_buffer(vmx);
7006 free_vpid(vmx->vpid);
7010 #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"
7011 #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"
7013 static int vmx_vm_init(struct kvm *kvm)
7016 kvm->arch.pause_in_guest = true;
7018 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7019 switch (l1tf_mitigation) {
7020 case L1TF_MITIGATION_OFF:
7021 case L1TF_MITIGATION_FLUSH_NOWARN:
7022 /* 'I explicitly don't care' is set */
7024 case L1TF_MITIGATION_FLUSH:
7025 case L1TF_MITIGATION_FLUSH_NOSMT:
7026 case L1TF_MITIGATION_FULL:
7028 * Warn upon starting the first VM in a potentially
7029 * insecure environment.
7031 if (sched_smt_active())
7032 pr_warn_once(L1TF_MSG_SMT);
7033 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7034 pr_warn_once(L1TF_MSG_L1D);
7036 case L1TF_MITIGATION_FULL_FORCE:
7037 /* Flush is enforced */
7044 static int __init vmx_check_processor_compat(void)
7046 struct vmcs_config vmcs_conf;
7047 struct vmx_capability vmx_cap;
7049 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7050 !this_cpu_has(X86_FEATURE_VMX)) {
7051 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7055 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7058 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
7059 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7060 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7061 smp_processor_id());
7067 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7072 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7073 * memory aliases with conflicting memory types and sometimes MCEs.
7074 * We have to be careful as to what are honored and when.
7076 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7077 * UC. The effective memory type is UC or WC depending on guest PAT.
7078 * This was historically the source of MCEs and we want to be
7081 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7082 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7083 * EPT memory type is set to WB. The effective memory type is forced
7086 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7087 * EPT memory type is used to emulate guest CD/MTRR.
7091 cache = MTRR_TYPE_UNCACHABLE;
7095 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7096 ipat = VMX_EPT_IPAT_BIT;
7097 cache = MTRR_TYPE_WRBACK;
7101 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7102 ipat = VMX_EPT_IPAT_BIT;
7103 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7104 cache = MTRR_TYPE_WRBACK;
7106 cache = MTRR_TYPE_UNCACHABLE;
7110 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
7113 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7116 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx, u32 new_ctl)
7119 * These bits in the secondary execution controls field
7120 * are dynamic, the others are mostly based on the hypervisor
7121 * architecture and the guest's CPUID. Do not touch the
7125 SECONDARY_EXEC_SHADOW_VMCS |
7126 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7127 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7128 SECONDARY_EXEC_DESC;
7130 u32 cur_ctl = secondary_exec_controls_get(vmx);
7132 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7136 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7137 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7139 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7141 struct vcpu_vmx *vmx = to_vmx(vcpu);
7142 struct kvm_cpuid_entry2 *entry;
7144 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7145 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7147 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7148 if (entry && (entry->_reg & (_cpuid_mask))) \
7149 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7152 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7153 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7154 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7155 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7156 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7157 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7158 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7159 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7160 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7161 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7162 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7163 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7164 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7165 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7166 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7168 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7169 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7170 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7171 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7172 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7173 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7174 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7176 #undef cr4_fixed1_update
7179 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7181 struct vcpu_vmx *vmx = to_vmx(vcpu);
7183 if (kvm_mpx_supported()) {
7184 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7187 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7188 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7190 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7191 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7196 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7198 struct vcpu_vmx *vmx = to_vmx(vcpu);
7199 struct kvm_cpuid_entry2 *best = NULL;
7202 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7203 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7206 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7207 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7208 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7209 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7212 /* Get the number of configurable Address Ranges for filtering */
7213 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7214 PT_CAP_num_address_ranges);
7216 /* Initialize and clear the no dependency bits */
7217 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7218 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7221 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7222 * will inject an #GP
7224 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7225 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7228 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7229 * PSBFreq can be set
7231 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7232 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7233 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7236 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7237 * MTCFreq can be set
7239 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7240 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7241 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7243 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7244 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7245 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7248 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7249 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7250 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7252 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7253 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7254 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7256 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7257 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7258 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7260 /* unmask address range configure area */
7261 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7262 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7265 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7267 struct vcpu_vmx *vmx = to_vmx(vcpu);
7269 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7270 vcpu->arch.xsaves_enabled = false;
7272 vmx_setup_uret_msrs(vmx);
7274 if (cpu_has_secondary_exec_ctrls())
7275 vmcs_set_secondary_exec_control(vmx,
7276 vmx_secondary_exec_control(vmx));
7278 if (nested_vmx_allowed(vcpu))
7279 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7280 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7281 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7283 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7284 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7285 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7287 if (nested_vmx_allowed(vcpu)) {
7288 nested_vmx_cr_fixed1_bits_update(vcpu);
7289 nested_vmx_entry_exit_ctls_update(vcpu);
7292 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7293 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7294 update_intel_pt_cfg(vcpu);
7296 if (boot_cpu_has(X86_FEATURE_RTM)) {
7297 struct vmx_uret_msr *msr;
7298 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7300 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7301 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7305 set_cr4_guest_host_mask(vmx);
7307 vmx_write_encls_bitmap(vcpu, NULL);
7308 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7309 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7311 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7313 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7314 vmx->msr_ia32_feature_control_valid_bits |=
7315 FEAT_CTL_SGX_LC_ENABLED;
7317 vmx->msr_ia32_feature_control_valid_bits &=
7318 ~FEAT_CTL_SGX_LC_ENABLED;
7320 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7321 vmx_update_exception_bitmap(vcpu);
7324 static __init void vmx_set_cpu_caps(void)
7330 kvm_cpu_cap_set(X86_FEATURE_VMX);
7333 if (kvm_mpx_supported())
7334 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7335 if (!cpu_has_vmx_invpcid())
7336 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7337 if (vmx_pt_mode_is_host_guest())
7338 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7341 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7342 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7343 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7344 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7347 if (vmx_umip_emulated())
7348 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7352 if (!cpu_has_vmx_xsaves())
7353 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7355 /* CPUID 0x80000001 and 0x7 (RDPID) */
7356 if (!cpu_has_vmx_rdtscp()) {
7357 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7358 kvm_cpu_cap_clear(X86_FEATURE_RDPID);
7361 if (cpu_has_vmx_waitpkg())
7362 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7365 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7367 to_vmx(vcpu)->req_immediate_exit = true;
7370 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7371 struct x86_instruction_info *info)
7373 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7374 unsigned short port;
7378 if (info->intercept == x86_intercept_in ||
7379 info->intercept == x86_intercept_ins) {
7380 port = info->src_val;
7381 size = info->dst_bytes;
7383 port = info->dst_val;
7384 size = info->src_bytes;
7388 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7389 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7392 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7394 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7395 intercept = nested_cpu_has(vmcs12,
7396 CPU_BASED_UNCOND_IO_EXITING);
7398 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7400 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7401 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7404 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7405 struct x86_instruction_info *info,
7406 enum x86_intercept_stage stage,
7407 struct x86_exception *exception)
7409 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7411 switch (info->intercept) {
7413 * RDPID causes #UD if disabled through secondary execution controls.
7414 * Because it is marked as EmulateOnUD, we need to intercept it here.
7415 * Note, RDPID is hidden behind ENABLE_RDTSCP.
7417 case x86_intercept_rdpid:
7418 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7419 exception->vector = UD_VECTOR;
7420 exception->error_code_valid = false;
7421 return X86EMUL_PROPAGATE_FAULT;
7425 case x86_intercept_in:
7426 case x86_intercept_ins:
7427 case x86_intercept_out:
7428 case x86_intercept_outs:
7429 return vmx_check_intercept_io(vcpu, info);
7431 case x86_intercept_lgdt:
7432 case x86_intercept_lidt:
7433 case x86_intercept_lldt:
7434 case x86_intercept_ltr:
7435 case x86_intercept_sgdt:
7436 case x86_intercept_sidt:
7437 case x86_intercept_sldt:
7438 case x86_intercept_str:
7439 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7440 return X86EMUL_CONTINUE;
7442 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7445 /* TODO: check more intercepts... */
7450 return X86EMUL_UNHANDLEABLE;
7453 #ifdef CONFIG_X86_64
7454 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7455 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7456 u64 divisor, u64 *result)
7458 u64 low = a << shift, high = a >> (64 - shift);
7460 /* To avoid the overflow on divq */
7461 if (high >= divisor)
7464 /* Low hold the result, high hold rem which is discarded */
7465 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7466 "rm" (divisor), "0" (low), "1" (high));
7472 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7475 struct vcpu_vmx *vmx;
7476 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7477 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7481 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7482 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7483 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7484 ktimer->timer_advance_ns);
7486 if (delta_tsc > lapic_timer_advance_cycles)
7487 delta_tsc -= lapic_timer_advance_cycles;
7491 /* Convert to host delta tsc if tsc scaling is enabled */
7492 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7493 delta_tsc && u64_shl_div_u64(delta_tsc,
7494 kvm_tsc_scaling_ratio_frac_bits,
7495 vcpu->arch.l1_tsc_scaling_ratio, &delta_tsc))
7499 * If the delta tsc can't fit in the 32 bit after the multi shift,
7500 * we can't use the preemption timer.
7501 * It's possible that it fits on later vmentries, but checking
7502 * on every vmentry is costly so we just use an hrtimer.
7504 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7507 vmx->hv_deadline_tsc = tscl + delta_tsc;
7508 *expired = !delta_tsc;
7512 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7514 to_vmx(vcpu)->hv_deadline_tsc = -1;
7518 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7520 if (!kvm_pause_in_guest(vcpu->kvm))
7521 shrink_ple_window(vcpu);
7524 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
7526 struct vcpu_vmx *vmx = to_vmx(vcpu);
7528 if (is_guest_mode(vcpu)) {
7529 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
7534 * Note, cpu_dirty_logging_count can be changed concurrent with this
7535 * code, but in that case another update request will be made and so
7536 * the guest will never run with a stale PML value.
7538 if (vcpu->kvm->arch.cpu_dirty_logging_count)
7539 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7541 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7544 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7546 if (pi_pre_block(vcpu))
7549 if (kvm_lapic_hv_timer_in_use(vcpu))
7550 kvm_lapic_switch_to_sw_timer(vcpu);
7555 static void vmx_post_block(struct kvm_vcpu *vcpu)
7557 if (kvm_x86_ops.set_hv_timer)
7558 kvm_lapic_switch_to_hv_timer(vcpu);
7560 pi_post_block(vcpu);
7563 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7565 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7566 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7567 FEAT_CTL_LMCE_ENABLED;
7569 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7570 ~FEAT_CTL_LMCE_ENABLED;
7573 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7575 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7576 if (to_vmx(vcpu)->nested.nested_run_pending)
7578 return !is_smm(vcpu);
7581 static int vmx_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7583 struct vcpu_vmx *vmx = to_vmx(vcpu);
7585 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7586 if (vmx->nested.smm.guest_mode)
7587 nested_vmx_vmexit(vcpu, -1, 0, 0);
7589 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7590 vmx->nested.vmxon = false;
7591 vmx_clear_hlt(vcpu);
7595 static int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7597 struct vcpu_vmx *vmx = to_vmx(vcpu);
7600 if (vmx->nested.smm.vmxon) {
7601 vmx->nested.vmxon = true;
7602 vmx->nested.smm.vmxon = false;
7605 if (vmx->nested.smm.guest_mode) {
7606 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7610 vmx->nested.nested_run_pending = 1;
7611 vmx->nested.smm.guest_mode = false;
7616 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
7618 /* RSM will cause a vmexit anyway. */
7621 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7623 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
7626 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7628 if (is_guest_mode(vcpu)) {
7629 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7631 if (hrtimer_try_to_cancel(timer) == 1)
7632 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7636 static void hardware_unsetup(void)
7638 kvm_set_posted_intr_wakeup_handler(NULL);
7641 nested_vmx_hardware_unsetup();
7646 static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7648 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7649 BIT(APICV_INHIBIT_REASON_HYPERV);
7651 return supported & BIT(bit);
7654 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7655 .hardware_unsetup = hardware_unsetup,
7657 .hardware_enable = hardware_enable,
7658 .hardware_disable = hardware_disable,
7659 .cpu_has_accelerated_tpr = report_flexpriority,
7660 .has_emulated_msr = vmx_has_emulated_msr,
7662 .vm_size = sizeof(struct kvm_vmx),
7663 .vm_init = vmx_vm_init,
7665 .vcpu_create = vmx_create_vcpu,
7666 .vcpu_free = vmx_free_vcpu,
7667 .vcpu_reset = vmx_vcpu_reset,
7669 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7670 .vcpu_load = vmx_vcpu_load,
7671 .vcpu_put = vmx_vcpu_put,
7673 .update_exception_bitmap = vmx_update_exception_bitmap,
7674 .get_msr_feature = vmx_get_msr_feature,
7675 .get_msr = vmx_get_msr,
7676 .set_msr = vmx_set_msr,
7677 .get_segment_base = vmx_get_segment_base,
7678 .get_segment = vmx_get_segment,
7679 .set_segment = vmx_set_segment,
7680 .get_cpl = vmx_get_cpl,
7681 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7682 .set_cr0 = vmx_set_cr0,
7683 .is_valid_cr4 = vmx_is_valid_cr4,
7684 .set_cr4 = vmx_set_cr4,
7685 .set_efer = vmx_set_efer,
7686 .get_idt = vmx_get_idt,
7687 .set_idt = vmx_set_idt,
7688 .get_gdt = vmx_get_gdt,
7689 .set_gdt = vmx_set_gdt,
7690 .set_dr7 = vmx_set_dr7,
7691 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7692 .cache_reg = vmx_cache_reg,
7693 .get_rflags = vmx_get_rflags,
7694 .set_rflags = vmx_set_rflags,
7695 .get_if_flag = vmx_get_if_flag,
7697 .tlb_flush_all = vmx_flush_tlb_all,
7698 .tlb_flush_current = vmx_flush_tlb_current,
7699 .tlb_flush_gva = vmx_flush_tlb_gva,
7700 .tlb_flush_guest = vmx_flush_tlb_guest,
7702 .run = vmx_vcpu_run,
7703 .handle_exit = vmx_handle_exit,
7704 .skip_emulated_instruction = vmx_skip_emulated_instruction,
7705 .update_emulated_instruction = vmx_update_emulated_instruction,
7706 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7707 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7708 .patch_hypercall = vmx_patch_hypercall,
7709 .set_irq = vmx_inject_irq,
7710 .set_nmi = vmx_inject_nmi,
7711 .queue_exception = vmx_queue_exception,
7712 .cancel_injection = vmx_cancel_injection,
7713 .interrupt_allowed = vmx_interrupt_allowed,
7714 .nmi_allowed = vmx_nmi_allowed,
7715 .get_nmi_mask = vmx_get_nmi_mask,
7716 .set_nmi_mask = vmx_set_nmi_mask,
7717 .enable_nmi_window = vmx_enable_nmi_window,
7718 .enable_irq_window = vmx_enable_irq_window,
7719 .update_cr8_intercept = vmx_update_cr8_intercept,
7720 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7721 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7722 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7723 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7724 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7725 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7726 .hwapic_irr_update = vmx_hwapic_irr_update,
7727 .hwapic_isr_update = vmx_hwapic_isr_update,
7728 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7729 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7730 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7731 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
7733 .set_tss_addr = vmx_set_tss_addr,
7734 .set_identity_map_addr = vmx_set_identity_map_addr,
7735 .get_mt_mask = vmx_get_mt_mask,
7737 .get_exit_info = vmx_get_exit_info,
7739 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
7741 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7743 .get_l2_tsc_offset = vmx_get_l2_tsc_offset,
7744 .get_l2_tsc_multiplier = vmx_get_l2_tsc_multiplier,
7745 .write_tsc_offset = vmx_write_tsc_offset,
7746 .write_tsc_multiplier = vmx_write_tsc_multiplier,
7748 .load_mmu_pgd = vmx_load_mmu_pgd,
7750 .check_intercept = vmx_check_intercept,
7751 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7753 .request_immediate_exit = vmx_request_immediate_exit,
7755 .sched_in = vmx_sched_in,
7757 .cpu_dirty_log_size = PML_ENTITY_NUM,
7758 .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
7760 .pre_block = vmx_pre_block,
7761 .post_block = vmx_post_block,
7763 .pmu_ops = &intel_pmu_ops,
7764 .nested_ops = &vmx_nested_ops,
7766 .update_pi_irte = pi_update_irte,
7767 .start_assignment = vmx_pi_start_assignment,
7769 #ifdef CONFIG_X86_64
7770 .set_hv_timer = vmx_set_hv_timer,
7771 .cancel_hv_timer = vmx_cancel_hv_timer,
7774 .setup_mce = vmx_setup_mce,
7776 .smi_allowed = vmx_smi_allowed,
7777 .enter_smm = vmx_enter_smm,
7778 .leave_smm = vmx_leave_smm,
7779 .enable_smi_window = vmx_enable_smi_window,
7781 .can_emulate_instruction = vmx_can_emulate_instruction,
7782 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7783 .migrate_timers = vmx_migrate_timers,
7785 .msr_filter_changed = vmx_msr_filter_changed,
7786 .complete_emulated_msr = kvm_complete_insn_gp,
7788 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
7791 static __init void vmx_setup_user_return_msrs(void)
7795 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
7796 * will emulate SYSCALL in legacy mode if the vendor string in guest
7797 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
7798 * support this emulation, MSR_STAR is included in the list for i386,
7799 * but is never loaded into hardware. MSR_CSTAR is also never loaded
7800 * into hardware and is here purely for emulation purposes.
7802 const u32 vmx_uret_msrs_list[] = {
7803 #ifdef CONFIG_X86_64
7804 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
7806 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
7811 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
7813 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
7814 kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
7817 static __init int hardware_setup(void)
7819 unsigned long host_bndcfgs;
7821 int r, ept_lpage_level;
7824 host_idt_base = dt.address;
7826 vmx_setup_user_return_msrs();
7828 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7831 if (boot_cpu_has(X86_FEATURE_NX))
7832 kvm_enable_efer_bits(EFER_NX);
7834 if (boot_cpu_has(X86_FEATURE_MPX)) {
7835 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7836 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7839 if (!cpu_has_vmx_mpx())
7840 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
7841 XFEATURE_MASK_BNDCSR);
7843 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7844 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7847 if (!cpu_has_vmx_ept() ||
7848 !cpu_has_vmx_ept_4levels() ||
7849 !cpu_has_vmx_ept_mt_wb() ||
7850 !cpu_has_vmx_invept_global())
7853 /* NX support is required for shadow paging. */
7854 if (!enable_ept && !boot_cpu_has(X86_FEATURE_NX)) {
7855 pr_err_ratelimited("kvm: NX (Execute Disable) not supported\n");
7859 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7860 enable_ept_ad_bits = 0;
7862 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7863 enable_unrestricted_guest = 0;
7865 if (!cpu_has_vmx_flexpriority())
7866 flexpriority_enabled = 0;
7868 if (!cpu_has_virtual_nmis())
7872 * set_apic_access_page_addr() is used to reload apic access
7873 * page upon invalidation. No need to do anything if not
7874 * using the APIC_ACCESS_ADDR VMCS field.
7876 if (!flexpriority_enabled)
7877 vmx_x86_ops.set_apic_access_page_addr = NULL;
7879 if (!cpu_has_vmx_tpr_shadow())
7880 vmx_x86_ops.update_cr8_intercept = NULL;
7882 #if IS_ENABLED(CONFIG_HYPERV)
7883 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7885 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
7886 vmx_x86_ops.tlb_remote_flush_with_range =
7887 hv_remote_flush_tlb_with_range;
7891 if (!cpu_has_vmx_ple()) {
7894 ple_window_grow = 0;
7896 ple_window_shrink = 0;
7899 if (!cpu_has_vmx_apicv())
7902 vmx_x86_ops.sync_pir_to_irr = NULL;
7904 if (cpu_has_vmx_tsc_scaling()) {
7905 kvm_has_tsc_control = true;
7906 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7907 kvm_tsc_scaling_ratio_frac_bits = 48;
7910 kvm_has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
7912 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7915 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
7916 cpu_has_vmx_ept_execute_only());
7919 ept_lpage_level = 0;
7920 else if (cpu_has_vmx_ept_1g_page())
7921 ept_lpage_level = PG_LEVEL_1G;
7922 else if (cpu_has_vmx_ept_2m_page())
7923 ept_lpage_level = PG_LEVEL_2M;
7925 ept_lpage_level = PG_LEVEL_4K;
7926 kvm_configure_mmu(enable_ept, 0, vmx_get_max_tdp_level(),
7930 * Only enable PML when hardware supports PML feature, and both EPT
7931 * and EPT A/D bit features are enabled -- PML depends on them to work.
7933 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7937 vmx_x86_ops.cpu_dirty_log_size = 0;
7939 if (!cpu_has_vmx_preemption_timer())
7940 enable_preemption_timer = false;
7942 if (enable_preemption_timer) {
7943 u64 use_timer_freq = 5000ULL * 1000 * 1000;
7946 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7947 cpu_preemption_timer_multi =
7948 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7951 use_timer_freq = (u64)tsc_khz * 1000;
7952 use_timer_freq >>= cpu_preemption_timer_multi;
7955 * KVM "disables" the preemption timer by setting it to its max
7956 * value. Don't use the timer if it might cause spurious exits
7957 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
7959 if (use_timer_freq > 0xffffffffu / 10)
7960 enable_preemption_timer = false;
7963 if (!enable_preemption_timer) {
7964 vmx_x86_ops.set_hv_timer = NULL;
7965 vmx_x86_ops.cancel_hv_timer = NULL;
7966 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
7969 kvm_mce_cap_supported |= MCG_LMCE_P;
7971 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7973 if (!enable_ept || !cpu_has_vmx_intel_pt())
7974 pt_mode = PT_MODE_SYSTEM;
7976 setup_default_sgx_lepubkeyhash();
7979 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7980 vmx_capability.ept);
7982 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7989 r = alloc_kvm_area();
7991 nested_vmx_hardware_unsetup();
7993 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
7998 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
7999 .cpu_has_kvm_support = cpu_has_kvm_support,
8000 .disabled_by_bios = vmx_disabled_by_bios,
8001 .check_processor_compatibility = vmx_check_processor_compat,
8002 .hardware_setup = hardware_setup,
8003 .intel_pt_intr_in_guest = vmx_pt_mode_is_host_guest,
8005 .runtime_ops = &vmx_x86_ops,
8008 static void vmx_cleanup_l1d_flush(void)
8010 if (vmx_l1d_flush_pages) {
8011 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8012 vmx_l1d_flush_pages = NULL;
8014 /* Restore state so sysfs ignores VMX */
8015 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8018 static void vmx_exit(void)
8020 #ifdef CONFIG_KEXEC_CORE
8021 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8027 #if IS_ENABLED(CONFIG_HYPERV)
8028 if (static_branch_unlikely(&enable_evmcs)) {
8030 struct hv_vp_assist_page *vp_ap;
8032 * Reset everything to support using non-enlightened VMCS
8033 * access later (e.g. when we reload the module with
8034 * enlightened_vmcs=0)
8036 for_each_online_cpu(cpu) {
8037 vp_ap = hv_get_vp_assist_page(cpu);
8042 vp_ap->nested_control.features.directhypercall = 0;
8043 vp_ap->current_nested_vmcs = 0;
8044 vp_ap->enlighten_vmentry = 0;
8047 static_branch_disable(&enable_evmcs);
8050 vmx_cleanup_l1d_flush();
8052 allow_smaller_maxphyaddr = false;
8054 module_exit(vmx_exit);
8056 static int __init vmx_init(void)
8060 #if IS_ENABLED(CONFIG_HYPERV)
8062 * Enlightened VMCS usage should be recommended and the host needs
8063 * to support eVMCS v1 or above. We can also disable eVMCS support
8064 * with module parameter.
8066 if (enlightened_vmcs &&
8067 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8068 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8069 KVM_EVMCS_VERSION) {
8072 /* Check that we have assist pages on all online CPUs */
8073 for_each_online_cpu(cpu) {
8074 if (!hv_get_vp_assist_page(cpu)) {
8075 enlightened_vmcs = false;
8080 if (enlightened_vmcs) {
8081 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8082 static_branch_enable(&enable_evmcs);
8085 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8086 vmx_x86_ops.enable_direct_tlbflush
8087 = hv_enable_direct_tlbflush;
8090 enlightened_vmcs = false;
8094 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8095 __alignof__(struct vcpu_vmx), THIS_MODULE);
8100 * Must be called after kvm_init() so enable_ept is properly set
8101 * up. Hand the parameter mitigation value in which was stored in
8102 * the pre module init parser. If no parameter was given, it will
8103 * contain 'auto' which will be turned into the default 'cond'
8106 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8112 vmx_setup_fb_clear_ctrl();
8114 for_each_possible_cpu(cpu) {
8115 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8120 #ifdef CONFIG_KEXEC_CORE
8121 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8122 crash_vmclear_local_loaded_vmcss);
8124 vmx_check_vmcs12_offsets();
8127 * Shadow paging doesn't have a (further) performance penalty
8128 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8132 allow_smaller_maxphyaddr = true;
8136 module_init(vmx_init);