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/frame.h>
17 #include <linux/highmem.h>
18 #include <linux/hrtimer.h>
19 #include <linux/kernel.h>
20 #include <linux/kvm_host.h>
21 #include <linux/module.h>
22 #include <linux/moduleparam.h>
23 #include <linux/mod_devicetable.h>
25 #include <linux/sched.h>
26 #include <linux/sched/smt.h>
27 #include <linux/slab.h>
28 #include <linux/tboot.h>
29 #include <linux/trace_events.h>
34 #include <asm/cpu_device_id.h>
35 #include <asm/debugreg.h>
37 #include <asm/fpu/internal.h>
39 #include <asm/irq_remapping.h>
40 #include <asm/kexec.h>
41 #include <asm/perf_event.h>
43 #include <asm/mmu_context.h>
44 #include <asm/mshyperv.h>
45 #include <asm/spec-ctrl.h>
46 #include <asm/virtext.h>
49 #include "capabilities.h"
53 #include "kvm_cache_regs.h"
65 MODULE_AUTHOR("Qumranet");
66 MODULE_LICENSE("GPL");
68 static const struct x86_cpu_id vmx_cpu_id[] = {
69 X86_FEATURE_MATCH(X86_FEATURE_VMX),
72 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
74 bool __read_mostly enable_vpid = 1;
75 module_param_named(vpid, enable_vpid, bool, 0444);
77 static bool __read_mostly enable_vnmi = 1;
78 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
80 bool __read_mostly flexpriority_enabled = 1;
81 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
83 bool __read_mostly enable_ept = 1;
84 module_param_named(ept, enable_ept, bool, S_IRUGO);
86 bool __read_mostly enable_unrestricted_guest = 1;
87 module_param_named(unrestricted_guest,
88 enable_unrestricted_guest, bool, S_IRUGO);
90 bool __read_mostly enable_ept_ad_bits = 1;
91 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
93 static bool __read_mostly emulate_invalid_guest_state = true;
94 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
96 static bool __read_mostly fasteoi = 1;
97 module_param(fasteoi, bool, S_IRUGO);
99 bool __read_mostly enable_apicv = 1;
100 module_param(enable_apicv, bool, S_IRUGO);
103 * If nested=1, nested virtualization is supported, i.e., guests may use
104 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
105 * use VMX instructions.
107 static bool __read_mostly nested = 1;
108 module_param(nested, bool, S_IRUGO);
110 static u64 __read_mostly host_xss;
112 bool __read_mostly enable_pml = 1;
113 module_param_named(pml, enable_pml, bool, S_IRUGO);
115 static bool __read_mostly dump_invalid_vmcs = 0;
116 module_param(dump_invalid_vmcs, bool, 0644);
118 #define MSR_BITMAP_MODE_X2APIC 1
119 #define MSR_BITMAP_MODE_X2APIC_APICV 2
121 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
123 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
124 static int __read_mostly cpu_preemption_timer_multi;
125 static bool __read_mostly enable_preemption_timer = 1;
127 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
130 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
131 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
132 #define KVM_VM_CR0_ALWAYS_ON \
133 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
134 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
135 #define KVM_CR4_GUEST_OWNED_BITS \
136 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
137 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
139 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
140 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
141 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
143 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
145 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
146 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
147 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
148 RTIT_STATUS_BYTECNT))
150 #define MSR_IA32_RTIT_OUTPUT_BASE_MASK \
151 (~((1UL << cpuid_query_maxphyaddr(vcpu)) - 1) | 0x7f)
154 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
155 * ple_gap: upper bound on the amount of time between two successive
156 * executions of PAUSE in a loop. Also indicate if ple enabled.
157 * According to test, this time is usually smaller than 128 cycles.
158 * ple_window: upper bound on the amount of time a guest is allowed to execute
159 * in a PAUSE loop. Tests indicate that most spinlocks are held for
160 * less than 2^12 cycles
161 * Time is measured based on a counter that runs at the same rate as the TSC,
162 * refer SDM volume 3b section 21.6.13 & 22.1.3.
164 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
165 module_param(ple_gap, uint, 0444);
167 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
168 module_param(ple_window, uint, 0444);
170 /* Default doubles per-vcpu window every exit. */
171 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
172 module_param(ple_window_grow, uint, 0444);
174 /* Default resets per-vcpu window every exit to ple_window. */
175 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
176 module_param(ple_window_shrink, uint, 0444);
178 /* Default is to compute the maximum so we can never overflow. */
179 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
180 module_param(ple_window_max, uint, 0444);
182 /* Default is SYSTEM mode, 1 for host-guest mode */
183 int __read_mostly pt_mode = PT_MODE_SYSTEM;
184 module_param(pt_mode, int, S_IRUGO);
186 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
187 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
188 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
190 /* Storage for pre module init parameter parsing */
191 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
193 static const struct {
196 } vmentry_l1d_param[] = {
197 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
198 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
199 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
200 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
201 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
202 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
205 #define L1D_CACHE_ORDER 4
206 static void *vmx_l1d_flush_pages;
208 /* Control for disabling CPU Fill buffer clear */
209 static bool __read_mostly vmx_fb_clear_ctrl_available;
211 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
216 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
217 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
222 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
226 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
229 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
230 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
231 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
236 /* If set to auto use the default l1tf mitigation method */
237 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
238 switch (l1tf_mitigation) {
239 case L1TF_MITIGATION_OFF:
240 l1tf = VMENTER_L1D_FLUSH_NEVER;
242 case L1TF_MITIGATION_FLUSH_NOWARN:
243 case L1TF_MITIGATION_FLUSH:
244 case L1TF_MITIGATION_FLUSH_NOSMT:
245 l1tf = VMENTER_L1D_FLUSH_COND;
247 case L1TF_MITIGATION_FULL:
248 case L1TF_MITIGATION_FULL_FORCE:
249 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
252 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
253 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
256 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
257 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
259 * This allocation for vmx_l1d_flush_pages is not tied to a VM
260 * lifetime and so should not be charged to a memcg.
262 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
265 vmx_l1d_flush_pages = page_address(page);
268 * Initialize each page with a different pattern in
269 * order to protect against KSM in the nested
270 * virtualization case.
272 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
273 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
278 l1tf_vmx_mitigation = l1tf;
280 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
281 static_branch_enable(&vmx_l1d_should_flush);
283 static_branch_disable(&vmx_l1d_should_flush);
285 if (l1tf == VMENTER_L1D_FLUSH_COND)
286 static_branch_enable(&vmx_l1d_flush_cond);
288 static_branch_disable(&vmx_l1d_flush_cond);
292 static int vmentry_l1d_flush_parse(const char *s)
297 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
298 if (vmentry_l1d_param[i].for_parse &&
299 sysfs_streq(s, vmentry_l1d_param[i].option))
306 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
310 l1tf = vmentry_l1d_flush_parse(s);
314 if (!boot_cpu_has(X86_BUG_L1TF))
318 * Has vmx_init() run already? If not then this is the pre init
319 * parameter parsing. In that case just store the value and let
320 * vmx_init() do the proper setup after enable_ept has been
323 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
324 vmentry_l1d_flush_param = l1tf;
328 mutex_lock(&vmx_l1d_flush_mutex);
329 ret = vmx_setup_l1d_flush(l1tf);
330 mutex_unlock(&vmx_l1d_flush_mutex);
334 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
336 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
337 return sprintf(s, "???\n");
339 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
342 static void vmx_setup_fb_clear_ctrl(void)
346 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES) &&
347 !boot_cpu_has_bug(X86_BUG_MDS) &&
348 !boot_cpu_has_bug(X86_BUG_TAA)) {
349 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
350 if (msr & ARCH_CAP_FB_CLEAR_CTRL)
351 vmx_fb_clear_ctrl_available = true;
355 static __always_inline void vmx_disable_fb_clear(struct vcpu_vmx *vmx)
359 if (!vmx->disable_fb_clear)
362 msr = __rdmsr(MSR_IA32_MCU_OPT_CTRL);
364 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, msr);
365 /* Cache the MSR value to avoid reading it later */
366 vmx->msr_ia32_mcu_opt_ctrl = msr;
369 static __always_inline void vmx_enable_fb_clear(struct vcpu_vmx *vmx)
371 if (!vmx->disable_fb_clear)
374 vmx->msr_ia32_mcu_opt_ctrl &= ~FB_CLEAR_DIS;
375 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, vmx->msr_ia32_mcu_opt_ctrl);
378 static void vmx_update_fb_clear_dis(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx)
380 vmx->disable_fb_clear = vmx_fb_clear_ctrl_available;
383 * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS
384 * at VMEntry. Skip the MSR read/write when a guest has no use case to
387 if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) ||
388 ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) &&
389 (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) &&
390 (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) &&
391 (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) &&
392 (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO)))
393 vmx->disable_fb_clear = false;
396 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
397 .set = vmentry_l1d_flush_set,
398 .get = vmentry_l1d_flush_get,
400 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
402 static bool guest_state_valid(struct kvm_vcpu *vcpu);
403 static u32 vmx_segment_access_rights(struct kvm_segment *var);
404 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
407 void vmx_vmexit(void);
409 #define vmx_insn_failed(fmt...) \
412 pr_warn_ratelimited(fmt); \
415 asmlinkage void vmread_error(unsigned long field, bool fault)
418 kvm_spurious_fault();
420 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
423 noinline void vmwrite_error(unsigned long field, unsigned long value)
425 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
426 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
429 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
431 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
434 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
436 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
439 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
441 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
445 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
447 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
451 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
452 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
454 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
455 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
457 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
460 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
461 * can find which vCPU should be waken up.
463 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
464 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
466 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
467 static DEFINE_SPINLOCK(vmx_vpid_lock);
469 struct vmcs_config vmcs_config;
470 struct vmx_capability vmx_capability;
472 #define VMX_SEGMENT_FIELD(seg) \
473 [VCPU_SREG_##seg] = { \
474 .selector = GUEST_##seg##_SELECTOR, \
475 .base = GUEST_##seg##_BASE, \
476 .limit = GUEST_##seg##_LIMIT, \
477 .ar_bytes = GUEST_##seg##_AR_BYTES, \
480 static const struct kvm_vmx_segment_field {
485 } kvm_vmx_segment_fields[] = {
486 VMX_SEGMENT_FIELD(CS),
487 VMX_SEGMENT_FIELD(DS),
488 VMX_SEGMENT_FIELD(ES),
489 VMX_SEGMENT_FIELD(FS),
490 VMX_SEGMENT_FIELD(GS),
491 VMX_SEGMENT_FIELD(SS),
492 VMX_SEGMENT_FIELD(TR),
493 VMX_SEGMENT_FIELD(LDTR),
497 static unsigned long host_idt_base;
500 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
501 * will emulate SYSCALL in legacy mode if the vendor string in guest
502 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
503 * support this emulation, IA32_STAR must always be included in
504 * vmx_msr_index[], even in i386 builds.
506 const u32 vmx_msr_index[] = {
508 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
510 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
513 #if IS_ENABLED(CONFIG_HYPERV)
514 static bool __read_mostly enlightened_vmcs = true;
515 module_param(enlightened_vmcs, bool, 0444);
517 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
518 static void check_ept_pointer_match(struct kvm *kvm)
520 struct kvm_vcpu *vcpu;
521 u64 tmp_eptp = INVALID_PAGE;
524 kvm_for_each_vcpu(i, vcpu, kvm) {
525 if (!VALID_PAGE(tmp_eptp)) {
526 tmp_eptp = to_vmx(vcpu)->ept_pointer;
527 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
528 to_kvm_vmx(kvm)->ept_pointers_match
529 = EPT_POINTERS_MISMATCH;
534 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
537 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
540 struct kvm_tlb_range *range = data;
542 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
546 static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
547 struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
549 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
552 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
553 * of the base of EPT PML4 table, strip off EPT configuration
557 return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
558 kvm_fill_hv_flush_list_func, (void *)range);
560 return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
563 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
564 struct kvm_tlb_range *range)
566 struct kvm_vcpu *vcpu;
569 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
571 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
572 check_ept_pointer_match(kvm);
574 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
575 kvm_for_each_vcpu(i, vcpu, kvm) {
576 /* If ept_pointer is invalid pointer, bypass flush request. */
577 if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
578 ret |= __hv_remote_flush_tlb_with_range(
582 ret = __hv_remote_flush_tlb_with_range(kvm,
583 kvm_get_vcpu(kvm, 0), range);
586 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
589 static int hv_remote_flush_tlb(struct kvm *kvm)
591 return hv_remote_flush_tlb_with_range(kvm, NULL);
594 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
596 struct hv_enlightened_vmcs *evmcs;
597 struct hv_partition_assist_pg **p_hv_pa_pg =
598 &vcpu->kvm->arch.hyperv.hv_pa_pg;
600 * Synthetic VM-Exit is not enabled in current code and so All
601 * evmcs in singe VM shares same assist page.
604 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL);
609 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
611 evmcs->partition_assist_page =
613 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
614 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
619 #endif /* IS_ENABLED(CONFIG_HYPERV) */
622 * Comment's format: document - errata name - stepping - processor name.
624 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
626 static u32 vmx_preemption_cpu_tfms[] = {
627 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
629 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
630 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
631 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
633 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
635 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
636 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
638 * 320767.pdf - AAP86 - B1 -
639 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
642 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
644 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
646 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
648 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
649 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
650 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
652 /* Xeon E3-1220 V2 */
656 static inline bool cpu_has_broken_vmx_preemption_timer(void)
658 u32 eax = cpuid_eax(0x00000001), i;
660 /* Clear the reserved bits */
661 eax &= ~(0x3U << 14 | 0xfU << 28);
662 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
663 if (eax == vmx_preemption_cpu_tfms[i])
669 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
671 return flexpriority_enabled && lapic_in_kernel(vcpu);
674 static inline bool report_flexpriority(void)
676 return flexpriority_enabled;
679 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
683 for (i = 0; i < vmx->nmsrs; ++i)
684 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
689 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
693 i = __find_msr_index(vmx, msr);
695 return &vmx->guest_msrs[i];
699 void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
701 vmcs_clear(loaded_vmcs->vmcs);
702 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
703 vmcs_clear(loaded_vmcs->shadow_vmcs);
704 loaded_vmcs->cpu = -1;
705 loaded_vmcs->launched = 0;
708 #ifdef CONFIG_KEXEC_CORE
709 static void crash_vmclear_local_loaded_vmcss(void)
711 int cpu = raw_smp_processor_id();
712 struct loaded_vmcs *v;
714 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
715 loaded_vmcss_on_cpu_link)
718 #endif /* CONFIG_KEXEC_CORE */
720 static void __loaded_vmcs_clear(void *arg)
722 struct loaded_vmcs *loaded_vmcs = arg;
723 int cpu = raw_smp_processor_id();
725 if (loaded_vmcs->cpu != cpu)
726 return; /* vcpu migration can race with cpu offline */
727 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
728 per_cpu(current_vmcs, cpu) = NULL;
730 vmcs_clear(loaded_vmcs->vmcs);
731 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
732 vmcs_clear(loaded_vmcs->shadow_vmcs);
734 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
737 * Ensure all writes to loaded_vmcs, including deleting it from its
738 * current percpu list, complete before setting loaded_vmcs->vcpu to
739 * -1, otherwise a different cpu can see vcpu == -1 first and add
740 * loaded_vmcs to its percpu list before it's deleted from this cpu's
741 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
745 loaded_vmcs->cpu = -1;
746 loaded_vmcs->launched = 0;
749 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
751 int cpu = loaded_vmcs->cpu;
754 smp_call_function_single(cpu,
755 __loaded_vmcs_clear, loaded_vmcs, 1);
758 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
762 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
764 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
765 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
766 vmx->segment_cache.bitmask = 0;
768 ret = vmx->segment_cache.bitmask & mask;
769 vmx->segment_cache.bitmask |= mask;
773 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
775 u16 *p = &vmx->segment_cache.seg[seg].selector;
777 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
778 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
782 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
784 ulong *p = &vmx->segment_cache.seg[seg].base;
786 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
787 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
791 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
793 u32 *p = &vmx->segment_cache.seg[seg].limit;
795 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
796 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
800 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
802 u32 *p = &vmx->segment_cache.seg[seg].ar;
804 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
805 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
809 void update_exception_bitmap(struct kvm_vcpu *vcpu)
813 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
814 (1u << DB_VECTOR) | (1u << AC_VECTOR);
816 * Guest access to VMware backdoor ports could legitimately
817 * trigger #GP because of TSS I/O permission bitmap.
818 * We intercept those #GP and allow access to them anyway
821 if (enable_vmware_backdoor)
822 eb |= (1u << GP_VECTOR);
823 if ((vcpu->guest_debug &
824 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
825 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
826 eb |= 1u << BP_VECTOR;
827 if (to_vmx(vcpu)->rmode.vm86_active)
830 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
832 /* When we are running a nested L2 guest and L1 specified for it a
833 * certain exception bitmap, we must trap the same exceptions and pass
834 * them to L1. When running L2, we will only handle the exceptions
835 * specified above if L1 did not want them.
837 if (is_guest_mode(vcpu))
838 eb |= get_vmcs12(vcpu)->exception_bitmap;
840 vmcs_write32(EXCEPTION_BITMAP, eb);
844 * Check if MSR is intercepted for currently loaded MSR bitmap.
846 static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr)
848 unsigned long *msr_bitmap;
849 int f = sizeof(unsigned long);
851 if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS))
854 msr_bitmap = vmx->loaded_vmcs->msr_bitmap;
857 return !!test_bit(msr, msr_bitmap + 0x800 / f);
858 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
860 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
866 unsigned int __vmx_vcpu_run_flags(struct vcpu_vmx *vmx)
868 unsigned int flags = 0;
870 if (vmx->loaded_vmcs->launched)
871 flags |= VMX_RUN_VMRESUME;
874 * If writes to the SPEC_CTRL MSR aren't intercepted, the guest is free
875 * to change it directly without causing a vmexit. In that case read
876 * it after vmexit and store it in vmx->spec_ctrl.
878 if (unlikely(!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL)))
879 flags |= VMX_RUN_SAVE_SPEC_CTRL;
884 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
885 unsigned long entry, unsigned long exit)
887 vm_entry_controls_clearbit(vmx, entry);
888 vm_exit_controls_clearbit(vmx, exit);
891 static int find_msr(struct vmx_msrs *m, unsigned int msr)
895 for (i = 0; i < m->nr; ++i) {
896 if (m->val[i].index == msr)
902 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
905 struct msr_autoload *m = &vmx->msr_autoload;
909 if (cpu_has_load_ia32_efer()) {
910 clear_atomic_switch_msr_special(vmx,
911 VM_ENTRY_LOAD_IA32_EFER,
912 VM_EXIT_LOAD_IA32_EFER);
916 case MSR_CORE_PERF_GLOBAL_CTRL:
917 if (cpu_has_load_perf_global_ctrl()) {
918 clear_atomic_switch_msr_special(vmx,
919 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
920 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
925 i = find_msr(&m->guest, msr);
929 m->guest.val[i] = m->guest.val[m->guest.nr];
930 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
933 i = find_msr(&m->host, msr);
938 m->host.val[i] = m->host.val[m->host.nr];
939 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
942 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
943 unsigned long entry, unsigned long exit,
944 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
945 u64 guest_val, u64 host_val)
947 vmcs_write64(guest_val_vmcs, guest_val);
948 if (host_val_vmcs != HOST_IA32_EFER)
949 vmcs_write64(host_val_vmcs, host_val);
950 vm_entry_controls_setbit(vmx, entry);
951 vm_exit_controls_setbit(vmx, exit);
954 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
955 u64 guest_val, u64 host_val, bool entry_only)
958 struct msr_autoload *m = &vmx->msr_autoload;
962 if (cpu_has_load_ia32_efer()) {
963 add_atomic_switch_msr_special(vmx,
964 VM_ENTRY_LOAD_IA32_EFER,
965 VM_EXIT_LOAD_IA32_EFER,
968 guest_val, host_val);
972 case MSR_CORE_PERF_GLOBAL_CTRL:
973 if (cpu_has_load_perf_global_ctrl()) {
974 add_atomic_switch_msr_special(vmx,
975 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
976 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
977 GUEST_IA32_PERF_GLOBAL_CTRL,
978 HOST_IA32_PERF_GLOBAL_CTRL,
979 guest_val, host_val);
983 case MSR_IA32_PEBS_ENABLE:
984 /* PEBS needs a quiescent period after being disabled (to write
985 * a record). Disabling PEBS through VMX MSR swapping doesn't
986 * provide that period, so a CPU could write host's record into
989 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
992 i = find_msr(&m->guest, msr);
994 j = find_msr(&m->host, msr);
996 if ((i < 0 && m->guest.nr == NR_AUTOLOAD_MSRS) ||
997 (j < 0 && m->host.nr == NR_AUTOLOAD_MSRS)) {
998 printk_once(KERN_WARNING "Not enough msr switch entries. "
999 "Can't add msr %x\n", msr);
1004 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1006 m->guest.val[i].index = msr;
1007 m->guest.val[i].value = guest_val;
1014 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1016 m->host.val[j].index = msr;
1017 m->host.val[j].value = host_val;
1020 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
1022 u64 guest_efer = vmx->vcpu.arch.efer;
1023 u64 ignore_bits = 0;
1025 /* Shadow paging assumes NX to be available. */
1027 guest_efer |= EFER_NX;
1030 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1032 ignore_bits |= EFER_SCE;
1033 #ifdef CONFIG_X86_64
1034 ignore_bits |= EFER_LMA | EFER_LME;
1035 /* SCE is meaningful only in long mode on Intel */
1036 if (guest_efer & EFER_LMA)
1037 ignore_bits &= ~(u64)EFER_SCE;
1041 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1042 * On CPUs that support "load IA32_EFER", always switch EFER
1043 * atomically, since it's faster than switching it manually.
1045 if (cpu_has_load_ia32_efer() ||
1046 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1047 if (!(guest_efer & EFER_LMA))
1048 guest_efer &= ~EFER_LME;
1049 if (guest_efer != host_efer)
1050 add_atomic_switch_msr(vmx, MSR_EFER,
1051 guest_efer, host_efer, false);
1053 clear_atomic_switch_msr(vmx, MSR_EFER);
1056 clear_atomic_switch_msr(vmx, MSR_EFER);
1058 guest_efer &= ~ignore_bits;
1059 guest_efer |= host_efer & ignore_bits;
1061 vmx->guest_msrs[efer_offset].data = guest_efer;
1062 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1068 #ifdef CONFIG_X86_32
1070 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1071 * VMCS rather than the segment table. KVM uses this helper to figure
1072 * out the current bases to poke them into the VMCS before entry.
1074 static unsigned long segment_base(u16 selector)
1076 struct desc_struct *table;
1079 if (!(selector & ~SEGMENT_RPL_MASK))
1082 table = get_current_gdt_ro();
1084 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1085 u16 ldt_selector = kvm_read_ldt();
1087 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1090 table = (struct desc_struct *)segment_base(ldt_selector);
1092 v = get_desc_base(&table[selector >> 3]);
1097 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1101 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1102 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1103 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1104 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1105 for (i = 0; i < addr_range; i++) {
1106 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1107 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1111 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1115 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1116 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1117 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1118 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1119 for (i = 0; i < addr_range; i++) {
1120 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1121 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1125 static void pt_guest_enter(struct vcpu_vmx *vmx)
1127 if (pt_mode == PT_MODE_SYSTEM)
1131 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1132 * Save host state before VM entry.
1134 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1135 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1136 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1137 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1138 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1142 static void pt_guest_exit(struct vcpu_vmx *vmx)
1144 if (pt_mode == PT_MODE_SYSTEM)
1147 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1148 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1149 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1152 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1153 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1156 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1157 unsigned long fs_base, unsigned long gs_base)
1159 if (unlikely(fs_sel != host->fs_sel)) {
1161 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1163 vmcs_write16(HOST_FS_SELECTOR, 0);
1164 host->fs_sel = fs_sel;
1166 if (unlikely(gs_sel != host->gs_sel)) {
1168 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1170 vmcs_write16(HOST_GS_SELECTOR, 0);
1171 host->gs_sel = gs_sel;
1173 if (unlikely(fs_base != host->fs_base)) {
1174 vmcs_writel(HOST_FS_BASE, fs_base);
1175 host->fs_base = fs_base;
1177 if (unlikely(gs_base != host->gs_base)) {
1178 vmcs_writel(HOST_GS_BASE, gs_base);
1179 host->gs_base = gs_base;
1183 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1185 struct vcpu_vmx *vmx = to_vmx(vcpu);
1186 struct vmcs_host_state *host_state;
1187 #ifdef CONFIG_X86_64
1188 int cpu = raw_smp_processor_id();
1190 unsigned long fs_base, gs_base;
1194 vmx->req_immediate_exit = false;
1197 * Note that guest MSRs to be saved/restored can also be changed
1198 * when guest state is loaded. This happens when guest transitions
1199 * to/from long-mode by setting MSR_EFER.LMA.
1201 if (!vmx->guest_msrs_ready) {
1202 vmx->guest_msrs_ready = true;
1203 for (i = 0; i < vmx->save_nmsrs; ++i)
1204 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1205 vmx->guest_msrs[i].data,
1206 vmx->guest_msrs[i].mask);
1210 if (vmx->nested.need_vmcs12_to_shadow_sync)
1211 nested_sync_vmcs12_to_shadow(vcpu);
1213 if (vmx->guest_state_loaded)
1216 host_state = &vmx->loaded_vmcs->host_state;
1219 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1220 * allow segment selectors with cpl > 0 or ti == 1.
1222 host_state->ldt_sel = kvm_read_ldt();
1224 #ifdef CONFIG_X86_64
1225 savesegment(ds, host_state->ds_sel);
1226 savesegment(es, host_state->es_sel);
1228 gs_base = cpu_kernelmode_gs_base(cpu);
1229 if (likely(is_64bit_mm(current->mm))) {
1230 save_fsgs_for_kvm();
1231 fs_sel = current->thread.fsindex;
1232 gs_sel = current->thread.gsindex;
1233 fs_base = current->thread.fsbase;
1234 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1236 savesegment(fs, fs_sel);
1237 savesegment(gs, gs_sel);
1238 fs_base = read_msr(MSR_FS_BASE);
1239 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1242 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1244 savesegment(fs, fs_sel);
1245 savesegment(gs, gs_sel);
1246 fs_base = segment_base(fs_sel);
1247 gs_base = segment_base(gs_sel);
1250 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1251 vmx->guest_state_loaded = true;
1254 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1256 struct vmcs_host_state *host_state;
1258 if (!vmx->guest_state_loaded)
1261 host_state = &vmx->loaded_vmcs->host_state;
1263 ++vmx->vcpu.stat.host_state_reload;
1265 #ifdef CONFIG_X86_64
1266 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1268 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1269 kvm_load_ldt(host_state->ldt_sel);
1270 #ifdef CONFIG_X86_64
1271 load_gs_index(host_state->gs_sel);
1273 loadsegment(gs, host_state->gs_sel);
1276 if (host_state->fs_sel & 7)
1277 loadsegment(fs, host_state->fs_sel);
1278 #ifdef CONFIG_X86_64
1279 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1280 loadsegment(ds, host_state->ds_sel);
1281 loadsegment(es, host_state->es_sel);
1284 invalidate_tss_limit();
1285 #ifdef CONFIG_X86_64
1286 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1288 load_fixmap_gdt(raw_smp_processor_id());
1289 vmx->guest_state_loaded = false;
1290 vmx->guest_msrs_ready = false;
1293 #ifdef CONFIG_X86_64
1294 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1297 if (vmx->guest_state_loaded)
1298 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1300 return vmx->msr_guest_kernel_gs_base;
1303 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1306 if (vmx->guest_state_loaded)
1307 wrmsrl(MSR_KERNEL_GS_BASE, data);
1309 vmx->msr_guest_kernel_gs_base = data;
1313 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1315 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1316 struct pi_desc old, new;
1320 * In case of hot-plug or hot-unplug, we may have to undo
1321 * vmx_vcpu_pi_put even if there is no assigned device. And we
1322 * always keep PI.NDST up to date for simplicity: it makes the
1323 * code easier, and CPU migration is not a fast path.
1325 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1329 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
1330 * PI.NDST: pi_post_block is the one expected to change PID.NDST and the
1331 * wakeup handler expects the vCPU to be on the blocked_vcpu_list that
1332 * matches PI.NDST. Otherwise, a vcpu may not be able to be woken up
1335 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR || vcpu->cpu == cpu) {
1336 pi_clear_sn(pi_desc);
1337 goto after_clear_sn;
1340 /* The full case. */
1342 old.control = new.control = pi_desc->control;
1344 dest = cpu_physical_id(cpu);
1346 if (x2apic_enabled())
1349 new.ndst = (dest << 8) & 0xFF00;
1352 } while (cmpxchg64(&pi_desc->control, old.control,
1353 new.control) != old.control);
1358 * Clear SN before reading the bitmap. The VT-d firmware
1359 * writes the bitmap and reads SN atomically (5.2.3 in the
1360 * spec), so it doesn't really have a memory barrier that
1361 * pairs with this, but we cannot do that and we need one.
1363 smp_mb__after_atomic();
1365 if (!pi_is_pir_empty(pi_desc))
1369 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1370 struct loaded_vmcs *buddy)
1372 struct vcpu_vmx *vmx = to_vmx(vcpu);
1373 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1376 if (!already_loaded) {
1377 loaded_vmcs_clear(vmx->loaded_vmcs);
1378 local_irq_disable();
1381 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1382 * this cpu's percpu list, otherwise it may not yet be deleted
1383 * from its previous cpu's percpu list. Pairs with the
1384 * smb_wmb() in __loaded_vmcs_clear().
1388 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1389 &per_cpu(loaded_vmcss_on_cpu, cpu));
1393 prev = per_cpu(current_vmcs, cpu);
1394 if (prev != vmx->loaded_vmcs->vmcs) {
1395 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1396 vmcs_load(vmx->loaded_vmcs->vmcs);
1399 * No indirect branch prediction barrier needed when switching
1400 * the active VMCS within a vCPU, unless IBRS is advertised to
1401 * the vCPU. To minimize the number of IBPBs executed, KVM
1402 * performs IBPB on nested VM-Exit (a single nested transition
1403 * may switch the active VMCS multiple times).
1405 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1406 indirect_branch_prediction_barrier();
1409 if (!already_loaded) {
1410 void *gdt = get_current_gdt_ro();
1411 unsigned long sysenter_esp;
1413 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1416 * Linux uses per-cpu TSS and GDT, so set these when switching
1417 * processors. See 22.2.4.
1419 vmcs_writel(HOST_TR_BASE,
1420 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1421 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1424 * VM exits change the host TR limit to 0x67 after a VM
1425 * exit. This is okay, since 0x67 covers everything except
1426 * the IO bitmap and have have code to handle the IO bitmap
1427 * being lost after a VM exit.
1429 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
1431 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1432 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1434 vmx->loaded_vmcs->cpu = cpu;
1437 /* Setup TSC multiplier */
1438 if (kvm_has_tsc_control &&
1439 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1440 decache_tsc_multiplier(vmx);
1444 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1445 * vcpu mutex is already taken.
1447 void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1449 struct vcpu_vmx *vmx = to_vmx(vcpu);
1451 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1453 vmx_vcpu_pi_load(vcpu, cpu);
1455 vmx->host_debugctlmsr = get_debugctlmsr();
1458 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1460 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1462 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1463 !irq_remapping_cap(IRQ_POSTING_CAP) ||
1464 !kvm_vcpu_apicv_active(vcpu))
1467 /* Set SN when the vCPU is preempted */
1468 if (vcpu->preempted)
1472 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1474 vmx_vcpu_pi_put(vcpu);
1476 vmx_prepare_switch_to_host(to_vmx(vcpu));
1479 static bool emulation_required(struct kvm_vcpu *vcpu)
1481 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1484 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1486 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1488 unsigned long rflags, save_rflags;
1490 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1491 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1492 rflags = vmcs_readl(GUEST_RFLAGS);
1493 if (to_vmx(vcpu)->rmode.vm86_active) {
1494 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1495 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1496 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1498 to_vmx(vcpu)->rflags = rflags;
1500 return to_vmx(vcpu)->rflags;
1503 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1505 unsigned long old_rflags = vmx_get_rflags(vcpu);
1507 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1508 to_vmx(vcpu)->rflags = rflags;
1509 if (to_vmx(vcpu)->rmode.vm86_active) {
1510 to_vmx(vcpu)->rmode.save_rflags = rflags;
1511 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1513 vmcs_writel(GUEST_RFLAGS, rflags);
1515 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
1516 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
1519 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1521 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1524 if (interruptibility & GUEST_INTR_STATE_STI)
1525 ret |= KVM_X86_SHADOW_INT_STI;
1526 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1527 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1532 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1534 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1535 u32 interruptibility = interruptibility_old;
1537 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1539 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1540 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1541 else if (mask & KVM_X86_SHADOW_INT_STI)
1542 interruptibility |= GUEST_INTR_STATE_STI;
1544 if ((interruptibility != interruptibility_old))
1545 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1548 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1550 struct vcpu_vmx *vmx = to_vmx(vcpu);
1551 unsigned long value;
1554 * Any MSR write that attempts to change bits marked reserved will
1557 if (data & vmx->pt_desc.ctl_bitmask)
1561 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1562 * result in a #GP unless the same write also clears TraceEn.
1564 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1565 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1569 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1570 * and FabricEn would cause #GP, if
1571 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1573 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1574 !(data & RTIT_CTL_FABRIC_EN) &&
1575 !intel_pt_validate_cap(vmx->pt_desc.caps,
1576 PT_CAP_single_range_output))
1580 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1581 * utilize encodings marked reserved will casue a #GP fault.
1583 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1584 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1585 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1586 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1588 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1589 PT_CAP_cycle_thresholds);
1590 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1591 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1592 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1594 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1595 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1596 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1597 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1601 * If ADDRx_CFG is reserved or the encodings is >2 will
1602 * cause a #GP fault.
1604 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1605 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1607 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1608 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1610 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1611 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1613 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1614 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1620 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1622 unsigned long rip, orig_rip;
1625 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1626 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1627 * set when EPT misconfig occurs. In practice, real hardware updates
1628 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1629 * (namely Hyper-V) don't set it due to it being undefined behavior,
1630 * i.e. we end up advancing IP with some random value.
1632 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1633 to_vmx(vcpu)->exit_reason != EXIT_REASON_EPT_MISCONFIG) {
1634 orig_rip = kvm_rip_read(vcpu);
1635 rip = orig_rip + vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1636 #ifdef CONFIG_X86_64
1638 * We need to mask out the high 32 bits of RIP if not in 64-bit
1639 * mode, but just finding out that we are in 64-bit mode is
1640 * quite expensive. Only do it if there was a carry.
1642 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1645 kvm_rip_write(vcpu, rip);
1647 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1651 /* skipping an emulated instruction also counts */
1652 vmx_set_interrupt_shadow(vcpu, 0);
1657 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1660 * Ensure that we clear the HLT state in the VMCS. We don't need to
1661 * explicitly skip the instruction because if the HLT state is set,
1662 * then the instruction is already executing and RIP has already been
1665 if (kvm_hlt_in_guest(vcpu->kvm) &&
1666 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1667 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1670 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1672 struct vcpu_vmx *vmx = to_vmx(vcpu);
1673 unsigned nr = vcpu->arch.exception.nr;
1674 bool has_error_code = vcpu->arch.exception.has_error_code;
1675 u32 error_code = vcpu->arch.exception.error_code;
1676 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1678 kvm_deliver_exception_payload(vcpu);
1680 if (has_error_code) {
1682 * Despite the error code being architecturally defined as 32
1683 * bits, and the VMCS field being 32 bits, Intel CPUs and thus
1684 * VMX don't actually supporting setting bits 31:16. Hardware
1685 * will (should) never provide a bogus error code, but AMD CPUs
1686 * do generate error codes with bits 31:16 set, and so KVM's
1687 * ABI lets userspace shove in arbitrary 32-bit values. Drop
1688 * the upper bits to avoid VM-Fail, losing information that
1689 * does't really exist is preferable to killing the VM.
1691 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)error_code);
1692 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1695 if (vmx->rmode.vm86_active) {
1697 if (kvm_exception_is_soft(nr))
1698 inc_eip = vcpu->arch.event_exit_inst_len;
1699 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1703 WARN_ON_ONCE(vmx->emulation_required);
1705 if (kvm_exception_is_soft(nr)) {
1706 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1707 vmx->vcpu.arch.event_exit_inst_len);
1708 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1710 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1712 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1714 vmx_clear_hlt(vcpu);
1717 static bool vmx_rdtscp_supported(void)
1719 return cpu_has_vmx_rdtscp();
1722 static bool vmx_invpcid_supported(void)
1724 return cpu_has_vmx_invpcid();
1728 * Swap MSR entry in host/guest MSR entry array.
1730 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1732 struct shared_msr_entry tmp;
1734 tmp = vmx->guest_msrs[to];
1735 vmx->guest_msrs[to] = vmx->guest_msrs[from];
1736 vmx->guest_msrs[from] = tmp;
1740 * Set up the vmcs to automatically save and restore system
1741 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1742 * mode, as fiddling with msrs is very expensive.
1744 static void setup_msrs(struct vcpu_vmx *vmx)
1746 int save_nmsrs, index;
1749 #ifdef CONFIG_X86_64
1751 * The SYSCALL MSRs are only needed on long mode guests, and only
1752 * when EFER.SCE is set.
1754 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1755 index = __find_msr_index(vmx, MSR_STAR);
1757 move_msr_up(vmx, index, save_nmsrs++);
1758 index = __find_msr_index(vmx, MSR_LSTAR);
1760 move_msr_up(vmx, index, save_nmsrs++);
1761 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1763 move_msr_up(vmx, index, save_nmsrs++);
1766 index = __find_msr_index(vmx, MSR_EFER);
1767 if (index >= 0 && update_transition_efer(vmx, index))
1768 move_msr_up(vmx, index, save_nmsrs++);
1769 index = __find_msr_index(vmx, MSR_TSC_AUX);
1770 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1771 move_msr_up(vmx, index, save_nmsrs++);
1773 vmx->save_nmsrs = save_nmsrs;
1774 vmx->guest_msrs_ready = false;
1776 if (cpu_has_vmx_msr_bitmap())
1777 vmx_update_msr_bitmap(&vmx->vcpu);
1780 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1782 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1784 if (is_guest_mode(vcpu) &&
1785 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
1786 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
1788 return vcpu->arch.tsc_offset;
1791 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1793 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1794 u64 g_tsc_offset = 0;
1797 * We're here if L1 chose not to trap WRMSR to TSC. According
1798 * to the spec, this should set L1's TSC; The offset that L1
1799 * set for L2 remains unchanged, and still needs to be added
1800 * to the newly set TSC to get L2's TSC.
1802 if (is_guest_mode(vcpu) &&
1803 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
1804 g_tsc_offset = vmcs12->tsc_offset;
1806 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1807 vcpu->arch.tsc_offset - g_tsc_offset,
1809 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1810 return offset + g_tsc_offset;
1814 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1815 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1816 * all guests if the "nested" module option is off, and can also be disabled
1817 * for a single guest by disabling its VMX cpuid bit.
1819 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1821 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1824 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1827 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1829 return !(val & ~valid_bits);
1832 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1834 switch (msr->index) {
1835 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1838 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1847 * Reads an msr value (of 'msr_index') into 'pdata'.
1848 * Returns 0 on success, non-0 otherwise.
1849 * Assumes vcpu_load() was already called.
1851 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1853 struct vcpu_vmx *vmx = to_vmx(vcpu);
1854 struct shared_msr_entry *msr;
1857 switch (msr_info->index) {
1858 #ifdef CONFIG_X86_64
1860 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1863 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1865 case MSR_KERNEL_GS_BASE:
1866 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1870 return kvm_get_msr_common(vcpu, msr_info);
1871 case MSR_IA32_UMWAIT_CONTROL:
1872 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1875 msr_info->data = vmx->msr_ia32_umwait_control;
1877 case MSR_IA32_SPEC_CTRL:
1878 if (!msr_info->host_initiated &&
1879 !guest_has_spec_ctrl_msr(vcpu))
1882 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1884 case MSR_IA32_SYSENTER_CS:
1885 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1887 case MSR_IA32_SYSENTER_EIP:
1888 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1890 case MSR_IA32_SYSENTER_ESP:
1891 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1893 case MSR_IA32_BNDCFGS:
1894 if (!kvm_mpx_supported() ||
1895 (!msr_info->host_initiated &&
1896 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1898 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1900 case MSR_IA32_MCG_EXT_CTL:
1901 if (!msr_info->host_initiated &&
1902 !(vmx->msr_ia32_feature_control &
1903 FEATURE_CONTROL_LMCE))
1905 msr_info->data = vcpu->arch.mcg_ext_ctl;
1907 case MSR_IA32_FEATURE_CONTROL:
1908 msr_info->data = vmx->msr_ia32_feature_control;
1910 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1911 if (!nested_vmx_allowed(vcpu))
1913 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1916 if (!vmx_xsaves_supported() ||
1917 (!msr_info->host_initiated &&
1918 !(guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
1919 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))))
1921 msr_info->data = vcpu->arch.ia32_xss;
1923 case MSR_IA32_RTIT_CTL:
1924 if (pt_mode != PT_MODE_HOST_GUEST)
1926 msr_info->data = vmx->pt_desc.guest.ctl;
1928 case MSR_IA32_RTIT_STATUS:
1929 if (pt_mode != PT_MODE_HOST_GUEST)
1931 msr_info->data = vmx->pt_desc.guest.status;
1933 case MSR_IA32_RTIT_CR3_MATCH:
1934 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1935 !intel_pt_validate_cap(vmx->pt_desc.caps,
1936 PT_CAP_cr3_filtering))
1938 msr_info->data = vmx->pt_desc.guest.cr3_match;
1940 case MSR_IA32_RTIT_OUTPUT_BASE:
1941 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1942 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1943 PT_CAP_topa_output) &&
1944 !intel_pt_validate_cap(vmx->pt_desc.caps,
1945 PT_CAP_single_range_output)))
1947 msr_info->data = vmx->pt_desc.guest.output_base;
1949 case MSR_IA32_RTIT_OUTPUT_MASK:
1950 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1951 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1952 PT_CAP_topa_output) &&
1953 !intel_pt_validate_cap(vmx->pt_desc.caps,
1954 PT_CAP_single_range_output)))
1956 msr_info->data = vmx->pt_desc.guest.output_mask;
1958 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1959 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1960 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1961 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1962 PT_CAP_num_address_ranges)))
1965 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1967 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1970 if (!msr_info->host_initiated &&
1971 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1973 /* Else, falls through */
1975 msr = find_msr_entry(vmx, msr_info->index);
1977 msr_info->data = msr->data;
1980 return kvm_get_msr_common(vcpu, msr_info);
1987 * Writes msr value into into the appropriate "register".
1988 * Returns 0 on success, non-0 otherwise.
1989 * Assumes vcpu_load() was already called.
1991 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1993 struct vcpu_vmx *vmx = to_vmx(vcpu);
1994 struct shared_msr_entry *msr;
1996 u32 msr_index = msr_info->index;
1997 u64 data = msr_info->data;
2000 switch (msr_index) {
2002 ret = kvm_set_msr_common(vcpu, msr_info);
2004 #ifdef CONFIG_X86_64
2006 vmx_segment_cache_clear(vmx);
2007 vmcs_writel(GUEST_FS_BASE, data);
2010 vmx_segment_cache_clear(vmx);
2011 vmcs_writel(GUEST_GS_BASE, data);
2013 case MSR_KERNEL_GS_BASE:
2014 vmx_write_guest_kernel_gs_base(vmx, data);
2017 case MSR_IA32_SYSENTER_CS:
2018 if (is_guest_mode(vcpu))
2019 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2020 vmcs_write32(GUEST_SYSENTER_CS, data);
2022 case MSR_IA32_SYSENTER_EIP:
2023 if (is_guest_mode(vcpu))
2024 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2025 vmcs_writel(GUEST_SYSENTER_EIP, data);
2027 case MSR_IA32_SYSENTER_ESP:
2028 if (is_guest_mode(vcpu))
2029 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2030 vmcs_writel(GUEST_SYSENTER_ESP, data);
2032 case MSR_IA32_DEBUGCTLMSR:
2033 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2034 VM_EXIT_SAVE_DEBUG_CONTROLS)
2035 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2037 ret = kvm_set_msr_common(vcpu, msr_info);
2040 case MSR_IA32_BNDCFGS:
2041 if (!kvm_mpx_supported() ||
2042 (!msr_info->host_initiated &&
2043 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2045 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2046 (data & MSR_IA32_BNDCFGS_RSVD))
2048 vmcs_write64(GUEST_BNDCFGS, data);
2050 case MSR_IA32_UMWAIT_CONTROL:
2051 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2054 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2055 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2058 vmx->msr_ia32_umwait_control = data;
2060 case MSR_IA32_SPEC_CTRL:
2061 if (!msr_info->host_initiated &&
2062 !guest_has_spec_ctrl_msr(vcpu))
2065 if (kvm_spec_ctrl_test_value(data))
2068 vmx->spec_ctrl = data;
2074 * When it's written (to non-zero) for the first time, pass
2078 * The handling of the MSR bitmap for L2 guests is done in
2079 * nested_vmx_merge_msr_bitmap. We should not touch the
2080 * vmcs02.msr_bitmap here since it gets completely overwritten
2081 * in the merging. We update the vmcs01 here for L1 as well
2082 * since it will end up touching the MSR anyway now.
2084 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
2088 case MSR_IA32_PRED_CMD:
2089 if (!msr_info->host_initiated &&
2090 !guest_has_pred_cmd_msr(vcpu))
2093 if (data & ~PRED_CMD_IBPB)
2095 if (!boot_cpu_has(X86_FEATURE_IBPB))
2100 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2104 * When it's written (to non-zero) for the first time, pass
2108 * The handling of the MSR bitmap for L2 guests is done in
2109 * nested_vmx_merge_msr_bitmap. We should not touch the
2110 * vmcs02.msr_bitmap here since it gets completely overwritten
2113 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
2116 case MSR_IA32_CR_PAT:
2117 if (!kvm_pat_valid(data))
2120 if (is_guest_mode(vcpu) &&
2121 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2122 get_vmcs12(vcpu)->guest_ia32_pat = data;
2124 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2125 vmcs_write64(GUEST_IA32_PAT, data);
2126 vcpu->arch.pat = data;
2129 ret = kvm_set_msr_common(vcpu, msr_info);
2131 case MSR_IA32_TSC_ADJUST:
2132 ret = kvm_set_msr_common(vcpu, msr_info);
2134 case MSR_IA32_MCG_EXT_CTL:
2135 if ((!msr_info->host_initiated &&
2136 !(to_vmx(vcpu)->msr_ia32_feature_control &
2137 FEATURE_CONTROL_LMCE)) ||
2138 (data & ~MCG_EXT_CTL_LMCE_EN))
2140 vcpu->arch.mcg_ext_ctl = data;
2142 case MSR_IA32_FEATURE_CONTROL:
2143 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2144 (to_vmx(vcpu)->msr_ia32_feature_control &
2145 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
2147 vmx->msr_ia32_feature_control = data;
2148 if (msr_info->host_initiated && data == 0)
2149 vmx_leave_nested(vcpu);
2151 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2152 if (!msr_info->host_initiated)
2153 return 1; /* they are read-only */
2154 if (!nested_vmx_allowed(vcpu))
2156 return vmx_set_vmx_msr(vcpu, msr_index, data);
2158 if (!vmx_xsaves_supported() ||
2159 (!msr_info->host_initiated &&
2160 !(guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
2161 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))))
2164 * The only supported bit as of Skylake is bit 8, but
2165 * it is not supported on KVM.
2169 vcpu->arch.ia32_xss = data;
2170 if (vcpu->arch.ia32_xss != host_xss)
2171 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
2172 vcpu->arch.ia32_xss, host_xss, false);
2174 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
2176 case MSR_IA32_RTIT_CTL:
2177 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2178 vmx_rtit_ctl_check(vcpu, data) ||
2181 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2182 vmx->pt_desc.guest.ctl = data;
2183 pt_update_intercept_for_msr(vmx);
2185 case MSR_IA32_RTIT_STATUS:
2186 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2187 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2188 (data & MSR_IA32_RTIT_STATUS_MASK))
2190 vmx->pt_desc.guest.status = data;
2192 case MSR_IA32_RTIT_CR3_MATCH:
2193 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2194 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2195 !intel_pt_validate_cap(vmx->pt_desc.caps,
2196 PT_CAP_cr3_filtering))
2198 vmx->pt_desc.guest.cr3_match = data;
2200 case MSR_IA32_RTIT_OUTPUT_BASE:
2201 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2202 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2203 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2204 PT_CAP_topa_output) &&
2205 !intel_pt_validate_cap(vmx->pt_desc.caps,
2206 PT_CAP_single_range_output)) ||
2207 (data & MSR_IA32_RTIT_OUTPUT_BASE_MASK))
2209 vmx->pt_desc.guest.output_base = data;
2211 case MSR_IA32_RTIT_OUTPUT_MASK:
2212 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2213 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2214 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2215 PT_CAP_topa_output) &&
2216 !intel_pt_validate_cap(vmx->pt_desc.caps,
2217 PT_CAP_single_range_output)))
2219 vmx->pt_desc.guest.output_mask = data;
2221 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2222 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2223 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2224 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2225 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2226 PT_CAP_num_address_ranges)))
2228 if (is_noncanonical_address(data, vcpu))
2231 vmx->pt_desc.guest.addr_b[index / 2] = data;
2233 vmx->pt_desc.guest.addr_a[index / 2] = data;
2236 if (!msr_info->host_initiated &&
2237 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2239 /* Check reserved bit, higher 32 bits should be zero */
2240 if ((data >> 32) != 0)
2242 /* Else, falls through */
2244 msr = find_msr_entry(vmx, msr_index);
2246 u64 old_msr_data = msr->data;
2248 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2250 ret = kvm_set_shared_msr(msr->index, msr->data,
2254 msr->data = old_msr_data;
2258 ret = kvm_set_msr_common(vcpu, msr_info);
2261 /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */
2262 if (msr_index == MSR_IA32_ARCH_CAPABILITIES)
2263 vmx_update_fb_clear_dis(vcpu, vmx);
2268 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2270 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2273 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2276 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2278 case VCPU_EXREG_PDPTR:
2280 ept_save_pdptrs(vcpu);
2287 static __init int cpu_has_kvm_support(void)
2289 return cpu_has_vmx();
2292 static __init int vmx_disabled_by_bios(void)
2296 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2297 if (msr & FEATURE_CONTROL_LOCKED) {
2298 /* launched w/ TXT and VMX disabled */
2299 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2302 /* launched w/o TXT and VMX only enabled w/ TXT */
2303 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2304 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2305 && !tboot_enabled()) {
2306 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2307 "activate TXT before enabling KVM\n");
2310 /* launched w/o TXT and VMX disabled */
2311 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2312 && !tboot_enabled())
2319 static void kvm_cpu_vmxon(u64 addr)
2321 cr4_set_bits(X86_CR4_VMXE);
2322 intel_pt_handle_vmx(1);
2324 asm volatile ("vmxon %0" : : "m"(addr));
2327 static int hardware_enable(void)
2329 int cpu = raw_smp_processor_id();
2330 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2333 if (cr4_read_shadow() & X86_CR4_VMXE)
2337 * This can happen if we hot-added a CPU but failed to allocate
2338 * VP assist page for it.
2340 if (static_branch_unlikely(&enable_evmcs) &&
2341 !hv_get_vp_assist_page(cpu))
2344 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2346 test_bits = FEATURE_CONTROL_LOCKED;
2347 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2348 if (tboot_enabled())
2349 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2351 if ((old & test_bits) != test_bits) {
2352 /* enable and lock */
2353 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2355 kvm_cpu_vmxon(phys_addr);
2362 static void vmclear_local_loaded_vmcss(void)
2364 int cpu = raw_smp_processor_id();
2365 struct loaded_vmcs *v, *n;
2367 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2368 loaded_vmcss_on_cpu_link)
2369 __loaded_vmcs_clear(v);
2373 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2376 static void kvm_cpu_vmxoff(void)
2378 asm volatile (__ex("vmxoff"));
2380 intel_pt_handle_vmx(0);
2381 cr4_clear_bits(X86_CR4_VMXE);
2384 static void hardware_disable(void)
2386 vmclear_local_loaded_vmcss();
2390 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2391 u32 msr, u32 *result)
2393 u32 vmx_msr_low, vmx_msr_high;
2394 u32 ctl = ctl_min | ctl_opt;
2396 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2398 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2399 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2401 /* Ensure minimum (required) set of control bits are supported. */
2409 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2410 struct vmx_capability *vmx_cap)
2412 u32 vmx_msr_low, vmx_msr_high;
2413 u32 min, opt, min2, opt2;
2414 u32 _pin_based_exec_control = 0;
2415 u32 _cpu_based_exec_control = 0;
2416 u32 _cpu_based_2nd_exec_control = 0;
2417 u32 _vmexit_control = 0;
2418 u32 _vmentry_control = 0;
2420 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2421 min = CPU_BASED_HLT_EXITING |
2422 #ifdef CONFIG_X86_64
2423 CPU_BASED_CR8_LOAD_EXITING |
2424 CPU_BASED_CR8_STORE_EXITING |
2426 CPU_BASED_CR3_LOAD_EXITING |
2427 CPU_BASED_CR3_STORE_EXITING |
2428 CPU_BASED_UNCOND_IO_EXITING |
2429 CPU_BASED_MOV_DR_EXITING |
2430 CPU_BASED_USE_TSC_OFFSETTING |
2431 CPU_BASED_MWAIT_EXITING |
2432 CPU_BASED_MONITOR_EXITING |
2433 CPU_BASED_INVLPG_EXITING |
2434 CPU_BASED_RDPMC_EXITING;
2436 opt = CPU_BASED_TPR_SHADOW |
2437 CPU_BASED_USE_MSR_BITMAPS |
2438 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2439 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2440 &_cpu_based_exec_control) < 0)
2442 #ifdef CONFIG_X86_64
2443 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2444 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2445 ~CPU_BASED_CR8_STORE_EXITING;
2447 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2449 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2450 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2451 SECONDARY_EXEC_WBINVD_EXITING |
2452 SECONDARY_EXEC_ENABLE_VPID |
2453 SECONDARY_EXEC_ENABLE_EPT |
2454 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2455 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2456 SECONDARY_EXEC_DESC |
2457 SECONDARY_EXEC_RDTSCP |
2458 SECONDARY_EXEC_ENABLE_INVPCID |
2459 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2460 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2461 SECONDARY_EXEC_SHADOW_VMCS |
2462 SECONDARY_EXEC_XSAVES |
2463 SECONDARY_EXEC_RDSEED_EXITING |
2464 SECONDARY_EXEC_RDRAND_EXITING |
2465 SECONDARY_EXEC_ENABLE_PML |
2466 SECONDARY_EXEC_TSC_SCALING |
2467 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2468 SECONDARY_EXEC_PT_USE_GPA |
2469 SECONDARY_EXEC_PT_CONCEAL_VMX |
2470 SECONDARY_EXEC_ENABLE_VMFUNC |
2471 SECONDARY_EXEC_ENCLS_EXITING;
2472 if (adjust_vmx_controls(min2, opt2,
2473 MSR_IA32_VMX_PROCBASED_CTLS2,
2474 &_cpu_based_2nd_exec_control) < 0)
2477 #ifndef CONFIG_X86_64
2478 if (!(_cpu_based_2nd_exec_control &
2479 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2480 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2483 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2484 _cpu_based_2nd_exec_control &= ~(
2485 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2486 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2487 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2489 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2490 &vmx_cap->ept, &vmx_cap->vpid);
2492 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2493 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2495 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2496 CPU_BASED_CR3_STORE_EXITING |
2497 CPU_BASED_INVLPG_EXITING);
2498 } else if (vmx_cap->ept) {
2500 pr_warn_once("EPT CAP should not exist if not support "
2501 "1-setting enable EPT VM-execution control\n");
2503 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2506 pr_warn_once("VPID CAP should not exist if not support "
2507 "1-setting enable VPID VM-execution control\n");
2510 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2511 #ifdef CONFIG_X86_64
2512 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2514 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2515 VM_EXIT_LOAD_IA32_PAT |
2516 VM_EXIT_LOAD_IA32_EFER |
2517 VM_EXIT_CLEAR_BNDCFGS |
2518 VM_EXIT_PT_CONCEAL_PIP |
2519 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2520 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2521 &_vmexit_control) < 0)
2524 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2525 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2526 PIN_BASED_VMX_PREEMPTION_TIMER;
2527 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2528 &_pin_based_exec_control) < 0)
2531 if (cpu_has_broken_vmx_preemption_timer())
2532 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2533 if (!(_cpu_based_2nd_exec_control &
2534 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2535 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2537 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2538 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2539 VM_ENTRY_LOAD_IA32_PAT |
2540 VM_ENTRY_LOAD_IA32_EFER |
2541 VM_ENTRY_LOAD_BNDCFGS |
2542 VM_ENTRY_PT_CONCEAL_PIP |
2543 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2544 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2545 &_vmentry_control) < 0)
2549 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2550 * can't be used due to an errata where VM Exit may incorrectly clear
2551 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2552 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2554 if (boot_cpu_data.x86 == 0x6) {
2555 switch (boot_cpu_data.x86_model) {
2556 case 26: /* AAK155 */
2557 case 30: /* AAP115 */
2558 case 37: /* AAT100 */
2559 case 44: /* BC86,AAY89,BD102 */
2561 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2562 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2563 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2564 "does not work properly. Using workaround\n");
2572 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2574 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2575 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2578 #ifdef CONFIG_X86_64
2579 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2580 if (vmx_msr_high & (1u<<16))
2584 /* Require Write-Back (WB) memory type for VMCS accesses. */
2585 if (((vmx_msr_high >> 18) & 15) != 6)
2588 vmcs_conf->size = vmx_msr_high & 0x1fff;
2589 vmcs_conf->order = get_order(vmcs_conf->size);
2590 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2592 vmcs_conf->revision_id = vmx_msr_low;
2594 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2595 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2596 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2597 vmcs_conf->vmexit_ctrl = _vmexit_control;
2598 vmcs_conf->vmentry_ctrl = _vmentry_control;
2600 if (static_branch_unlikely(&enable_evmcs))
2601 evmcs_sanitize_exec_ctrls(vmcs_conf);
2606 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2608 int node = cpu_to_node(cpu);
2612 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2615 vmcs = page_address(pages);
2616 memset(vmcs, 0, vmcs_config.size);
2618 /* KVM supports Enlightened VMCS v1 only */
2619 if (static_branch_unlikely(&enable_evmcs))
2620 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2622 vmcs->hdr.revision_id = vmcs_config.revision_id;
2625 vmcs->hdr.shadow_vmcs = 1;
2629 void free_vmcs(struct vmcs *vmcs)
2631 free_pages((unsigned long)vmcs, vmcs_config.order);
2635 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2637 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2639 if (!loaded_vmcs->vmcs)
2641 loaded_vmcs_clear(loaded_vmcs);
2642 free_vmcs(loaded_vmcs->vmcs);
2643 loaded_vmcs->vmcs = NULL;
2644 if (loaded_vmcs->msr_bitmap)
2645 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2646 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2649 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2651 loaded_vmcs->vmcs = alloc_vmcs(false);
2652 if (!loaded_vmcs->vmcs)
2655 loaded_vmcs->shadow_vmcs = NULL;
2656 loaded_vmcs->hv_timer_soft_disabled = false;
2657 loaded_vmcs_init(loaded_vmcs);
2659 if (cpu_has_vmx_msr_bitmap()) {
2660 loaded_vmcs->msr_bitmap = (unsigned long *)
2661 __get_free_page(GFP_KERNEL_ACCOUNT);
2662 if (!loaded_vmcs->msr_bitmap)
2664 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2666 if (IS_ENABLED(CONFIG_HYPERV) &&
2667 static_branch_unlikely(&enable_evmcs) &&
2668 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2669 struct hv_enlightened_vmcs *evmcs =
2670 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2672 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2676 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2677 memset(&loaded_vmcs->controls_shadow, 0,
2678 sizeof(struct vmcs_controls_shadow));
2683 free_loaded_vmcs(loaded_vmcs);
2687 static void free_kvm_area(void)
2691 for_each_possible_cpu(cpu) {
2692 free_vmcs(per_cpu(vmxarea, cpu));
2693 per_cpu(vmxarea, cpu) = NULL;
2697 static __init int alloc_kvm_area(void)
2701 for_each_possible_cpu(cpu) {
2704 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2711 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2712 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2713 * revision_id reported by MSR_IA32_VMX_BASIC.
2715 * However, even though not explicitly documented by
2716 * TLFS, VMXArea passed as VMXON argument should
2717 * still be marked with revision_id reported by
2720 if (static_branch_unlikely(&enable_evmcs))
2721 vmcs->hdr.revision_id = vmcs_config.revision_id;
2723 per_cpu(vmxarea, cpu) = vmcs;
2728 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2729 struct kvm_segment *save)
2731 if (!emulate_invalid_guest_state) {
2733 * CS and SS RPL should be equal during guest entry according
2734 * to VMX spec, but in reality it is not always so. Since vcpu
2735 * is in the middle of the transition from real mode to
2736 * protected mode it is safe to assume that RPL 0 is a good
2739 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2740 save->selector &= ~SEGMENT_RPL_MASK;
2741 save->dpl = save->selector & SEGMENT_RPL_MASK;
2744 vmx_set_segment(vcpu, save, seg);
2747 static void enter_pmode(struct kvm_vcpu *vcpu)
2749 unsigned long flags;
2750 struct vcpu_vmx *vmx = to_vmx(vcpu);
2753 * Update real mode segment cache. It may be not up-to-date if sement
2754 * register was written while vcpu was in a guest mode.
2756 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2757 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2758 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2759 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2760 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2761 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2763 vmx->rmode.vm86_active = 0;
2765 vmx_segment_cache_clear(vmx);
2767 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2769 flags = vmcs_readl(GUEST_RFLAGS);
2770 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2771 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2772 vmcs_writel(GUEST_RFLAGS, flags);
2774 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2775 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2777 update_exception_bitmap(vcpu);
2779 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2780 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2781 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2782 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2783 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2784 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2787 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2789 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2790 struct kvm_segment var = *save;
2793 if (seg == VCPU_SREG_CS)
2796 if (!emulate_invalid_guest_state) {
2797 var.selector = var.base >> 4;
2798 var.base = var.base & 0xffff0;
2808 if (save->base & 0xf)
2809 printk_once(KERN_WARNING "kvm: segment base is not "
2810 "paragraph aligned when entering "
2811 "protected mode (seg=%d)", seg);
2814 vmcs_write16(sf->selector, var.selector);
2815 vmcs_writel(sf->base, var.base);
2816 vmcs_write32(sf->limit, var.limit);
2817 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2820 static void enter_rmode(struct kvm_vcpu *vcpu)
2822 unsigned long flags;
2823 struct vcpu_vmx *vmx = to_vmx(vcpu);
2824 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2826 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2827 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2828 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2829 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2830 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2831 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2832 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2834 vmx->rmode.vm86_active = 1;
2837 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2838 * vcpu. Warn the user that an update is overdue.
2840 if (!kvm_vmx->tss_addr)
2841 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2842 "called before entering vcpu\n");
2844 vmx_segment_cache_clear(vmx);
2846 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2847 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2848 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2850 flags = vmcs_readl(GUEST_RFLAGS);
2851 vmx->rmode.save_rflags = flags;
2853 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2855 vmcs_writel(GUEST_RFLAGS, flags);
2856 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2857 update_exception_bitmap(vcpu);
2859 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2860 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2861 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2862 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2863 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2864 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2866 kvm_mmu_reset_context(vcpu);
2869 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2871 struct vcpu_vmx *vmx = to_vmx(vcpu);
2872 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2877 vcpu->arch.efer = efer;
2878 if (efer & EFER_LMA) {
2879 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2882 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2884 msr->data = efer & ~EFER_LME;
2889 #ifdef CONFIG_X86_64
2891 static void enter_lmode(struct kvm_vcpu *vcpu)
2895 vmx_segment_cache_clear(to_vmx(vcpu));
2897 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2898 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2899 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2901 vmcs_write32(GUEST_TR_AR_BYTES,
2902 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2903 | VMX_AR_TYPE_BUSY_64_TSS);
2905 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2908 static void exit_lmode(struct kvm_vcpu *vcpu)
2910 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2911 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2916 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2918 int vpid = to_vmx(vcpu)->vpid;
2920 if (!vpid_sync_vcpu_addr(vpid, addr))
2921 vpid_sync_context(vpid);
2924 * If VPIDs are not supported or enabled, then the above is a no-op.
2925 * But we don't really need a TLB flush in that case anyway, because
2926 * each VM entry/exit includes an implicit flush when VPID is 0.
2930 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2932 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2934 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
2935 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
2938 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2940 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
2941 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2942 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2945 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2947 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2949 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2950 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2953 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2955 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2957 if (!test_bit(VCPU_EXREG_PDPTR,
2958 (unsigned long *)&vcpu->arch.regs_dirty))
2961 if (is_pae_paging(vcpu)) {
2962 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2963 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2964 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2965 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2969 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2971 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2973 if (is_pae_paging(vcpu)) {
2974 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2975 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2976 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2977 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2980 __set_bit(VCPU_EXREG_PDPTR,
2981 (unsigned long *)&vcpu->arch.regs_avail);
2982 __set_bit(VCPU_EXREG_PDPTR,
2983 (unsigned long *)&vcpu->arch.regs_dirty);
2986 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2988 struct kvm_vcpu *vcpu)
2990 struct vcpu_vmx *vmx = to_vmx(vcpu);
2992 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2993 vmx_decache_cr3(vcpu);
2994 if (!(cr0 & X86_CR0_PG)) {
2995 /* From paging/starting to nonpaging */
2996 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
2997 CPU_BASED_CR3_STORE_EXITING);
2998 vcpu->arch.cr0 = cr0;
2999 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3000 } else if (!is_paging(vcpu)) {
3001 /* From nonpaging to paging */
3002 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3003 CPU_BASED_CR3_STORE_EXITING);
3004 vcpu->arch.cr0 = cr0;
3005 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3008 if (!(cr0 & X86_CR0_WP))
3009 *hw_cr0 &= ~X86_CR0_WP;
3012 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3014 struct vcpu_vmx *vmx = to_vmx(vcpu);
3015 unsigned long hw_cr0;
3017 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3018 if (enable_unrestricted_guest)
3019 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3021 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3023 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3026 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3030 #ifdef CONFIG_X86_64
3031 if (vcpu->arch.efer & EFER_LME) {
3032 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3034 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3039 if (enable_ept && !enable_unrestricted_guest)
3040 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3042 vmcs_writel(CR0_READ_SHADOW, cr0);
3043 vmcs_writel(GUEST_CR0, hw_cr0);
3044 vcpu->arch.cr0 = cr0;
3046 /* depends on vcpu->arch.cr0 to be set to a new value */
3047 vmx->emulation_required = emulation_required(vcpu);
3050 static int get_ept_level(struct kvm_vcpu *vcpu)
3052 /* Nested EPT currently only supports 4-level walks. */
3053 if (is_guest_mode(vcpu) && nested_cpu_has_ept(get_vmcs12(vcpu)))
3055 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
3060 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
3062 u64 eptp = VMX_EPTP_MT_WB;
3064 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3066 if (enable_ept_ad_bits &&
3067 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3068 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3069 eptp |= (root_hpa & PAGE_MASK);
3074 void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
3076 struct kvm *kvm = vcpu->kvm;
3077 bool update_guest_cr3 = true;
3078 unsigned long guest_cr3;
3083 eptp = construct_eptp(vcpu, cr3);
3084 vmcs_write64(EPT_POINTER, eptp);
3086 if (kvm_x86_ops->tlb_remote_flush) {
3087 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3088 to_vmx(vcpu)->ept_pointer = eptp;
3089 to_kvm_vmx(kvm)->ept_pointers_match
3090 = EPT_POINTERS_CHECK;
3091 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3094 /* Loading vmcs02.GUEST_CR3 is handled by nested VM-Enter. */
3095 if (is_guest_mode(vcpu))
3096 update_guest_cr3 = false;
3097 else if (enable_unrestricted_guest || is_paging(vcpu))
3098 guest_cr3 = kvm_read_cr3(vcpu);
3100 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3101 ept_load_pdptrs(vcpu);
3104 if (update_guest_cr3)
3105 vmcs_writel(GUEST_CR3, guest_cr3);
3108 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3110 struct vcpu_vmx *vmx = to_vmx(vcpu);
3112 * Pass through host's Machine Check Enable value to hw_cr4, which
3113 * is in force while we are in guest mode. Do not let guests control
3114 * this bit, even if host CR4.MCE == 0.
3116 unsigned long hw_cr4;
3118 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3119 if (enable_unrestricted_guest)
3120 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3121 else if (vmx->rmode.vm86_active)
3122 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3124 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3126 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3127 if (cr4 & X86_CR4_UMIP) {
3128 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3129 hw_cr4 &= ~X86_CR4_UMIP;
3130 } else if (!is_guest_mode(vcpu) ||
3131 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3132 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3136 if (cr4 & X86_CR4_VMXE) {
3138 * To use VMXON (and later other VMX instructions), a guest
3139 * must first be able to turn on cr4.VMXE (see handle_vmon()).
3140 * So basically the check on whether to allow nested VMX
3141 * is here. We operate under the default treatment of SMM,
3142 * so VMX cannot be enabled under SMM.
3144 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
3148 if (vmx->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3151 vcpu->arch.cr4 = cr4;
3153 if (!enable_unrestricted_guest) {
3155 if (!is_paging(vcpu)) {
3156 hw_cr4 &= ~X86_CR4_PAE;
3157 hw_cr4 |= X86_CR4_PSE;
3158 } else if (!(cr4 & X86_CR4_PAE)) {
3159 hw_cr4 &= ~X86_CR4_PAE;
3164 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3165 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3166 * to be manually disabled when guest switches to non-paging
3169 * If !enable_unrestricted_guest, the CPU is always running
3170 * with CR0.PG=1 and CR4 needs to be modified.
3171 * If enable_unrestricted_guest, the CPU automatically
3172 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3174 if (!is_paging(vcpu))
3175 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3178 vmcs_writel(CR4_READ_SHADOW, cr4);
3179 vmcs_writel(GUEST_CR4, hw_cr4);
3183 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3185 struct vcpu_vmx *vmx = to_vmx(vcpu);
3188 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3189 *var = vmx->rmode.segs[seg];
3190 if (seg == VCPU_SREG_TR
3191 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3193 var->base = vmx_read_guest_seg_base(vmx, seg);
3194 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3197 var->base = vmx_read_guest_seg_base(vmx, seg);
3198 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3199 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3200 ar = vmx_read_guest_seg_ar(vmx, seg);
3201 var->unusable = (ar >> 16) & 1;
3202 var->type = ar & 15;
3203 var->s = (ar >> 4) & 1;
3204 var->dpl = (ar >> 5) & 3;
3206 * Some userspaces do not preserve unusable property. Since usable
3207 * segment has to be present according to VMX spec we can use present
3208 * property to amend userspace bug by making unusable segment always
3209 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3210 * segment as unusable.
3212 var->present = !var->unusable;
3213 var->avl = (ar >> 12) & 1;
3214 var->l = (ar >> 13) & 1;
3215 var->db = (ar >> 14) & 1;
3216 var->g = (ar >> 15) & 1;
3219 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3221 struct kvm_segment s;
3223 if (to_vmx(vcpu)->rmode.vm86_active) {
3224 vmx_get_segment(vcpu, &s, seg);
3227 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3230 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3232 struct vcpu_vmx *vmx = to_vmx(vcpu);
3234 if (unlikely(vmx->rmode.vm86_active))
3237 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3238 return VMX_AR_DPL(ar);
3242 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3246 ar = var->type & 15;
3247 ar |= (var->s & 1) << 4;
3248 ar |= (var->dpl & 3) << 5;
3249 ar |= (var->present & 1) << 7;
3250 ar |= (var->avl & 1) << 12;
3251 ar |= (var->l & 1) << 13;
3252 ar |= (var->db & 1) << 14;
3253 ar |= (var->g & 1) << 15;
3254 ar |= (var->unusable || !var->present) << 16;
3259 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3261 struct vcpu_vmx *vmx = to_vmx(vcpu);
3262 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3264 vmx_segment_cache_clear(vmx);
3266 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3267 vmx->rmode.segs[seg] = *var;
3268 if (seg == VCPU_SREG_TR)
3269 vmcs_write16(sf->selector, var->selector);
3271 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3275 vmcs_writel(sf->base, var->base);
3276 vmcs_write32(sf->limit, var->limit);
3277 vmcs_write16(sf->selector, var->selector);
3280 * Fix the "Accessed" bit in AR field of segment registers for older
3282 * IA32 arch specifies that at the time of processor reset the
3283 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3284 * is setting it to 0 in the userland code. This causes invalid guest
3285 * state vmexit when "unrestricted guest" mode is turned on.
3286 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3287 * tree. Newer qemu binaries with that qemu fix would not need this
3290 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3291 var->type |= 0x1; /* Accessed */
3293 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3296 vmx->emulation_required = emulation_required(vcpu);
3299 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3301 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3303 *db = (ar >> 14) & 1;
3304 *l = (ar >> 13) & 1;
3307 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3309 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3310 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3313 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3315 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3316 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3319 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3321 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3322 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3325 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3327 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3328 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3331 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3333 struct kvm_segment var;
3336 vmx_get_segment(vcpu, &var, seg);
3338 if (seg == VCPU_SREG_CS)
3340 ar = vmx_segment_access_rights(&var);
3342 if (var.base != (var.selector << 4))
3344 if (var.limit != 0xffff)
3352 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3354 struct kvm_segment cs;
3355 unsigned int cs_rpl;
3357 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3358 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3362 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3366 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3367 if (cs.dpl > cs_rpl)
3370 if (cs.dpl != cs_rpl)
3376 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3380 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3382 struct kvm_segment ss;
3383 unsigned int ss_rpl;
3385 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3386 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3390 if (ss.type != 3 && ss.type != 7)
3394 if (ss.dpl != ss_rpl) /* DPL != RPL */
3402 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3404 struct kvm_segment var;
3407 vmx_get_segment(vcpu, &var, seg);
3408 rpl = var.selector & SEGMENT_RPL_MASK;
3416 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3417 if (var.dpl < rpl) /* DPL < RPL */
3421 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3427 static bool tr_valid(struct kvm_vcpu *vcpu)
3429 struct kvm_segment tr;
3431 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3435 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3437 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3445 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3447 struct kvm_segment ldtr;
3449 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3453 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3463 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3465 struct kvm_segment cs, ss;
3467 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3468 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3470 return ((cs.selector & SEGMENT_RPL_MASK) ==
3471 (ss.selector & SEGMENT_RPL_MASK));
3475 * Check if guest state is valid. Returns true if valid, false if
3477 * We assume that registers are always usable
3479 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3481 if (enable_unrestricted_guest)
3484 /* real mode guest state checks */
3485 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3486 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3488 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3490 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3492 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3494 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3496 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3499 /* protected mode guest state checks */
3500 if (!cs_ss_rpl_check(vcpu))
3502 if (!code_segment_valid(vcpu))
3504 if (!stack_segment_valid(vcpu))
3506 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3508 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3510 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3512 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3514 if (!tr_valid(vcpu))
3516 if (!ldtr_valid(vcpu))
3520 * - Add checks on RIP
3521 * - Add checks on RFLAGS
3527 static int init_rmode_tss(struct kvm *kvm)
3533 idx = srcu_read_lock(&kvm->srcu);
3534 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3535 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3538 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3539 r = kvm_write_guest_page(kvm, fn++, &data,
3540 TSS_IOPB_BASE_OFFSET, sizeof(u16));
3543 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3546 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3550 r = kvm_write_guest_page(kvm, fn, &data,
3551 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3554 srcu_read_unlock(&kvm->srcu, idx);
3558 static int init_rmode_identity_map(struct kvm *kvm)
3560 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3562 kvm_pfn_t identity_map_pfn;
3565 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3566 mutex_lock(&kvm->slots_lock);
3568 if (likely(kvm_vmx->ept_identity_pagetable_done))
3571 if (!kvm_vmx->ept_identity_map_addr)
3572 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3573 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3575 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3576 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3580 idx = srcu_read_lock(&kvm->srcu);
3581 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3584 /* Set up identity-mapping pagetable for EPT in real mode */
3585 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3586 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3587 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3588 r = kvm_write_guest_page(kvm, identity_map_pfn,
3589 &tmp, i * sizeof(tmp), sizeof(tmp));
3593 kvm_vmx->ept_identity_pagetable_done = true;
3596 srcu_read_unlock(&kvm->srcu, idx);
3599 mutex_unlock(&kvm->slots_lock);
3603 static void seg_setup(int seg)
3605 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3608 vmcs_write16(sf->selector, 0);
3609 vmcs_writel(sf->base, 0);
3610 vmcs_write32(sf->limit, 0xffff);
3612 if (seg == VCPU_SREG_CS)
3613 ar |= 0x08; /* code segment */
3615 vmcs_write32(sf->ar_bytes, ar);
3618 static int alloc_apic_access_page(struct kvm *kvm)
3623 mutex_lock(&kvm->slots_lock);
3624 if (kvm->arch.apic_access_page_done)
3626 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3627 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3631 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3632 if (is_error_page(page)) {
3638 * Do not pin the page in memory, so that memory hot-unplug
3639 * is able to migrate it.
3642 kvm->arch.apic_access_page_done = true;
3644 mutex_unlock(&kvm->slots_lock);
3648 int allocate_vpid(void)
3654 spin_lock(&vmx_vpid_lock);
3655 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3656 if (vpid < VMX_NR_VPIDS)
3657 __set_bit(vpid, vmx_vpid_bitmap);
3660 spin_unlock(&vmx_vpid_lock);
3664 void free_vpid(int vpid)
3666 if (!enable_vpid || vpid == 0)
3668 spin_lock(&vmx_vpid_lock);
3669 __clear_bit(vpid, vmx_vpid_bitmap);
3670 spin_unlock(&vmx_vpid_lock);
3673 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3676 int f = sizeof(unsigned long);
3678 if (!cpu_has_vmx_msr_bitmap())
3681 if (static_branch_unlikely(&enable_evmcs))
3682 evmcs_touch_msr_bitmap();
3685 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3686 * have the write-low and read-high bitmap offsets the wrong way round.
3687 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3689 if (msr <= 0x1fff) {
3690 if (type & MSR_TYPE_R)
3692 __clear_bit(msr, msr_bitmap + 0x000 / f);
3694 if (type & MSR_TYPE_W)
3696 __clear_bit(msr, msr_bitmap + 0x800 / f);
3698 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3700 if (type & MSR_TYPE_R)
3702 __clear_bit(msr, msr_bitmap + 0x400 / f);
3704 if (type & MSR_TYPE_W)
3706 __clear_bit(msr, msr_bitmap + 0xc00 / f);
3711 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3714 int f = sizeof(unsigned long);
3716 if (!cpu_has_vmx_msr_bitmap())
3719 if (static_branch_unlikely(&enable_evmcs))
3720 evmcs_touch_msr_bitmap();
3723 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3724 * have the write-low and read-high bitmap offsets the wrong way round.
3725 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3727 if (msr <= 0x1fff) {
3728 if (type & MSR_TYPE_R)
3730 __set_bit(msr, msr_bitmap + 0x000 / f);
3732 if (type & MSR_TYPE_W)
3734 __set_bit(msr, msr_bitmap + 0x800 / f);
3736 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3738 if (type & MSR_TYPE_R)
3740 __set_bit(msr, msr_bitmap + 0x400 / f);
3742 if (type & MSR_TYPE_W)
3744 __set_bit(msr, msr_bitmap + 0xc00 / f);
3749 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3750 u32 msr, int type, bool value)
3753 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3755 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3758 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3762 if (cpu_has_secondary_exec_ctrls() &&
3763 (secondary_exec_controls_get(to_vmx(vcpu)) &
3764 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3765 mode |= MSR_BITMAP_MODE_X2APIC;
3766 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3767 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3773 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3778 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3779 unsigned word = msr / BITS_PER_LONG;
3780 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3781 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3784 if (mode & MSR_BITMAP_MODE_X2APIC) {
3786 * TPR reads and writes can be virtualized even if virtual interrupt
3787 * delivery is not in use.
3789 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3790 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3791 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3792 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3793 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3798 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3800 struct vcpu_vmx *vmx = to_vmx(vcpu);
3801 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3802 u8 mode = vmx_msr_bitmap_mode(vcpu);
3803 u8 changed = mode ^ vmx->msr_bitmap_mode;
3808 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3809 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3811 vmx->msr_bitmap_mode = mode;
3814 void pt_update_intercept_for_msr(struct vcpu_vmx *vmx)
3816 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3817 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3820 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_STATUS,
3822 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_BASE,
3824 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_MASK,
3826 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_CR3_MATCH,
3828 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3829 vmx_set_intercept_for_msr(msr_bitmap,
3830 MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3831 vmx_set_intercept_for_msr(msr_bitmap,
3832 MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3836 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
3838 return enable_apicv;
3841 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3843 struct vcpu_vmx *vmx = to_vmx(vcpu);
3848 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3849 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3850 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3853 rvi = vmx_get_rvi();
3855 vapic_page = vmx->nested.virtual_apic_map.hva;
3856 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3858 return ((rvi & 0xf0) > (vppr & 0xf0));
3861 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3865 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3867 if (vcpu->mode == IN_GUEST_MODE) {
3869 * The vector of interrupt to be delivered to vcpu had
3870 * been set in PIR before this function.
3872 * Following cases will be reached in this block, and
3873 * we always send a notification event in all cases as
3876 * Case 1: vcpu keeps in non-root mode. Sending a
3877 * notification event posts the interrupt to vcpu.
3879 * Case 2: vcpu exits to root mode and is still
3880 * runnable. PIR will be synced to vIRR before the
3881 * next vcpu entry. Sending a notification event in
3882 * this case has no effect, as vcpu is not in root
3885 * Case 3: vcpu exits to root mode and is blocked.
3886 * vcpu_block() has already synced PIR to vIRR and
3887 * never blocks vcpu if vIRR is not cleared. Therefore,
3888 * a blocked vcpu here does not wait for any requested
3889 * interrupts in PIR, and sending a notification event
3890 * which has no effect is safe here.
3893 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3900 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3903 struct vcpu_vmx *vmx = to_vmx(vcpu);
3905 if (is_guest_mode(vcpu) &&
3906 vector == vmx->nested.posted_intr_nv) {
3908 * If a posted intr is not recognized by hardware,
3909 * we will accomplish it in the next vmentry.
3911 vmx->nested.pi_pending = true;
3912 kvm_make_request(KVM_REQ_EVENT, vcpu);
3913 /* the PIR and ON have been set by L1. */
3914 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3915 kvm_vcpu_kick(vcpu);
3921 * Send interrupt to vcpu via posted interrupt way.
3922 * 1. If target vcpu is running(non-root mode), send posted interrupt
3923 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3924 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3925 * interrupt from PIR in next vmentry.
3927 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3929 struct vcpu_vmx *vmx = to_vmx(vcpu);
3932 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3936 if (!vcpu->arch.apicv_active)
3939 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3942 /* If a previous notification has sent the IPI, nothing to do. */
3943 if (pi_test_and_set_on(&vmx->pi_desc))
3946 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3947 kvm_vcpu_kick(vcpu);
3953 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3954 * will not change in the lifetime of the guest.
3955 * Note that host-state that does change is set elsewhere. E.g., host-state
3956 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3958 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3962 unsigned long cr0, cr3, cr4;
3965 WARN_ON(cr0 & X86_CR0_TS);
3966 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
3969 * Save the most likely value for this task's CR3 in the VMCS.
3970 * We can't use __get_current_cr3_fast() because we're not atomic.
3973 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
3974 vmx->loaded_vmcs->host_state.cr3 = cr3;
3976 /* Save the most likely value for this task's CR4 in the VMCS. */
3977 cr4 = cr4_read_shadow();
3978 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
3979 vmx->loaded_vmcs->host_state.cr4 = cr4;
3981 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
3982 #ifdef CONFIG_X86_64
3984 * Load null selectors, so we can avoid reloading them in
3985 * vmx_prepare_switch_to_host(), in case userspace uses
3986 * the null selectors too (the expected case).
3988 vmcs_write16(HOST_DS_SELECTOR, 0);
3989 vmcs_write16(HOST_ES_SELECTOR, 0);
3991 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3992 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3994 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3995 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
3997 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
3999 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4001 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4002 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4003 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4004 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4006 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4007 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4008 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4011 if (cpu_has_load_ia32_efer())
4012 vmcs_write64(HOST_IA32_EFER, host_efer);
4015 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4017 BUILD_BUG_ON(KVM_CR4_GUEST_OWNED_BITS & ~KVM_POSSIBLE_CR4_GUEST_BITS);
4019 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
4021 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
4022 if (is_guest_mode(&vmx->vcpu))
4023 vmx->vcpu.arch.cr4_guest_owned_bits &=
4024 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
4025 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
4028 u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4030 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4032 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4033 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4036 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4038 if (!enable_preemption_timer)
4039 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4041 return pin_based_exec_ctrl;
4044 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4046 struct vcpu_vmx *vmx = to_vmx(vcpu);
4048 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4049 if (cpu_has_secondary_exec_ctrls()) {
4050 if (kvm_vcpu_apicv_active(vcpu))
4051 secondary_exec_controls_setbit(vmx,
4052 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4053 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4055 secondary_exec_controls_clearbit(vmx,
4056 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4057 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4060 if (cpu_has_vmx_msr_bitmap())
4061 vmx_update_msr_bitmap(vcpu);
4064 u32 vmx_exec_control(struct vcpu_vmx *vmx)
4066 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4068 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4069 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4071 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4072 exec_control &= ~CPU_BASED_TPR_SHADOW;
4073 #ifdef CONFIG_X86_64
4074 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4075 CPU_BASED_CR8_LOAD_EXITING;
4079 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4080 CPU_BASED_CR3_LOAD_EXITING |
4081 CPU_BASED_INVLPG_EXITING;
4082 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4083 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4084 CPU_BASED_MONITOR_EXITING);
4085 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4086 exec_control &= ~CPU_BASED_HLT_EXITING;
4087 return exec_control;
4091 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
4093 struct kvm_vcpu *vcpu = &vmx->vcpu;
4095 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4097 if (pt_mode == PT_MODE_SYSTEM)
4098 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4099 if (!cpu_need_virtualize_apic_accesses(vcpu))
4100 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4102 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4104 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4105 enable_unrestricted_guest = 0;
4107 if (!enable_unrestricted_guest)
4108 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4109 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4110 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4111 if (!kvm_vcpu_apicv_active(vcpu))
4112 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4113 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4114 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4116 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4117 * in vmx_set_cr4. */
4118 exec_control &= ~SECONDARY_EXEC_DESC;
4120 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4122 We can NOT enable shadow_vmcs here because we don't have yet
4125 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4128 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4130 if (vmx_xsaves_supported()) {
4131 /* Exposing XSAVES only when XSAVE is exposed */
4132 bool xsaves_enabled =
4133 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4134 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4136 if (!xsaves_enabled)
4137 exec_control &= ~SECONDARY_EXEC_XSAVES;
4141 vmx->nested.msrs.secondary_ctls_high |=
4142 SECONDARY_EXEC_XSAVES;
4144 vmx->nested.msrs.secondary_ctls_high &=
4145 ~SECONDARY_EXEC_XSAVES;
4149 if (vmx_rdtscp_supported()) {
4150 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
4151 if (!rdtscp_enabled)
4152 exec_control &= ~SECONDARY_EXEC_RDTSCP;
4156 vmx->nested.msrs.secondary_ctls_high |=
4157 SECONDARY_EXEC_RDTSCP;
4159 vmx->nested.msrs.secondary_ctls_high &=
4160 ~SECONDARY_EXEC_RDTSCP;
4164 if (vmx_invpcid_supported()) {
4165 /* Exposing INVPCID only when PCID is exposed */
4166 bool invpcid_enabled =
4167 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
4168 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
4170 if (!invpcid_enabled) {
4171 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
4172 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
4176 if (invpcid_enabled)
4177 vmx->nested.msrs.secondary_ctls_high |=
4178 SECONDARY_EXEC_ENABLE_INVPCID;
4180 vmx->nested.msrs.secondary_ctls_high &=
4181 ~SECONDARY_EXEC_ENABLE_INVPCID;
4185 if (vmx_rdrand_supported()) {
4186 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
4188 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
4192 vmx->nested.msrs.secondary_ctls_high |=
4193 SECONDARY_EXEC_RDRAND_EXITING;
4195 vmx->nested.msrs.secondary_ctls_high &=
4196 ~SECONDARY_EXEC_RDRAND_EXITING;
4200 if (vmx_rdseed_supported()) {
4201 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
4203 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
4207 vmx->nested.msrs.secondary_ctls_high |=
4208 SECONDARY_EXEC_RDSEED_EXITING;
4210 vmx->nested.msrs.secondary_ctls_high &=
4211 ~SECONDARY_EXEC_RDSEED_EXITING;
4215 if (vmx_waitpkg_supported()) {
4216 bool waitpkg_enabled =
4217 guest_cpuid_has(vcpu, X86_FEATURE_WAITPKG);
4219 if (!waitpkg_enabled)
4220 exec_control &= ~SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4223 if (waitpkg_enabled)
4224 vmx->nested.msrs.secondary_ctls_high |=
4225 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4227 vmx->nested.msrs.secondary_ctls_high &=
4228 ~SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4232 vmx->secondary_exec_control = exec_control;
4235 static void ept_set_mmio_spte_mask(void)
4238 * EPT Misconfigurations can be generated if the value of bits 2:0
4239 * of an EPT paging-structure entry is 110b (write/execute).
4241 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
4242 VMX_EPT_MISCONFIG_WX_VALUE, 0);
4245 #define VMX_XSS_EXIT_BITMAP 0
4248 * Sets up the vmcs for emulated real mode.
4250 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
4255 nested_vmx_vcpu_setup();
4257 if (cpu_has_vmx_msr_bitmap())
4258 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4260 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4263 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4264 vmx->hv_deadline_tsc = -1;
4266 exec_controls_set(vmx, vmx_exec_control(vmx));
4268 if (cpu_has_secondary_exec_ctrls()) {
4269 vmx_compute_secondary_exec_control(vmx);
4270 secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
4273 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4274 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4275 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4276 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4277 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4279 vmcs_write16(GUEST_INTR_STATUS, 0);
4281 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4282 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4285 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4286 vmcs_write32(PLE_GAP, ple_gap);
4287 vmx->ple_window = ple_window;
4288 vmx->ple_window_dirty = true;
4291 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4292 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4293 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4295 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4296 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4297 vmx_set_constant_host_state(vmx);
4298 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4299 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4301 if (cpu_has_vmx_vmfunc())
4302 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4304 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4305 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4306 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4307 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4308 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4310 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4311 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4313 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
4314 u32 index = vmx_msr_index[i];
4315 u32 data_low, data_high;
4318 if (rdmsr_safe(index, &data_low, &data_high) < 0)
4320 if (wrmsr_safe(index, data_low, data_high) < 0)
4322 vmx->guest_msrs[j].index = i;
4323 vmx->guest_msrs[j].data = 0;
4324 vmx->guest_msrs[j].mask = -1ull;
4328 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4330 /* 22.2.1, 20.8.1 */
4331 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4333 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
4334 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
4336 set_cr4_guest_host_mask(vmx);
4338 if (vmx_xsaves_supported())
4339 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4342 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4343 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4346 if (cpu_has_vmx_encls_vmexit())
4347 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
4349 if (pt_mode == PT_MODE_HOST_GUEST) {
4350 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4351 /* Bit[6~0] are forced to 1, writes are ignored. */
4352 vmx->pt_desc.guest.output_mask = 0x7F;
4353 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4357 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4359 struct vcpu_vmx *vmx = to_vmx(vcpu);
4360 struct msr_data apic_base_msr;
4363 vmx->rmode.vm86_active = 0;
4366 vmx->msr_ia32_umwait_control = 0;
4368 vcpu->arch.microcode_version = 0x100000000ULL;
4369 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4370 vmx->hv_deadline_tsc = -1;
4371 kvm_set_cr8(vcpu, 0);
4374 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4375 MSR_IA32_APICBASE_ENABLE;
4376 if (kvm_vcpu_is_reset_bsp(vcpu))
4377 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4378 apic_base_msr.host_initiated = true;
4379 kvm_set_apic_base(vcpu, &apic_base_msr);
4382 vmx_segment_cache_clear(vmx);
4384 seg_setup(VCPU_SREG_CS);
4385 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4386 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4388 seg_setup(VCPU_SREG_DS);
4389 seg_setup(VCPU_SREG_ES);
4390 seg_setup(VCPU_SREG_FS);
4391 seg_setup(VCPU_SREG_GS);
4392 seg_setup(VCPU_SREG_SS);
4394 vmcs_write16(GUEST_TR_SELECTOR, 0);
4395 vmcs_writel(GUEST_TR_BASE, 0);
4396 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4397 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4399 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4400 vmcs_writel(GUEST_LDTR_BASE, 0);
4401 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4402 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4405 vmcs_write32(GUEST_SYSENTER_CS, 0);
4406 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4407 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4408 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4411 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4412 kvm_rip_write(vcpu, 0xfff0);
4414 vmcs_writel(GUEST_GDTR_BASE, 0);
4415 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4417 vmcs_writel(GUEST_IDTR_BASE, 0);
4418 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4420 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4421 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4422 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4423 if (kvm_mpx_supported())
4424 vmcs_write64(GUEST_BNDCFGS, 0);
4428 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4430 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4431 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4432 if (cpu_need_tpr_shadow(vcpu))
4433 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4434 __pa(vcpu->arch.apic->regs));
4435 vmcs_write32(TPR_THRESHOLD, 0);
4438 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4441 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4443 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4444 vmx->vcpu.arch.cr0 = cr0;
4445 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4446 vmx_set_cr4(vcpu, 0);
4447 vmx_set_efer(vcpu, 0);
4449 update_exception_bitmap(vcpu);
4451 vpid_sync_context(vmx->vpid);
4453 vmx_clear_hlt(vcpu);
4455 vmx_update_fb_clear_dis(vcpu, vmx);
4458 static void enable_irq_window(struct kvm_vcpu *vcpu)
4460 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4463 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4466 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4467 enable_irq_window(vcpu);
4471 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4474 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4476 struct vcpu_vmx *vmx = to_vmx(vcpu);
4478 int irq = vcpu->arch.interrupt.nr;
4480 trace_kvm_inj_virq(irq);
4482 ++vcpu->stat.irq_injections;
4483 if (vmx->rmode.vm86_active) {
4485 if (vcpu->arch.interrupt.soft)
4486 inc_eip = vcpu->arch.event_exit_inst_len;
4487 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4490 intr = irq | INTR_INFO_VALID_MASK;
4491 if (vcpu->arch.interrupt.soft) {
4492 intr |= INTR_TYPE_SOFT_INTR;
4493 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4494 vmx->vcpu.arch.event_exit_inst_len);
4496 intr |= INTR_TYPE_EXT_INTR;
4497 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4499 vmx_clear_hlt(vcpu);
4502 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4504 struct vcpu_vmx *vmx = to_vmx(vcpu);
4508 * Tracking the NMI-blocked state in software is built upon
4509 * finding the next open IRQ window. This, in turn, depends on
4510 * well-behaving guests: They have to keep IRQs disabled at
4511 * least as long as the NMI handler runs. Otherwise we may
4512 * cause NMI nesting, maybe breaking the guest. But as this is
4513 * highly unlikely, we can live with the residual risk.
4515 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4516 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4519 ++vcpu->stat.nmi_injections;
4520 vmx->loaded_vmcs->nmi_known_unmasked = false;
4522 if (vmx->rmode.vm86_active) {
4523 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4527 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4528 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4530 vmx_clear_hlt(vcpu);
4533 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4535 struct vcpu_vmx *vmx = to_vmx(vcpu);
4539 return vmx->loaded_vmcs->soft_vnmi_blocked;
4540 if (vmx->loaded_vmcs->nmi_known_unmasked)
4542 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4543 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4547 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4549 struct vcpu_vmx *vmx = to_vmx(vcpu);
4552 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4553 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4554 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4557 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4559 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4560 GUEST_INTR_STATE_NMI);
4562 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4563 GUEST_INTR_STATE_NMI);
4567 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4569 if (to_vmx(vcpu)->nested.nested_run_pending)
4573 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4576 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4577 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4578 | GUEST_INTR_STATE_NMI));
4581 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4583 if (to_vmx(vcpu)->nested.nested_run_pending)
4586 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4589 return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4590 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4591 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4594 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4598 if (enable_unrestricted_guest)
4601 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4605 to_kvm_vmx(kvm)->tss_addr = addr;
4606 return init_rmode_tss(kvm);
4609 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4611 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4615 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4620 * Update instruction length as we may reinject the exception
4621 * from user space while in guest debugging mode.
4623 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4624 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4625 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4629 if (vcpu->guest_debug &
4630 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4647 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4648 int vec, u32 err_code)
4651 * Instruction with address size override prefix opcode 0x67
4652 * Cause the #SS fault with 0 error code in VM86 mode.
4654 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4655 if (kvm_emulate_instruction(vcpu, 0)) {
4656 if (vcpu->arch.halt_request) {
4657 vcpu->arch.halt_request = 0;
4658 return kvm_vcpu_halt(vcpu);
4666 * Forward all other exceptions that are valid in real mode.
4667 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4668 * the required debugging infrastructure rework.
4670 kvm_queue_exception(vcpu, vec);
4675 * Trigger machine check on the host. We assume all the MSRs are already set up
4676 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4677 * We pass a fake environment to the machine check handler because we want
4678 * the guest to be always treated like user space, no matter what context
4679 * it used internally.
4681 static void kvm_machine_check(void)
4683 #if defined(CONFIG_X86_MCE)
4684 struct pt_regs regs = {
4685 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4686 .flags = X86_EFLAGS_IF,
4689 do_machine_check(®s, 0);
4693 static int handle_machine_check(struct kvm_vcpu *vcpu)
4695 /* handled by vmx_vcpu_run() */
4699 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4701 struct vcpu_vmx *vmx = to_vmx(vcpu);
4702 struct kvm_run *kvm_run = vcpu->run;
4703 u32 intr_info, ex_no, error_code;
4704 unsigned long cr2, rip, dr6;
4707 vect_info = vmx->idt_vectoring_info;
4708 intr_info = vmx->exit_intr_info;
4710 if (is_machine_check(intr_info) || is_nmi(intr_info))
4711 return 1; /* handled by handle_exception_nmi_irqoff() */
4713 if (is_invalid_opcode(intr_info))
4714 return handle_ud(vcpu);
4717 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4718 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4720 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4721 WARN_ON_ONCE(!enable_vmware_backdoor);
4724 * VMware backdoor emulation on #GP interception only handles
4725 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4726 * error code on #GP.
4729 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4732 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4736 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4737 * MMIO, it is better to report an internal error.
4738 * See the comments in vmx_handle_exit.
4740 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4741 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4742 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4743 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4744 vcpu->run->internal.ndata = 3;
4745 vcpu->run->internal.data[0] = vect_info;
4746 vcpu->run->internal.data[1] = intr_info;
4747 vcpu->run->internal.data[2] = error_code;
4751 if (is_page_fault(intr_info)) {
4752 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4753 /* EPT won't cause page fault directly */
4754 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
4755 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4758 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4760 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4761 return handle_rmode_exception(vcpu, ex_no, error_code);
4765 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4768 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4769 if (!(vcpu->guest_debug &
4770 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4771 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
4772 vcpu->arch.dr6 |= dr6 | DR6_RTM;
4773 if (is_icebp(intr_info))
4774 WARN_ON(!skip_emulated_instruction(vcpu));
4776 kvm_queue_exception(vcpu, DB_VECTOR);
4779 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4780 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4784 * Update instruction length as we may reinject #BP from
4785 * user space while in guest debugging mode. Reading it for
4786 * #DB as well causes no harm, it is not used in that case.
4788 vmx->vcpu.arch.event_exit_inst_len =
4789 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4790 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4791 rip = kvm_rip_read(vcpu);
4792 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4793 kvm_run->debug.arch.exception = ex_no;
4796 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4797 kvm_run->ex.exception = ex_no;
4798 kvm_run->ex.error_code = error_code;
4804 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4806 ++vcpu->stat.irq_exits;
4810 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4812 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4813 vcpu->mmio_needed = 0;
4817 static int handle_io(struct kvm_vcpu *vcpu)
4819 unsigned long exit_qualification;
4820 int size, in, string;
4823 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4824 string = (exit_qualification & 16) != 0;
4826 ++vcpu->stat.io_exits;
4829 return kvm_emulate_instruction(vcpu, 0);
4831 port = exit_qualification >> 16;
4832 size = (exit_qualification & 7) + 1;
4833 in = (exit_qualification & 8) != 0;
4835 return kvm_fast_pio(vcpu, size, port, in);
4839 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4842 * Patch in the VMCALL instruction:
4844 hypercall[0] = 0x0f;
4845 hypercall[1] = 0x01;
4846 hypercall[2] = 0xc1;
4849 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4850 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4852 if (is_guest_mode(vcpu)) {
4853 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4854 unsigned long orig_val = val;
4857 * We get here when L2 changed cr0 in a way that did not change
4858 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4859 * but did change L0 shadowed bits. So we first calculate the
4860 * effective cr0 value that L1 would like to write into the
4861 * hardware. It consists of the L2-owned bits from the new
4862 * value combined with the L1-owned bits from L1's guest_cr0.
4864 val = (val & ~vmcs12->cr0_guest_host_mask) |
4865 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4867 if (!nested_guest_cr0_valid(vcpu, val))
4870 if (kvm_set_cr0(vcpu, val))
4872 vmcs_writel(CR0_READ_SHADOW, orig_val);
4875 if (to_vmx(vcpu)->nested.vmxon &&
4876 !nested_host_cr0_valid(vcpu, val))
4879 return kvm_set_cr0(vcpu, val);
4883 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4885 if (is_guest_mode(vcpu)) {
4886 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4887 unsigned long orig_val = val;
4889 /* analogously to handle_set_cr0 */
4890 val = (val & ~vmcs12->cr4_guest_host_mask) |
4891 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4892 if (kvm_set_cr4(vcpu, val))
4894 vmcs_writel(CR4_READ_SHADOW, orig_val);
4897 return kvm_set_cr4(vcpu, val);
4900 static int handle_desc(struct kvm_vcpu *vcpu)
4902 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4903 return kvm_emulate_instruction(vcpu, 0);
4906 static int handle_cr(struct kvm_vcpu *vcpu)
4908 unsigned long exit_qualification, val;
4914 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4915 cr = exit_qualification & 15;
4916 reg = (exit_qualification >> 8) & 15;
4917 switch ((exit_qualification >> 4) & 3) {
4918 case 0: /* mov to cr */
4919 val = kvm_register_readl(vcpu, reg);
4920 trace_kvm_cr_write(cr, val);
4923 err = handle_set_cr0(vcpu, val);
4924 return kvm_complete_insn_gp(vcpu, err);
4926 WARN_ON_ONCE(enable_unrestricted_guest);
4927 err = kvm_set_cr3(vcpu, val);
4928 return kvm_complete_insn_gp(vcpu, err);
4930 err = handle_set_cr4(vcpu, val);
4931 return kvm_complete_insn_gp(vcpu, err);
4933 u8 cr8_prev = kvm_get_cr8(vcpu);
4935 err = kvm_set_cr8(vcpu, cr8);
4936 ret = kvm_complete_insn_gp(vcpu, err);
4937 if (lapic_in_kernel(vcpu))
4939 if (cr8_prev <= cr8)
4942 * TODO: we might be squashing a
4943 * KVM_GUESTDBG_SINGLESTEP-triggered
4944 * KVM_EXIT_DEBUG here.
4946 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4952 WARN_ONCE(1, "Guest should always own CR0.TS");
4953 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4954 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4955 return kvm_skip_emulated_instruction(vcpu);
4956 case 1: /*mov from cr*/
4959 WARN_ON_ONCE(enable_unrestricted_guest);
4960 val = kvm_read_cr3(vcpu);
4961 kvm_register_write(vcpu, reg, val);
4962 trace_kvm_cr_read(cr, val);
4963 return kvm_skip_emulated_instruction(vcpu);
4965 val = kvm_get_cr8(vcpu);
4966 kvm_register_write(vcpu, reg, val);
4967 trace_kvm_cr_read(cr, val);
4968 return kvm_skip_emulated_instruction(vcpu);
4972 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4973 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4974 kvm_lmsw(vcpu, val);
4976 return kvm_skip_emulated_instruction(vcpu);
4980 vcpu->run->exit_reason = 0;
4981 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4982 (int)(exit_qualification >> 4) & 3, cr);
4986 static int handle_dr(struct kvm_vcpu *vcpu)
4988 unsigned long exit_qualification;
4991 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4992 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
4994 /* First, if DR does not exist, trigger UD */
4995 if (!kvm_require_dr(vcpu, dr))
4998 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
4999 if (!kvm_require_cpl(vcpu, 0))
5001 dr7 = vmcs_readl(GUEST_DR7);
5004 * As the vm-exit takes precedence over the debug trap, we
5005 * need to emulate the latter, either for the host or the
5006 * guest debugging itself.
5008 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5009 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
5010 vcpu->run->debug.arch.dr7 = dr7;
5011 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5012 vcpu->run->debug.arch.exception = DB_VECTOR;
5013 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5016 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
5017 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
5018 kvm_queue_exception(vcpu, DB_VECTOR);
5023 if (vcpu->guest_debug == 0) {
5024 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5027 * No more DR vmexits; force a reload of the debug registers
5028 * and reenter on this instruction. The next vmexit will
5029 * retrieve the full state of the debug registers.
5031 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5035 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5036 if (exit_qualification & TYPE_MOV_FROM_DR) {
5039 if (kvm_get_dr(vcpu, dr, &val))
5041 kvm_register_write(vcpu, reg, val);
5043 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
5046 return kvm_skip_emulated_instruction(vcpu);
5049 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
5051 return vcpu->arch.dr6;
5054 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
5058 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5060 get_debugreg(vcpu->arch.db[0], 0);
5061 get_debugreg(vcpu->arch.db[1], 1);
5062 get_debugreg(vcpu->arch.db[2], 2);
5063 get_debugreg(vcpu->arch.db[3], 3);
5064 get_debugreg(vcpu->arch.dr6, 6);
5065 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5067 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5068 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5071 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5073 vmcs_writel(GUEST_DR7, val);
5076 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5078 kvm_apic_update_ppr(vcpu);
5082 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5084 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5086 kvm_make_request(KVM_REQ_EVENT, vcpu);
5088 ++vcpu->stat.irq_window_exits;
5092 static int handle_vmcall(struct kvm_vcpu *vcpu)
5094 return kvm_emulate_hypercall(vcpu);
5097 static int handle_invd(struct kvm_vcpu *vcpu)
5099 return kvm_emulate_instruction(vcpu, 0);
5102 static int handle_invlpg(struct kvm_vcpu *vcpu)
5104 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5106 kvm_mmu_invlpg(vcpu, exit_qualification);
5107 return kvm_skip_emulated_instruction(vcpu);
5110 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5114 err = kvm_rdpmc(vcpu);
5115 return kvm_complete_insn_gp(vcpu, err);
5118 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5120 return kvm_emulate_wbinvd(vcpu);
5123 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5125 u64 new_bv = kvm_read_edx_eax(vcpu);
5126 u32 index = kvm_rcx_read(vcpu);
5128 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5129 return kvm_skip_emulated_instruction(vcpu);
5133 static int handle_apic_access(struct kvm_vcpu *vcpu)
5135 if (likely(fasteoi)) {
5136 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5137 int access_type, offset;
5139 access_type = exit_qualification & APIC_ACCESS_TYPE;
5140 offset = exit_qualification & APIC_ACCESS_OFFSET;
5142 * Sane guest uses MOV to write EOI, with written value
5143 * not cared. So make a short-circuit here by avoiding
5144 * heavy instruction emulation.
5146 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5147 (offset == APIC_EOI)) {
5148 kvm_lapic_set_eoi(vcpu);
5149 return kvm_skip_emulated_instruction(vcpu);
5152 return kvm_emulate_instruction(vcpu, 0);
5155 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5157 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5158 int vector = exit_qualification & 0xff;
5160 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5161 kvm_apic_set_eoi_accelerated(vcpu, vector);
5165 static int handle_apic_write(struct kvm_vcpu *vcpu)
5167 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5168 u32 offset = exit_qualification & 0xfff;
5170 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5171 kvm_apic_write_nodecode(vcpu, offset);
5175 static int handle_task_switch(struct kvm_vcpu *vcpu)
5177 struct vcpu_vmx *vmx = to_vmx(vcpu);
5178 unsigned long exit_qualification;
5179 bool has_error_code = false;
5182 int reason, type, idt_v, idt_index;
5184 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5185 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5186 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5188 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5190 reason = (u32)exit_qualification >> 30;
5191 if (reason == TASK_SWITCH_GATE && idt_v) {
5193 case INTR_TYPE_NMI_INTR:
5194 vcpu->arch.nmi_injected = false;
5195 vmx_set_nmi_mask(vcpu, true);
5197 case INTR_TYPE_EXT_INTR:
5198 case INTR_TYPE_SOFT_INTR:
5199 kvm_clear_interrupt_queue(vcpu);
5201 case INTR_TYPE_HARD_EXCEPTION:
5202 if (vmx->idt_vectoring_info &
5203 VECTORING_INFO_DELIVER_CODE_MASK) {
5204 has_error_code = true;
5206 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5209 case INTR_TYPE_SOFT_EXCEPTION:
5210 kvm_clear_exception_queue(vcpu);
5216 tss_selector = exit_qualification;
5218 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5219 type != INTR_TYPE_EXT_INTR &&
5220 type != INTR_TYPE_NMI_INTR))
5221 WARN_ON(!skip_emulated_instruction(vcpu));
5224 * TODO: What about debug traps on tss switch?
5225 * Are we supposed to inject them and update dr6?
5227 return kvm_task_switch(vcpu, tss_selector,
5228 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5229 reason, has_error_code, error_code);
5232 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5234 unsigned long exit_qualification;
5238 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5241 * EPT violation happened while executing iret from NMI,
5242 * "blocked by NMI" bit has to be set before next VM entry.
5243 * There are errata that may cause this bit to not be set:
5246 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5248 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5249 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5251 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5252 trace_kvm_page_fault(gpa, exit_qualification);
5254 /* Is it a read fault? */
5255 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5256 ? PFERR_USER_MASK : 0;
5257 /* Is it a write fault? */
5258 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5259 ? PFERR_WRITE_MASK : 0;
5260 /* Is it a fetch fault? */
5261 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5262 ? PFERR_FETCH_MASK : 0;
5263 /* ept page table entry is present? */
5264 error_code |= (exit_qualification &
5265 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5266 EPT_VIOLATION_EXECUTABLE))
5267 ? PFERR_PRESENT_MASK : 0;
5269 error_code |= (exit_qualification & 0x100) != 0 ?
5270 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5272 vcpu->arch.exit_qualification = exit_qualification;
5273 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5276 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5281 * A nested guest cannot optimize MMIO vmexits, because we have an
5282 * nGPA here instead of the required GPA.
5284 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5285 if (!is_guest_mode(vcpu) &&
5286 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5287 trace_kvm_fast_mmio(gpa);
5288 return kvm_skip_emulated_instruction(vcpu);
5291 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5294 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5296 WARN_ON_ONCE(!enable_vnmi);
5297 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5298 ++vcpu->stat.nmi_window_exits;
5299 kvm_make_request(KVM_REQ_EVENT, vcpu);
5304 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5306 struct vcpu_vmx *vmx = to_vmx(vcpu);
5307 bool intr_window_requested;
5308 unsigned count = 130;
5311 * We should never reach the point where we are emulating L2
5312 * due to invalid guest state as that means we incorrectly
5313 * allowed a nested VMEntry with an invalid vmcs12.
5315 WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
5317 intr_window_requested = exec_controls_get(vmx) &
5318 CPU_BASED_INTR_WINDOW_EXITING;
5320 while (vmx->emulation_required && count-- != 0) {
5321 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5322 return handle_interrupt_window(&vmx->vcpu);
5324 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5327 if (!kvm_emulate_instruction(vcpu, 0))
5330 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5331 vcpu->arch.exception.pending) {
5332 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5333 vcpu->run->internal.suberror =
5334 KVM_INTERNAL_ERROR_EMULATION;
5335 vcpu->run->internal.ndata = 0;
5339 if (vcpu->arch.halt_request) {
5340 vcpu->arch.halt_request = 0;
5341 return kvm_vcpu_halt(vcpu);
5345 * Note, return 1 and not 0, vcpu_run() is responsible for
5346 * morphing the pending signal into the proper return code.
5348 if (signal_pending(current))
5358 static void grow_ple_window(struct kvm_vcpu *vcpu)
5360 struct vcpu_vmx *vmx = to_vmx(vcpu);
5361 unsigned int old = vmx->ple_window;
5363 vmx->ple_window = __grow_ple_window(old, ple_window,
5367 if (vmx->ple_window != old) {
5368 vmx->ple_window_dirty = true;
5369 trace_kvm_ple_window_update(vcpu->vcpu_id,
5370 vmx->ple_window, old);
5374 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5376 struct vcpu_vmx *vmx = to_vmx(vcpu);
5377 unsigned int old = vmx->ple_window;
5379 vmx->ple_window = __shrink_ple_window(old, ple_window,
5383 if (vmx->ple_window != old) {
5384 vmx->ple_window_dirty = true;
5385 trace_kvm_ple_window_update(vcpu->vcpu_id,
5386 vmx->ple_window, old);
5391 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5393 static void wakeup_handler(void)
5395 struct kvm_vcpu *vcpu;
5396 int cpu = smp_processor_id();
5398 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5399 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5400 blocked_vcpu_list) {
5401 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5403 if (pi_test_on(pi_desc) == 1)
5404 kvm_vcpu_kick(vcpu);
5406 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5409 static void vmx_enable_tdp(void)
5411 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5412 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5413 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5414 0ull, VMX_EPT_EXECUTABLE_MASK,
5415 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5416 VMX_EPT_RWX_MASK, 0ull);
5418 ept_set_mmio_spte_mask();
5423 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5424 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5426 static int handle_pause(struct kvm_vcpu *vcpu)
5428 if (!kvm_pause_in_guest(vcpu->kvm))
5429 grow_ple_window(vcpu);
5432 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5433 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5434 * never set PAUSE_EXITING and just set PLE if supported,
5435 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5437 kvm_vcpu_on_spin(vcpu, true);
5438 return kvm_skip_emulated_instruction(vcpu);
5441 static int handle_nop(struct kvm_vcpu *vcpu)
5443 return kvm_skip_emulated_instruction(vcpu);
5446 static int handle_mwait(struct kvm_vcpu *vcpu)
5448 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5449 return handle_nop(vcpu);
5452 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5454 kvm_queue_exception(vcpu, UD_VECTOR);
5458 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5463 static int handle_monitor(struct kvm_vcpu *vcpu)
5465 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5466 return handle_nop(vcpu);
5469 static int handle_invpcid(struct kvm_vcpu *vcpu)
5471 u32 vmx_instruction_info;
5475 struct x86_exception e;
5477 unsigned long roots_to_free = 0;
5483 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5484 kvm_queue_exception(vcpu, UD_VECTOR);
5488 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5489 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5492 kvm_inject_gp(vcpu, 0);
5496 /* According to the Intel instruction reference, the memory operand
5497 * is read even if it isn't needed (e.g., for type==all)
5499 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5500 vmx_instruction_info, false,
5501 sizeof(operand), &gva))
5504 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5505 kvm_inject_page_fault(vcpu, &e);
5509 if (operand.pcid >> 12 != 0) {
5510 kvm_inject_gp(vcpu, 0);
5514 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5517 case INVPCID_TYPE_INDIV_ADDR:
5518 if ((!pcid_enabled && (operand.pcid != 0)) ||
5519 is_noncanonical_address(operand.gla, vcpu)) {
5520 kvm_inject_gp(vcpu, 0);
5523 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5524 return kvm_skip_emulated_instruction(vcpu);
5526 case INVPCID_TYPE_SINGLE_CTXT:
5527 if (!pcid_enabled && (operand.pcid != 0)) {
5528 kvm_inject_gp(vcpu, 0);
5532 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5533 kvm_mmu_sync_roots(vcpu);
5534 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5537 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5538 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
5540 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5542 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5544 * If neither the current cr3 nor any of the prev_roots use the
5545 * given PCID, then nothing needs to be done here because a
5546 * resync will happen anyway before switching to any other CR3.
5549 return kvm_skip_emulated_instruction(vcpu);
5551 case INVPCID_TYPE_ALL_NON_GLOBAL:
5553 * Currently, KVM doesn't mark global entries in the shadow
5554 * page tables, so a non-global flush just degenerates to a
5555 * global flush. If needed, we could optimize this later by
5556 * keeping track of global entries in shadow page tables.
5560 case INVPCID_TYPE_ALL_INCL_GLOBAL:
5561 kvm_mmu_unload(vcpu);
5562 return kvm_skip_emulated_instruction(vcpu);
5565 BUG(); /* We have already checked above that type <= 3 */
5569 static int handle_pml_full(struct kvm_vcpu *vcpu)
5571 unsigned long exit_qualification;
5573 trace_kvm_pml_full(vcpu->vcpu_id);
5575 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5578 * PML buffer FULL happened while executing iret from NMI,
5579 * "blocked by NMI" bit has to be set before next VM entry.
5581 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5583 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5584 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5585 GUEST_INTR_STATE_NMI);
5588 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5589 * here.., and there's no userspace involvement needed for PML.
5594 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5596 struct vcpu_vmx *vmx = to_vmx(vcpu);
5598 if (!vmx->req_immediate_exit &&
5599 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled))
5600 kvm_lapic_expired_hv_timer(vcpu);
5606 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5607 * are overwritten by nested_vmx_setup() when nested=1.
5609 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5611 kvm_queue_exception(vcpu, UD_VECTOR);
5615 static int handle_encls(struct kvm_vcpu *vcpu)
5618 * SGX virtualization is not yet supported. There is no software
5619 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5620 * to prevent the guest from executing ENCLS.
5622 kvm_queue_exception(vcpu, UD_VECTOR);
5627 * The exit handlers return 1 if the exit was handled fully and guest execution
5628 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5629 * to be done to userspace and return 0.
5631 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5632 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5633 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5634 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5635 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5636 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5637 [EXIT_REASON_CR_ACCESS] = handle_cr,
5638 [EXIT_REASON_DR_ACCESS] = handle_dr,
5639 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5640 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5641 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5642 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5643 [EXIT_REASON_HLT] = kvm_emulate_halt,
5644 [EXIT_REASON_INVD] = handle_invd,
5645 [EXIT_REASON_INVLPG] = handle_invlpg,
5646 [EXIT_REASON_RDPMC] = handle_rdpmc,
5647 [EXIT_REASON_VMCALL] = handle_vmcall,
5648 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5649 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5650 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5651 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5652 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5653 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5654 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5655 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5656 [EXIT_REASON_VMON] = handle_vmx_instruction,
5657 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5658 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5659 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5660 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5661 [EXIT_REASON_WBINVD] = handle_wbinvd,
5662 [EXIT_REASON_XSETBV] = handle_xsetbv,
5663 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5664 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5665 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5666 [EXIT_REASON_LDTR_TR] = handle_desc,
5667 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5668 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5669 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5670 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5671 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5672 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5673 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5674 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5675 [EXIT_REASON_RDRAND] = handle_invalid_op,
5676 [EXIT_REASON_RDSEED] = handle_invalid_op,
5677 [EXIT_REASON_PML_FULL] = handle_pml_full,
5678 [EXIT_REASON_INVPCID] = handle_invpcid,
5679 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5680 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5681 [EXIT_REASON_ENCLS] = handle_encls,
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)
5689 *info1 = vmcs_readl(EXIT_QUALIFICATION);
5690 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
5693 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5696 __free_page(vmx->pml_pg);
5701 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5703 struct vcpu_vmx *vmx = to_vmx(vcpu);
5707 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5709 /* Do nothing if PML buffer is empty */
5710 if (pml_idx == (PML_ENTITY_NUM - 1))
5713 /* PML index always points to next available PML buffer entity */
5714 if (pml_idx >= PML_ENTITY_NUM)
5719 pml_buf = page_address(vmx->pml_pg);
5720 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5723 gpa = pml_buf[pml_idx];
5724 WARN_ON(gpa & (PAGE_SIZE - 1));
5725 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5728 /* reset PML index */
5729 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5733 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5734 * Called before reporting dirty_bitmap to userspace.
5736 static void kvm_flush_pml_buffers(struct kvm *kvm)
5739 struct kvm_vcpu *vcpu;
5741 * We only need to kick vcpu out of guest mode here, as PML buffer
5742 * is flushed at beginning of all VMEXITs, and it's obvious that only
5743 * vcpus running in guest are possible to have unflushed GPAs in PML
5746 kvm_for_each_vcpu(i, vcpu, kvm)
5747 kvm_vcpu_kick(vcpu);
5750 static void vmx_dump_sel(char *name, uint32_t sel)
5752 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5753 name, vmcs_read16(sel),
5754 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5755 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5756 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5759 static void vmx_dump_dtsel(char *name, uint32_t limit)
5761 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5762 name, vmcs_read32(limit),
5763 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5766 void dump_vmcs(void)
5768 u32 vmentry_ctl, vmexit_ctl;
5769 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5774 if (!dump_invalid_vmcs) {
5775 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5779 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5780 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5781 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5782 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5783 cr4 = vmcs_readl(GUEST_CR4);
5784 efer = vmcs_read64(GUEST_IA32_EFER);
5785 secondary_exec_control = 0;
5786 if (cpu_has_secondary_exec_ctrls())
5787 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5789 pr_err("*** Guest State ***\n");
5790 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5791 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5792 vmcs_readl(CR0_GUEST_HOST_MASK));
5793 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5794 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5795 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5796 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5797 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5799 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5800 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5801 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5802 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5804 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5805 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5806 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5807 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5808 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5809 vmcs_readl(GUEST_SYSENTER_ESP),
5810 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5811 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5812 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5813 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5814 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5815 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5816 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5817 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5818 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5819 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5820 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5821 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5822 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5823 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5824 efer, vmcs_read64(GUEST_IA32_PAT));
5825 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5826 vmcs_read64(GUEST_IA32_DEBUGCTL),
5827 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5828 if (cpu_has_load_perf_global_ctrl() &&
5829 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5830 pr_err("PerfGlobCtl = 0x%016llx\n",
5831 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5832 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5833 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5834 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5835 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5836 vmcs_read32(GUEST_ACTIVITY_STATE));
5837 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5838 pr_err("InterruptStatus = %04x\n",
5839 vmcs_read16(GUEST_INTR_STATUS));
5841 pr_err("*** Host State ***\n");
5842 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5843 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5844 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5845 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5846 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5847 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5848 vmcs_read16(HOST_TR_SELECTOR));
5849 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5850 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5851 vmcs_readl(HOST_TR_BASE));
5852 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5853 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5854 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5855 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5856 vmcs_readl(HOST_CR4));
5857 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5858 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5859 vmcs_read32(HOST_IA32_SYSENTER_CS),
5860 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5861 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5862 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5863 vmcs_read64(HOST_IA32_EFER),
5864 vmcs_read64(HOST_IA32_PAT));
5865 if (cpu_has_load_perf_global_ctrl() &&
5866 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5867 pr_err("PerfGlobCtl = 0x%016llx\n",
5868 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5870 pr_err("*** Control State ***\n");
5871 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5872 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5873 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5874 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5875 vmcs_read32(EXCEPTION_BITMAP),
5876 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5877 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5878 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5879 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5880 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5881 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5882 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5883 vmcs_read32(VM_EXIT_INTR_INFO),
5884 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5885 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5886 pr_err(" reason=%08x qualification=%016lx\n",
5887 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5888 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5889 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5890 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5891 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5892 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5893 pr_err("TSC Multiplier = 0x%016llx\n",
5894 vmcs_read64(TSC_MULTIPLIER));
5895 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5896 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5897 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5898 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5900 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5901 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5902 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5903 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5905 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5906 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5907 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5908 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5909 n = vmcs_read32(CR3_TARGET_COUNT);
5910 for (i = 0; i + 1 < n; i += 4)
5911 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
5912 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
5913 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
5915 pr_err("CR3 target%u=%016lx\n",
5916 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
5917 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5918 pr_err("PLE Gap=%08x Window=%08x\n",
5919 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5920 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5921 pr_err("Virtual processor ID = 0x%04x\n",
5922 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5926 * The guest has exited. See if we can fix it or if we need userspace
5929 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
5931 struct vcpu_vmx *vmx = to_vmx(vcpu);
5932 u32 exit_reason = vmx->exit_reason;
5933 u32 vectoring_info = vmx->idt_vectoring_info;
5935 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
5938 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5939 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5940 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5941 * mode as if vcpus is in root mode, the PML buffer must has been
5945 vmx_flush_pml_buffer(vcpu);
5947 /* If guest state is invalid, start emulating */
5948 if (vmx->emulation_required)
5949 return handle_invalid_guest_state(vcpu);
5951 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
5952 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
5954 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5956 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5957 vcpu->run->fail_entry.hardware_entry_failure_reason
5962 if (unlikely(vmx->fail)) {
5964 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5965 vcpu->run->fail_entry.hardware_entry_failure_reason
5966 = vmcs_read32(VM_INSTRUCTION_ERROR);
5972 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5973 * delivery event since it indicates guest is accessing MMIO.
5974 * The vm-exit can be triggered again after return to guest that
5975 * will cause infinite loop.
5977 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5978 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5979 exit_reason != EXIT_REASON_EPT_VIOLATION &&
5980 exit_reason != EXIT_REASON_PML_FULL &&
5981 exit_reason != EXIT_REASON_APIC_ACCESS &&
5982 exit_reason != EXIT_REASON_TASK_SWITCH)) {
5983 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5984 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
5985 vcpu->run->internal.ndata = 3;
5986 vcpu->run->internal.data[0] = vectoring_info;
5987 vcpu->run->internal.data[1] = exit_reason;
5988 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
5989 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
5990 vcpu->run->internal.ndata++;
5991 vcpu->run->internal.data[3] =
5992 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5997 if (unlikely(!enable_vnmi &&
5998 vmx->loaded_vmcs->soft_vnmi_blocked)) {
5999 if (vmx_interrupt_allowed(vcpu)) {
6000 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6001 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6002 vcpu->arch.nmi_pending) {
6004 * This CPU don't support us in finding the end of an
6005 * NMI-blocked window if the guest runs with IRQs
6006 * disabled. So we pull the trigger after 1 s of
6007 * futile waiting, but inform the user about this.
6009 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6010 "state on VCPU %d after 1 s timeout\n",
6011 __func__, vcpu->vcpu_id);
6012 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6016 if (exit_reason < kvm_vmx_max_exit_handlers
6017 && kvm_vmx_exit_handlers[exit_reason]) {
6018 #ifdef CONFIG_RETPOLINE
6019 if (exit_reason == EXIT_REASON_MSR_WRITE)
6020 return kvm_emulate_wrmsr(vcpu);
6021 else if (exit_reason == EXIT_REASON_PREEMPTION_TIMER)
6022 return handle_preemption_timer(vcpu);
6023 else if (exit_reason == EXIT_REASON_INTERRUPT_WINDOW)
6024 return handle_interrupt_window(vcpu);
6025 else if (exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6026 return handle_external_interrupt(vcpu);
6027 else if (exit_reason == EXIT_REASON_HLT)
6028 return kvm_emulate_halt(vcpu);
6029 else if (exit_reason == EXIT_REASON_EPT_MISCONFIG)
6030 return handle_ept_misconfig(vcpu);
6032 return kvm_vmx_exit_handlers[exit_reason](vcpu);
6034 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6037 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6038 vcpu->run->internal.suberror =
6039 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6040 vcpu->run->internal.ndata = 1;
6041 vcpu->run->internal.data[0] = exit_reason;
6047 * Software based L1D cache flush which is used when microcode providing
6048 * the cache control MSR is not loaded.
6050 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6051 * flush it is required to read in 64 KiB because the replacement algorithm
6052 * is not exactly LRU. This could be sized at runtime via topology
6053 * information but as all relevant affected CPUs have 32KiB L1D cache size
6054 * there is no point in doing so.
6056 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6058 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6061 * This code is only executed when the the flush mode is 'cond' or
6064 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6068 * Clear the per-vcpu flush bit, it gets set again
6069 * either from vcpu_run() or from one of the unsafe
6072 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6073 vcpu->arch.l1tf_flush_l1d = false;
6076 * Clear the per-cpu flush bit, it gets set again from
6077 * the interrupt handlers.
6079 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6080 kvm_clear_cpu_l1tf_flush_l1d();
6086 vcpu->stat.l1d_flush++;
6088 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6089 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6094 /* First ensure the pages are in the TLB */
6095 "xorl %%eax, %%eax\n"
6096 ".Lpopulate_tlb:\n\t"
6097 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6098 "addl $4096, %%eax\n\t"
6099 "cmpl %%eax, %[size]\n\t"
6100 "jne .Lpopulate_tlb\n\t"
6101 "xorl %%eax, %%eax\n\t"
6103 /* Now fill the cache */
6104 "xorl %%eax, %%eax\n"
6106 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6107 "addl $64, %%eax\n\t"
6108 "cmpl %%eax, %[size]\n\t"
6109 "jne .Lfill_cache\n\t"
6111 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6113 : "eax", "ebx", "ecx", "edx");
6116 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6118 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6120 if (is_guest_mode(vcpu) &&
6121 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6124 if (irr == -1 || tpr < irr) {
6125 vmcs_write32(TPR_THRESHOLD, 0);
6129 vmcs_write32(TPR_THRESHOLD, irr);
6132 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6134 struct vcpu_vmx *vmx = to_vmx(vcpu);
6135 u32 sec_exec_control;
6137 if (!lapic_in_kernel(vcpu))
6140 if (!flexpriority_enabled &&
6141 !cpu_has_vmx_virtualize_x2apic_mode())
6144 /* Postpone execution until vmcs01 is the current VMCS. */
6145 if (is_guest_mode(vcpu)) {
6146 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6150 sec_exec_control = secondary_exec_controls_get(vmx);
6151 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6152 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6154 switch (kvm_get_apic_mode(vcpu)) {
6155 case LAPIC_MODE_INVALID:
6156 WARN_ONCE(true, "Invalid local APIC state");
6157 case LAPIC_MODE_DISABLED:
6159 case LAPIC_MODE_XAPIC:
6160 if (flexpriority_enabled) {
6162 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6163 vmx_flush_tlb(vcpu, true);
6166 case LAPIC_MODE_X2APIC:
6167 if (cpu_has_vmx_virtualize_x2apic_mode())
6169 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6172 secondary_exec_controls_set(vmx, sec_exec_control);
6174 vmx_update_msr_bitmap(vcpu);
6177 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
6179 if (!is_guest_mode(vcpu)) {
6180 vmcs_write64(APIC_ACCESS_ADDR, hpa);
6181 vmx_flush_tlb(vcpu, true);
6185 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6193 status = vmcs_read16(GUEST_INTR_STATUS);
6195 if (max_isr != old) {
6197 status |= max_isr << 8;
6198 vmcs_write16(GUEST_INTR_STATUS, status);
6202 static void vmx_set_rvi(int vector)
6210 status = vmcs_read16(GUEST_INTR_STATUS);
6211 old = (u8)status & 0xff;
6212 if ((u8)vector != old) {
6214 status |= (u8)vector;
6215 vmcs_write16(GUEST_INTR_STATUS, status);
6219 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6222 * When running L2, updating RVI is only relevant when
6223 * vmcs12 virtual-interrupt-delivery enabled.
6224 * However, it can be enabled only when L1 also
6225 * intercepts external-interrupts and in that case
6226 * we should not update vmcs02 RVI but instead intercept
6227 * interrupt. Therefore, do nothing when running L2.
6229 if (!is_guest_mode(vcpu))
6230 vmx_set_rvi(max_irr);
6233 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6235 struct vcpu_vmx *vmx = to_vmx(vcpu);
6237 bool max_irr_updated;
6239 WARN_ON(!vcpu->arch.apicv_active);
6240 if (pi_test_on(&vmx->pi_desc)) {
6241 pi_clear_on(&vmx->pi_desc);
6243 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6244 * But on x86 this is just a compiler barrier anyway.
6246 smp_mb__after_atomic();
6248 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6251 * If we are running L2 and L1 has a new pending interrupt
6252 * which can be injected, we should re-evaluate
6253 * what should be done with this new L1 interrupt.
6254 * If L1 intercepts external-interrupts, we should
6255 * exit from L2 to L1. Otherwise, interrupt should be
6256 * delivered directly to L2.
6258 if (is_guest_mode(vcpu) && max_irr_updated) {
6259 if (nested_exit_on_intr(vcpu))
6260 kvm_vcpu_exiting_guest_mode(vcpu);
6262 kvm_make_request(KVM_REQ_EVENT, vcpu);
6265 max_irr = kvm_lapic_find_highest_irr(vcpu);
6267 vmx_hwapic_irr_update(vcpu, max_irr);
6271 static bool vmx_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
6273 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6275 return pi_test_on(pi_desc) ||
6276 (pi_test_sn(pi_desc) && !pi_is_pir_empty(pi_desc));
6279 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6281 if (!kvm_vcpu_apicv_active(vcpu))
6284 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6285 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6286 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6287 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6290 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6292 struct vcpu_vmx *vmx = to_vmx(vcpu);
6294 pi_clear_on(&vmx->pi_desc);
6295 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6298 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6300 vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6302 /* if exit due to PF check for async PF */
6303 if (is_page_fault(vmx->exit_intr_info))
6304 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
6306 /* Handle machine checks before interrupts are enabled */
6307 if (is_machine_check(vmx->exit_intr_info))
6308 kvm_machine_check();
6310 /* We need to handle NMIs before interrupts are enabled */
6311 if (is_nmi(vmx->exit_intr_info)) {
6312 kvm_before_interrupt(&vmx->vcpu);
6314 kvm_after_interrupt(&vmx->vcpu);
6318 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6320 unsigned int vector;
6321 unsigned long entry;
6322 #ifdef CONFIG_X86_64
6328 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6329 if (WARN_ONCE(!is_external_intr(intr_info),
6330 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6333 vector = intr_info & INTR_INFO_VECTOR_MASK;
6334 desc = (gate_desc *)host_idt_base + vector;
6335 entry = gate_offset(desc);
6337 kvm_before_interrupt(vcpu);
6340 #ifdef CONFIG_X86_64
6341 "mov %%" _ASM_SP ", %[sp]\n\t"
6342 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
6347 __ASM_SIZE(push) " $%c[cs]\n\t"
6350 #ifdef CONFIG_X86_64
6355 THUNK_TARGET(entry),
6356 [ss]"i"(__KERNEL_DS),
6357 [cs]"i"(__KERNEL_CS)
6360 kvm_after_interrupt(vcpu);
6361 vcpu->arch.at_instruction_boundary = true;
6363 STACK_FRAME_NON_STANDARD(handle_external_interrupt_irqoff);
6365 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6367 struct vcpu_vmx *vmx = to_vmx(vcpu);
6369 if (vmx->exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6370 handle_external_interrupt_irqoff(vcpu);
6371 else if (vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)
6372 handle_exception_nmi_irqoff(vmx);
6375 static bool vmx_has_emulated_msr(int index)
6378 case MSR_IA32_SMBASE:
6380 * We cannot do SMM unless we can run the guest in big
6383 return enable_unrestricted_guest || emulate_invalid_guest_state;
6384 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6386 case MSR_AMD64_VIRT_SPEC_CTRL:
6387 /* This is AMD only. */
6394 static bool vmx_pt_supported(void)
6396 return pt_mode == PT_MODE_HOST_GUEST;
6399 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6404 bool idtv_info_valid;
6406 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6409 if (vmx->loaded_vmcs->nmi_known_unmasked)
6412 * Can't use vmx->exit_intr_info since we're not sure what
6413 * the exit reason is.
6415 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6416 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6417 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6419 * SDM 3: 27.7.1.2 (September 2008)
6420 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6421 * a guest IRET fault.
6422 * SDM 3: 23.2.2 (September 2008)
6423 * Bit 12 is undefined in any of the following cases:
6424 * If the VM exit sets the valid bit in the IDT-vectoring
6425 * information field.
6426 * If the VM exit is due to a double fault.
6428 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6429 vector != DF_VECTOR && !idtv_info_valid)
6430 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6431 GUEST_INTR_STATE_NMI);
6433 vmx->loaded_vmcs->nmi_known_unmasked =
6434 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6435 & GUEST_INTR_STATE_NMI);
6436 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6437 vmx->loaded_vmcs->vnmi_blocked_time +=
6438 ktime_to_ns(ktime_sub(ktime_get(),
6439 vmx->loaded_vmcs->entry_time));
6442 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6443 u32 idt_vectoring_info,
6444 int instr_len_field,
6445 int error_code_field)
6449 bool idtv_info_valid;
6451 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6453 vcpu->arch.nmi_injected = false;
6454 kvm_clear_exception_queue(vcpu);
6455 kvm_clear_interrupt_queue(vcpu);
6457 if (!idtv_info_valid)
6460 kvm_make_request(KVM_REQ_EVENT, vcpu);
6462 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6463 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6466 case INTR_TYPE_NMI_INTR:
6467 vcpu->arch.nmi_injected = true;
6469 * SDM 3: 27.7.1.2 (September 2008)
6470 * Clear bit "block by NMI" before VM entry if a NMI
6473 vmx_set_nmi_mask(vcpu, false);
6475 case INTR_TYPE_SOFT_EXCEPTION:
6476 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6478 case INTR_TYPE_HARD_EXCEPTION:
6479 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6480 u32 err = vmcs_read32(error_code_field);
6481 kvm_requeue_exception_e(vcpu, vector, err);
6483 kvm_requeue_exception(vcpu, vector);
6485 case INTR_TYPE_SOFT_INTR:
6486 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6488 case INTR_TYPE_EXT_INTR:
6489 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6496 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6498 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6499 VM_EXIT_INSTRUCTION_LEN,
6500 IDT_VECTORING_ERROR_CODE);
6503 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6505 __vmx_complete_interrupts(vcpu,
6506 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6507 VM_ENTRY_INSTRUCTION_LEN,
6508 VM_ENTRY_EXCEPTION_ERROR_CODE);
6510 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6513 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6516 struct perf_guest_switch_msr *msrs;
6518 msrs = perf_guest_get_msrs(&nr_msrs);
6523 for (i = 0; i < nr_msrs; i++)
6524 if (msrs[i].host == msrs[i].guest)
6525 clear_atomic_switch_msr(vmx, msrs[i].msr);
6527 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6528 msrs[i].host, false);
6531 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6533 struct vcpu_vmx *vmx = to_vmx(vcpu);
6537 if (vmx->req_immediate_exit) {
6538 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6539 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6540 } else if (vmx->hv_deadline_tsc != -1) {
6542 if (vmx->hv_deadline_tsc > tscl)
6543 /* set_hv_timer ensures the delta fits in 32-bits */
6544 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6545 cpu_preemption_timer_multi);
6549 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6550 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6551 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6552 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6553 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6557 void vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6559 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6560 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6561 vmcs_writel(HOST_RSP, host_rsp);
6565 void noinstr vmx_spec_ctrl_restore_host(struct vcpu_vmx *vmx,
6568 u64 hostval = this_cpu_read(x86_spec_ctrl_current);
6570 if (!cpu_feature_enabled(X86_FEATURE_MSR_SPEC_CTRL))
6573 if (flags & VMX_RUN_SAVE_SPEC_CTRL)
6574 vmx->spec_ctrl = __rdmsr(MSR_IA32_SPEC_CTRL);
6577 * If the guest/host SPEC_CTRL values differ, restore the host value.
6579 * For legacy IBRS, the IBRS bit always needs to be written after
6580 * transitioning from a less privileged predictor mode, regardless of
6581 * whether the guest/host values differ.
6583 if (cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS) ||
6584 vmx->spec_ctrl != hostval)
6585 native_wrmsrl(MSR_IA32_SPEC_CTRL, hostval);
6590 static void vmx_vcpu_run(struct kvm_vcpu *vcpu)
6592 struct vcpu_vmx *vmx = to_vmx(vcpu);
6593 unsigned long cr3, cr4;
6595 /* Record the guest's net vcpu time for enforced NMI injections. */
6596 if (unlikely(!enable_vnmi &&
6597 vmx->loaded_vmcs->soft_vnmi_blocked))
6598 vmx->loaded_vmcs->entry_time = ktime_get();
6600 /* Don't enter VMX if guest state is invalid, let the exit handler
6601 start emulation until we arrive back to a valid state */
6602 if (vmx->emulation_required)
6605 if (vmx->ple_window_dirty) {
6606 vmx->ple_window_dirty = false;
6607 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6611 * We did this in prepare_switch_to_guest, because it needs to
6612 * be within srcu_read_lock.
6614 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6616 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
6617 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6618 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
6619 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6621 cr3 = __get_current_cr3_fast();
6622 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6623 vmcs_writel(HOST_CR3, cr3);
6624 vmx->loaded_vmcs->host_state.cr3 = cr3;
6627 cr4 = cr4_read_shadow();
6628 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6629 vmcs_writel(HOST_CR4, cr4);
6630 vmx->loaded_vmcs->host_state.cr4 = cr4;
6633 /* When single-stepping over STI and MOV SS, we must clear the
6634 * corresponding interruptibility bits in the guest state. Otherwise
6635 * vmentry fails as it then expects bit 14 (BS) in pending debug
6636 * exceptions being set, but that's not correct for the guest debugging
6638 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6639 vmx_set_interrupt_shadow(vcpu, 0);
6641 kvm_load_guest_xcr0(vcpu);
6643 pt_guest_enter(vmx);
6645 atomic_switch_perf_msrs(vmx);
6647 if (enable_preemption_timer)
6648 vmx_update_hv_timer(vcpu);
6650 if (lapic_in_kernel(vcpu) &&
6651 vcpu->arch.apic->lapic_timer.timer_advance_ns)
6652 kvm_wait_lapic_expire(vcpu);
6655 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6656 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6657 * is no need to worry about the conditional branch over the wrmsr
6658 * being speculatively taken.
6660 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6662 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6663 if (static_branch_unlikely(&vmx_l1d_should_flush))
6664 vmx_l1d_flush(vcpu);
6665 else if (static_branch_unlikely(&mds_user_clear))
6666 mds_clear_cpu_buffers();
6667 else if (static_branch_unlikely(&mmio_stale_data_clear) &&
6668 kvm_arch_has_assigned_device(vcpu->kvm))
6669 mds_clear_cpu_buffers();
6671 vmx_disable_fb_clear(vmx);
6673 if (vcpu->arch.cr2 != read_cr2())
6674 write_cr2(vcpu->arch.cr2);
6676 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6677 __vmx_vcpu_run_flags(vmx));
6679 vcpu->arch.cr2 = read_cr2();
6681 vmx_enable_fb_clear(vmx);
6683 /* All fields are clean at this point */
6684 if (static_branch_unlikely(&enable_evmcs))
6685 current_evmcs->hv_clean_fields |=
6686 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6688 if (static_branch_unlikely(&enable_evmcs))
6689 current_evmcs->hv_vp_id = vcpu->arch.hyperv.vp_index;
6691 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6692 if (vmx->host_debugctlmsr)
6693 update_debugctlmsr(vmx->host_debugctlmsr);
6695 #ifndef CONFIG_X86_64
6697 * The sysexit path does not restore ds/es, so we must set them to
6698 * a reasonable value ourselves.
6700 * We can't defer this to vmx_prepare_switch_to_host() since that
6701 * function may be executed in interrupt context, which saves and
6702 * restore segments around it, nullifying its effect.
6704 loadsegment(ds, __USER_DS);
6705 loadsegment(es, __USER_DS);
6708 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
6709 | (1 << VCPU_EXREG_RFLAGS)
6710 | (1 << VCPU_EXREG_PDPTR)
6711 | (1 << VCPU_EXREG_SEGMENTS)
6712 | (1 << VCPU_EXREG_CR3));
6713 vcpu->arch.regs_dirty = 0;
6717 kvm_put_guest_xcr0(vcpu);
6719 vmx->nested.nested_run_pending = 0;
6720 vmx->idt_vectoring_info = 0;
6722 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
6723 if ((u16)vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY)
6724 kvm_machine_check();
6726 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6729 vmx->loaded_vmcs->launched = 1;
6730 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6732 vmx_recover_nmi_blocking(vmx);
6733 vmx_complete_interrupts(vmx);
6736 static struct kvm *vmx_vm_alloc(void)
6738 struct kvm_vmx *kvm_vmx = __vmalloc(sizeof(struct kvm_vmx),
6739 GFP_KERNEL_ACCOUNT | __GFP_ZERO,
6745 return &kvm_vmx->kvm;
6748 static void vmx_vm_free(struct kvm *kvm)
6750 kfree(kvm->arch.hyperv.hv_pa_pg);
6751 vfree(to_kvm_vmx(kvm));
6754 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6756 struct vcpu_vmx *vmx = to_vmx(vcpu);
6759 vmx_destroy_pml_buffer(vmx);
6760 free_vpid(vmx->vpid);
6761 nested_vmx_free_vcpu(vcpu);
6762 free_loaded_vmcs(vmx->loaded_vmcs);
6763 kfree(vmx->guest_msrs);
6764 kvm_vcpu_uninit(vcpu);
6765 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.user_fpu);
6766 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6767 kmem_cache_free(kvm_vcpu_cache, vmx);
6770 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
6773 struct vcpu_vmx *vmx;
6774 unsigned long *msr_bitmap;
6777 BUILD_BUG_ON_MSG(offsetof(struct vcpu_vmx, vcpu) != 0,
6778 "struct kvm_vcpu must be at offset 0 for arch usercopy region");
6780 vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
6782 return ERR_PTR(-ENOMEM);
6784 vmx->vcpu.arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
6785 GFP_KERNEL_ACCOUNT);
6786 if (!vmx->vcpu.arch.user_fpu) {
6787 printk(KERN_ERR "kvm: failed to allocate kvm userspace's fpu\n");
6789 goto free_partial_vcpu;
6792 vmx->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
6793 GFP_KERNEL_ACCOUNT);
6794 if (!vmx->vcpu.arch.guest_fpu) {
6795 printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
6800 vmx->vpid = allocate_vpid();
6802 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
6809 * If PML is turned on, failure on enabling PML just results in failure
6810 * of creating the vcpu, therefore we can simplify PML logic (by
6811 * avoiding dealing with cases, such as enabling PML partially on vcpus
6812 * for the guest, etc.
6815 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6820 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
6821 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
6824 if (!vmx->guest_msrs)
6827 err = alloc_loaded_vmcs(&vmx->vmcs01);
6831 msr_bitmap = vmx->vmcs01.msr_bitmap;
6832 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6833 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6834 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6835 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6836 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6837 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6838 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6839 if (kvm_cstate_in_guest(kvm)) {
6840 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C1_RES, MSR_TYPE_R);
6841 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6842 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6843 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6845 vmx->msr_bitmap_mode = 0;
6847 vmx->loaded_vmcs = &vmx->vmcs01;
6849 vmx_vcpu_load(&vmx->vcpu, cpu);
6850 vmx->vcpu.cpu = cpu;
6851 vmx_vcpu_setup(vmx);
6852 vmx_vcpu_put(&vmx->vcpu);
6854 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
6855 err = alloc_apic_access_page(kvm);
6860 if (enable_ept && !enable_unrestricted_guest) {
6861 err = init_rmode_identity_map(kvm);
6867 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
6868 vmx_capability.ept);
6870 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6872 vmx->nested.posted_intr_nv = -1;
6873 vmx->nested.current_vmptr = -1ull;
6875 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
6878 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6879 * or POSTED_INTR_WAKEUP_VECTOR.
6881 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6882 vmx->pi_desc.sn = 1;
6884 vmx->ept_pointer = INVALID_PAGE;
6889 free_loaded_vmcs(vmx->loaded_vmcs);
6891 kfree(vmx->guest_msrs);
6893 vmx_destroy_pml_buffer(vmx);
6895 kvm_vcpu_uninit(&vmx->vcpu);
6897 free_vpid(vmx->vpid);
6898 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6900 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.user_fpu);
6902 kmem_cache_free(kvm_vcpu_cache, vmx);
6903 return ERR_PTR(err);
6906 #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"
6907 #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"
6909 static int vmx_vm_init(struct kvm *kvm)
6911 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
6914 kvm->arch.pause_in_guest = true;
6916 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6917 switch (l1tf_mitigation) {
6918 case L1TF_MITIGATION_OFF:
6919 case L1TF_MITIGATION_FLUSH_NOWARN:
6920 /* 'I explicitly don't care' is set */
6922 case L1TF_MITIGATION_FLUSH:
6923 case L1TF_MITIGATION_FLUSH_NOSMT:
6924 case L1TF_MITIGATION_FULL:
6926 * Warn upon starting the first VM in a potentially
6927 * insecure environment.
6929 if (sched_smt_active())
6930 pr_warn_once(L1TF_MSG_SMT);
6931 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6932 pr_warn_once(L1TF_MSG_L1D);
6934 case L1TF_MITIGATION_FULL_FORCE:
6935 /* Flush is enforced */
6942 static int __init vmx_check_processor_compat(void)
6944 struct vmcs_config vmcs_conf;
6945 struct vmx_capability vmx_cap;
6947 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
6950 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
6951 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6952 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6953 smp_processor_id());
6959 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6964 /* For VT-d and EPT combination
6965 * 1. MMIO: always map as UC
6967 * a. VT-d without snooping control feature: can't guarantee the
6968 * result, try to trust guest.
6969 * b. VT-d with snooping control feature: snooping control feature of
6970 * VT-d engine can guarantee the cache correctness. Just set it
6971 * to WB to keep consistent with host. So the same as item 3.
6972 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
6973 * consistent with host MTRR
6976 cache = MTRR_TYPE_UNCACHABLE;
6980 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
6981 ipat = VMX_EPT_IPAT_BIT;
6982 cache = MTRR_TYPE_WRBACK;
6986 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
6987 ipat = VMX_EPT_IPAT_BIT;
6988 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
6989 cache = MTRR_TYPE_WRBACK;
6991 cache = MTRR_TYPE_UNCACHABLE;
6995 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
6998 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7001 static int vmx_get_lpage_level(void)
7003 if (enable_ept && !cpu_has_vmx_ept_1g_page())
7004 return PT_DIRECTORY_LEVEL;
7006 /* For shadow and EPT supported 1GB page */
7007 return PT_PDPE_LEVEL;
7010 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
7013 * These bits in the secondary execution controls field
7014 * are dynamic, the others are mostly based on the hypervisor
7015 * architecture and the guest's CPUID. Do not touch the
7019 SECONDARY_EXEC_SHADOW_VMCS |
7020 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7021 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7022 SECONDARY_EXEC_DESC;
7024 u32 new_ctl = vmx->secondary_exec_control;
7025 u32 cur_ctl = secondary_exec_controls_get(vmx);
7027 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7031 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7032 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7034 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7036 struct vcpu_vmx *vmx = to_vmx(vcpu);
7037 struct kvm_cpuid_entry2 *entry;
7039 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7040 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7042 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7043 if (entry && (entry->_reg & (_cpuid_mask))) \
7044 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7047 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7048 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
7049 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
7050 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
7051 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
7052 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
7053 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
7054 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
7055 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
7056 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
7057 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
7058 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
7059 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
7060 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
7061 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
7063 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7064 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
7065 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
7066 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
7067 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
7068 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
7070 #undef cr4_fixed1_update
7073 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7075 struct vcpu_vmx *vmx = to_vmx(vcpu);
7077 if (kvm_mpx_supported()) {
7078 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7081 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7082 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7084 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7085 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7090 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7092 struct vcpu_vmx *vmx = to_vmx(vcpu);
7093 struct kvm_cpuid_entry2 *best = NULL;
7096 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7097 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7100 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7101 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7102 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7103 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7106 /* Get the number of configurable Address Ranges for filtering */
7107 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7108 PT_CAP_num_address_ranges);
7110 /* Initialize and clear the no dependency bits */
7111 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7112 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7115 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7116 * will inject an #GP
7118 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7119 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7122 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7123 * PSBFreq can be set
7125 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7126 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7127 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7130 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7131 * MTCFreq can be set
7133 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7134 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7135 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7137 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7138 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7139 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7142 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7143 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7144 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7146 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7147 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7148 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7150 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
7151 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7152 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7154 /* unmask address range configure area */
7155 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7156 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7159 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
7161 struct vcpu_vmx *vmx = to_vmx(vcpu);
7163 if (cpu_has_secondary_exec_ctrls()) {
7164 vmx_compute_secondary_exec_control(vmx);
7165 vmcs_set_secondary_exec_control(vmx);
7168 if (nested_vmx_allowed(vcpu))
7169 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7170 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7172 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7173 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7175 if (nested_vmx_allowed(vcpu)) {
7176 nested_vmx_cr_fixed1_bits_update(vcpu);
7177 nested_vmx_entry_exit_ctls_update(vcpu);
7180 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7181 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7182 update_intel_pt_cfg(vcpu);
7185 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
7187 if (func == 1 && nested)
7188 entry->ecx |= bit(X86_FEATURE_VMX);
7191 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7193 to_vmx(vcpu)->req_immediate_exit = true;
7196 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7197 struct x86_instruction_info *info)
7199 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7200 unsigned short port;
7204 if (info->intercept == x86_intercept_in ||
7205 info->intercept == x86_intercept_ins) {
7206 port = info->src_val;
7207 size = info->dst_bytes;
7209 port = info->dst_val;
7210 size = info->src_bytes;
7214 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7215 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7218 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7220 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7221 intercept = nested_cpu_has(vmcs12,
7222 CPU_BASED_UNCOND_IO_EXITING);
7224 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7226 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7227 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7230 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7231 struct x86_instruction_info *info,
7232 enum x86_intercept_stage stage)
7234 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7235 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7237 switch (info->intercept) {
7239 * RDPID causes #UD if disabled through secondary execution controls.
7240 * Because it is marked as EmulateOnUD, we need to intercept it here.
7242 case x86_intercept_rdtscp:
7243 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
7244 ctxt->exception.vector = UD_VECTOR;
7245 ctxt->exception.error_code_valid = false;
7246 return X86EMUL_PROPAGATE_FAULT;
7250 case x86_intercept_in:
7251 case x86_intercept_ins:
7252 case x86_intercept_out:
7253 case x86_intercept_outs:
7254 return vmx_check_intercept_io(vcpu, info);
7256 case x86_intercept_lgdt:
7257 case x86_intercept_lidt:
7258 case x86_intercept_lldt:
7259 case x86_intercept_ltr:
7260 case x86_intercept_sgdt:
7261 case x86_intercept_sidt:
7262 case x86_intercept_sldt:
7263 case x86_intercept_str:
7264 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7265 return X86EMUL_CONTINUE;
7267 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7270 case x86_intercept_pause:
7272 * PAUSE is a single-byte NOP with a REPE prefix, i.e. collides
7273 * with vanilla NOPs in the emulator. Apply the interception
7274 * check only to actual PAUSE instructions. Don't check
7275 * PAUSE-loop-exiting, software can't expect a given PAUSE to
7276 * exit, i.e. KVM is within its rights to allow L2 to execute
7279 if ((info->rep_prefix != REPE_PREFIX) ||
7280 !nested_cpu_has2(vmcs12, CPU_BASED_PAUSE_EXITING))
7281 return X86EMUL_CONTINUE;
7285 /* TODO: check more intercepts... */
7290 return X86EMUL_UNHANDLEABLE;
7293 #ifdef CONFIG_X86_64
7294 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7295 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7296 u64 divisor, u64 *result)
7298 u64 low = a << shift, high = a >> (64 - shift);
7300 /* To avoid the overflow on divq */
7301 if (high >= divisor)
7304 /* Low hold the result, high hold rem which is discarded */
7305 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7306 "rm" (divisor), "0" (low), "1" (high));
7312 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7315 struct vcpu_vmx *vmx;
7316 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7317 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7319 if (kvm_mwait_in_guest(vcpu->kvm) ||
7320 kvm_can_post_timer_interrupt(vcpu))
7325 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7326 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7327 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7328 ktimer->timer_advance_ns);
7330 if (delta_tsc > lapic_timer_advance_cycles)
7331 delta_tsc -= lapic_timer_advance_cycles;
7335 /* Convert to host delta tsc if tsc scaling is enabled */
7336 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7337 delta_tsc && u64_shl_div_u64(delta_tsc,
7338 kvm_tsc_scaling_ratio_frac_bits,
7339 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7343 * If the delta tsc can't fit in the 32 bit after the multi shift,
7344 * we can't use the preemption timer.
7345 * It's possible that it fits on later vmentries, but checking
7346 * on every vmentry is costly so we just use an hrtimer.
7348 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7351 vmx->hv_deadline_tsc = tscl + delta_tsc;
7352 *expired = !delta_tsc;
7356 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7358 to_vmx(vcpu)->hv_deadline_tsc = -1;
7362 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7364 if (!kvm_pause_in_guest(vcpu->kvm))
7365 shrink_ple_window(vcpu);
7368 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7369 struct kvm_memory_slot *slot)
7371 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7372 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7375 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7376 struct kvm_memory_slot *slot)
7378 kvm_mmu_slot_set_dirty(kvm, slot);
7381 static void vmx_flush_log_dirty(struct kvm *kvm)
7383 kvm_flush_pml_buffers(kvm);
7386 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu, gpa_t gpa)
7388 struct vmcs12 *vmcs12;
7389 struct vcpu_vmx *vmx = to_vmx(vcpu);
7392 if (is_guest_mode(vcpu)) {
7393 WARN_ON_ONCE(vmx->nested.pml_full);
7396 * Check if PML is enabled for the nested guest.
7397 * Whether eptp bit 6 is set is already checked
7398 * as part of A/D emulation.
7400 vmcs12 = get_vmcs12(vcpu);
7401 if (!nested_cpu_has_pml(vmcs12))
7404 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
7405 vmx->nested.pml_full = true;
7410 dst = vmcs12->pml_address + sizeof(u64) * vmcs12->guest_pml_index;
7412 if (kvm_write_guest_page(vcpu->kvm, gpa_to_gfn(dst), &gpa,
7413 offset_in_page(dst), sizeof(gpa)))
7416 vmcs12->guest_pml_index--;
7422 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7423 struct kvm_memory_slot *memslot,
7424 gfn_t offset, unsigned long mask)
7426 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7429 static void __pi_post_block(struct kvm_vcpu *vcpu)
7431 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7432 struct pi_desc old, new;
7436 old.control = new.control = pi_desc->control;
7437 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
7438 "Wakeup handler not enabled while the VCPU is blocked\n");
7440 dest = cpu_physical_id(vcpu->cpu);
7442 if (x2apic_enabled())
7445 new.ndst = (dest << 8) & 0xFF00;
7447 /* set 'NV' to 'notification vector' */
7448 new.nv = POSTED_INTR_VECTOR;
7449 } while (cmpxchg64(&pi_desc->control, old.control,
7450 new.control) != old.control);
7452 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
7453 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7454 list_del(&vcpu->blocked_vcpu_list);
7455 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7456 vcpu->pre_pcpu = -1;
7461 * This routine does the following things for vCPU which is going
7462 * to be blocked if VT-d PI is enabled.
7463 * - Store the vCPU to the wakeup list, so when interrupts happen
7464 * we can find the right vCPU to wake up.
7465 * - Change the Posted-interrupt descriptor as below:
7466 * 'NDST' <-- vcpu->pre_pcpu
7467 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
7468 * - If 'ON' is set during this process, which means at least one
7469 * interrupt is posted for this vCPU, we cannot block it, in
7470 * this case, return 1, otherwise, return 0.
7473 static int pi_pre_block(struct kvm_vcpu *vcpu)
7476 struct pi_desc old, new;
7477 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7479 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
7480 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7481 !kvm_vcpu_apicv_active(vcpu))
7484 WARN_ON(irqs_disabled());
7485 local_irq_disable();
7486 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
7487 vcpu->pre_pcpu = vcpu->cpu;
7488 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7489 list_add_tail(&vcpu->blocked_vcpu_list,
7490 &per_cpu(blocked_vcpu_on_cpu,
7492 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7496 old.control = new.control = pi_desc->control;
7498 WARN((pi_desc->sn == 1),
7499 "Warning: SN field of posted-interrupts "
7500 "is set before blocking\n");
7503 * Since vCPU can be preempted during this process,
7504 * vcpu->cpu could be different with pre_pcpu, we
7505 * need to set pre_pcpu as the destination of wakeup
7506 * notification event, then we can find the right vCPU
7507 * to wakeup in wakeup handler if interrupts happen
7508 * when the vCPU is in blocked state.
7510 dest = cpu_physical_id(vcpu->pre_pcpu);
7512 if (x2apic_enabled())
7515 new.ndst = (dest << 8) & 0xFF00;
7517 /* set 'NV' to 'wakeup vector' */
7518 new.nv = POSTED_INTR_WAKEUP_VECTOR;
7519 } while (cmpxchg64(&pi_desc->control, old.control,
7520 new.control) != old.control);
7522 /* We should not block the vCPU if an interrupt is posted for it. */
7523 if (pi_test_on(pi_desc) == 1)
7524 __pi_post_block(vcpu);
7527 return (vcpu->pre_pcpu == -1);
7530 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7532 if (pi_pre_block(vcpu))
7535 if (kvm_lapic_hv_timer_in_use(vcpu))
7536 kvm_lapic_switch_to_sw_timer(vcpu);
7541 static void pi_post_block(struct kvm_vcpu *vcpu)
7543 if (vcpu->pre_pcpu == -1)
7546 WARN_ON(irqs_disabled());
7547 local_irq_disable();
7548 __pi_post_block(vcpu);
7552 static void vmx_post_block(struct kvm_vcpu *vcpu)
7554 if (kvm_x86_ops->set_hv_timer)
7555 kvm_lapic_switch_to_hv_timer(vcpu);
7557 pi_post_block(vcpu);
7561 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
7564 * @host_irq: host irq of the interrupt
7565 * @guest_irq: gsi of the interrupt
7566 * @set: set or unset PI
7567 * returns 0 on success, < 0 on failure
7569 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7570 uint32_t guest_irq, bool set)
7572 struct kvm_kernel_irq_routing_entry *e;
7573 struct kvm_irq_routing_table *irq_rt;
7574 struct kvm_lapic_irq irq;
7575 struct kvm_vcpu *vcpu;
7576 struct vcpu_data vcpu_info;
7579 if (!kvm_arch_has_assigned_device(kvm) ||
7580 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7581 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7584 idx = srcu_read_lock(&kvm->irq_srcu);
7585 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7586 if (guest_irq >= irq_rt->nr_rt_entries ||
7587 hlist_empty(&irq_rt->map[guest_irq])) {
7588 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7589 guest_irq, irq_rt->nr_rt_entries);
7593 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7594 if (e->type != KVM_IRQ_ROUTING_MSI)
7597 * VT-d PI cannot support posting multicast/broadcast
7598 * interrupts to a vCPU, we still use interrupt remapping
7599 * for these kind of interrupts.
7601 * For lowest-priority interrupts, we only support
7602 * those with single CPU as the destination, e.g. user
7603 * configures the interrupts via /proc/irq or uses
7604 * irqbalance to make the interrupts single-CPU.
7606 * We will support full lowest-priority interrupt later.
7608 * In addition, we can only inject generic interrupts using
7609 * the PI mechanism, refuse to route others through it.
7612 kvm_set_msi_irq(kvm, e, &irq);
7613 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
7614 !kvm_irq_is_postable(&irq)) {
7616 * Make sure the IRTE is in remapped mode if
7617 * we don't handle it in posted mode.
7619 ret = irq_set_vcpu_affinity(host_irq, NULL);
7622 "failed to back to remapped mode, irq: %u\n",
7630 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7631 vcpu_info.vector = irq.vector;
7633 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7634 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7637 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7639 ret = irq_set_vcpu_affinity(host_irq, NULL);
7642 printk(KERN_INFO "%s: failed to update PI IRTE\n",
7650 srcu_read_unlock(&kvm->irq_srcu, idx);
7654 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7656 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7657 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7658 FEATURE_CONTROL_LMCE;
7660 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7661 ~FEATURE_CONTROL_LMCE;
7664 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
7666 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7667 if (to_vmx(vcpu)->nested.nested_run_pending)
7672 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7674 struct vcpu_vmx *vmx = to_vmx(vcpu);
7676 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7677 if (vmx->nested.smm.guest_mode)
7678 nested_vmx_vmexit(vcpu, -1, 0, 0);
7680 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7681 vmx->nested.vmxon = false;
7682 vmx_clear_hlt(vcpu);
7686 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7688 struct vcpu_vmx *vmx = to_vmx(vcpu);
7691 if (vmx->nested.smm.vmxon) {
7692 vmx->nested.vmxon = true;
7693 vmx->nested.smm.vmxon = false;
7696 if (vmx->nested.smm.guest_mode) {
7697 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7701 vmx->nested.smm.guest_mode = false;
7706 static int enable_smi_window(struct kvm_vcpu *vcpu)
7711 static bool vmx_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7716 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7718 return to_vmx(vcpu)->nested.vmxon;
7721 static __init int hardware_setup(void)
7723 unsigned long host_bndcfgs;
7727 rdmsrl_safe(MSR_EFER, &host_efer);
7730 host_idt_base = dt.address;
7732 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7733 kvm_define_shared_msr(i, vmx_msr_index[i]);
7735 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7738 if (boot_cpu_has(X86_FEATURE_NX))
7739 kvm_enable_efer_bits(EFER_NX);
7741 if (boot_cpu_has(X86_FEATURE_MPX)) {
7742 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7743 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7746 if (boot_cpu_has(X86_FEATURE_XSAVES))
7747 rdmsrl(MSR_IA32_XSS, host_xss);
7749 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7750 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7753 if (!cpu_has_vmx_ept() ||
7754 !cpu_has_vmx_ept_4levels() ||
7755 !cpu_has_vmx_ept_mt_wb() ||
7756 !cpu_has_vmx_invept_global())
7759 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7760 enable_ept_ad_bits = 0;
7762 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7763 enable_unrestricted_guest = 0;
7765 if (!cpu_has_vmx_flexpriority())
7766 flexpriority_enabled = 0;
7768 if (!cpu_has_virtual_nmis())
7772 * set_apic_access_page_addr() is used to reload apic access
7773 * page upon invalidation. No need to do anything if not
7774 * using the APIC_ACCESS_ADDR VMCS field.
7776 if (!flexpriority_enabled)
7777 kvm_x86_ops->set_apic_access_page_addr = NULL;
7779 if (!cpu_has_vmx_tpr_shadow())
7780 kvm_x86_ops->update_cr8_intercept = NULL;
7782 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7783 kvm_disable_largepages();
7785 #if IS_ENABLED(CONFIG_HYPERV)
7786 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7788 kvm_x86_ops->tlb_remote_flush = hv_remote_flush_tlb;
7789 kvm_x86_ops->tlb_remote_flush_with_range =
7790 hv_remote_flush_tlb_with_range;
7794 if (!cpu_has_vmx_ple()) {
7797 ple_window_grow = 0;
7799 ple_window_shrink = 0;
7802 if (!cpu_has_vmx_apicv()) {
7804 kvm_x86_ops->sync_pir_to_irr = NULL;
7807 if (cpu_has_vmx_tsc_scaling()) {
7808 kvm_has_tsc_control = true;
7809 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7810 kvm_tsc_scaling_ratio_frac_bits = 48;
7813 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7821 * Only enable PML when hardware supports PML feature, and both EPT
7822 * and EPT A/D bit features are enabled -- PML depends on them to work.
7824 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7828 kvm_x86_ops->slot_enable_log_dirty = NULL;
7829 kvm_x86_ops->slot_disable_log_dirty = NULL;
7830 kvm_x86_ops->flush_log_dirty = NULL;
7831 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7834 if (!cpu_has_vmx_preemption_timer())
7835 enable_preemption_timer = false;
7837 if (enable_preemption_timer) {
7838 u64 use_timer_freq = 5000ULL * 1000 * 1000;
7841 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7842 cpu_preemption_timer_multi =
7843 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7846 use_timer_freq = (u64)tsc_khz * 1000;
7847 use_timer_freq >>= cpu_preemption_timer_multi;
7850 * KVM "disables" the preemption timer by setting it to its max
7851 * value. Don't use the timer if it might cause spurious exits
7852 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
7854 if (use_timer_freq > 0xffffffffu / 10)
7855 enable_preemption_timer = false;
7858 if (!enable_preemption_timer) {
7859 kvm_x86_ops->set_hv_timer = NULL;
7860 kvm_x86_ops->cancel_hv_timer = NULL;
7861 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7864 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7866 kvm_mce_cap_supported |= MCG_LMCE_P;
7868 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7870 if (!enable_ept || !cpu_has_vmx_intel_pt())
7871 pt_mode = PT_MODE_SYSTEM;
7874 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7875 vmx_capability.ept);
7877 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7882 r = alloc_kvm_area();
7884 nested_vmx_hardware_unsetup();
7888 static __exit void hardware_unsetup(void)
7891 nested_vmx_hardware_unsetup();
7896 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
7897 .cpu_has_kvm_support = cpu_has_kvm_support,
7898 .disabled_by_bios = vmx_disabled_by_bios,
7899 .hardware_setup = hardware_setup,
7900 .hardware_unsetup = hardware_unsetup,
7901 .check_processor_compatibility = vmx_check_processor_compat,
7902 .hardware_enable = hardware_enable,
7903 .hardware_disable = hardware_disable,
7904 .cpu_has_accelerated_tpr = report_flexpriority,
7905 .has_emulated_msr = vmx_has_emulated_msr,
7907 .vm_init = vmx_vm_init,
7908 .vm_alloc = vmx_vm_alloc,
7909 .vm_free = vmx_vm_free,
7911 .vcpu_create = vmx_create_vcpu,
7912 .vcpu_free = vmx_free_vcpu,
7913 .vcpu_reset = vmx_vcpu_reset,
7915 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7916 .vcpu_load = vmx_vcpu_load,
7917 .vcpu_put = vmx_vcpu_put,
7919 .update_bp_intercept = update_exception_bitmap,
7920 .get_msr_feature = vmx_get_msr_feature,
7921 .get_msr = vmx_get_msr,
7922 .set_msr = vmx_set_msr,
7923 .get_segment_base = vmx_get_segment_base,
7924 .get_segment = vmx_get_segment,
7925 .set_segment = vmx_set_segment,
7926 .get_cpl = vmx_get_cpl,
7927 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7928 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
7929 .decache_cr3 = vmx_decache_cr3,
7930 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
7931 .set_cr0 = vmx_set_cr0,
7932 .set_cr3 = vmx_set_cr3,
7933 .set_cr4 = vmx_set_cr4,
7934 .set_efer = vmx_set_efer,
7935 .get_idt = vmx_get_idt,
7936 .set_idt = vmx_set_idt,
7937 .get_gdt = vmx_get_gdt,
7938 .set_gdt = vmx_set_gdt,
7939 .get_dr6 = vmx_get_dr6,
7940 .set_dr6 = vmx_set_dr6,
7941 .set_dr7 = vmx_set_dr7,
7942 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7943 .cache_reg = vmx_cache_reg,
7944 .get_rflags = vmx_get_rflags,
7945 .set_rflags = vmx_set_rflags,
7947 .tlb_flush = vmx_flush_tlb,
7948 .tlb_flush_gva = vmx_flush_tlb_gva,
7950 .run = vmx_vcpu_run,
7951 .handle_exit = vmx_handle_exit,
7952 .skip_emulated_instruction = skip_emulated_instruction,
7953 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7954 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7955 .patch_hypercall = vmx_patch_hypercall,
7956 .set_irq = vmx_inject_irq,
7957 .set_nmi = vmx_inject_nmi,
7958 .queue_exception = vmx_queue_exception,
7959 .cancel_injection = vmx_cancel_injection,
7960 .interrupt_allowed = vmx_interrupt_allowed,
7961 .nmi_allowed = vmx_nmi_allowed,
7962 .get_nmi_mask = vmx_get_nmi_mask,
7963 .set_nmi_mask = vmx_set_nmi_mask,
7964 .enable_nmi_window = enable_nmi_window,
7965 .enable_irq_window = enable_irq_window,
7966 .update_cr8_intercept = update_cr8_intercept,
7967 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7968 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7969 .get_enable_apicv = vmx_get_enable_apicv,
7970 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7971 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7972 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7973 .hwapic_irr_update = vmx_hwapic_irr_update,
7974 .hwapic_isr_update = vmx_hwapic_isr_update,
7975 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7976 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7977 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7978 .dy_apicv_has_pending_interrupt = vmx_dy_apicv_has_pending_interrupt,
7980 .set_tss_addr = vmx_set_tss_addr,
7981 .set_identity_map_addr = vmx_set_identity_map_addr,
7982 .get_tdp_level = get_ept_level,
7983 .get_mt_mask = vmx_get_mt_mask,
7985 .get_exit_info = vmx_get_exit_info,
7987 .get_lpage_level = vmx_get_lpage_level,
7989 .cpuid_update = vmx_cpuid_update,
7991 .rdtscp_supported = vmx_rdtscp_supported,
7992 .invpcid_supported = vmx_invpcid_supported,
7994 .set_supported_cpuid = vmx_set_supported_cpuid,
7996 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7998 .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
7999 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
8001 .set_tdp_cr3 = vmx_set_cr3,
8003 .check_intercept = vmx_check_intercept,
8004 .handle_exit_irqoff = vmx_handle_exit_irqoff,
8005 .mpx_supported = vmx_mpx_supported,
8006 .xsaves_supported = vmx_xsaves_supported,
8007 .umip_emulated = vmx_umip_emulated,
8008 .pt_supported = vmx_pt_supported,
8009 .pku_supported = vmx_pku_supported,
8011 .request_immediate_exit = vmx_request_immediate_exit,
8013 .sched_in = vmx_sched_in,
8015 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
8016 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
8017 .flush_log_dirty = vmx_flush_log_dirty,
8018 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
8019 .write_log_dirty = vmx_write_pml_buffer,
8021 .pre_block = vmx_pre_block,
8022 .post_block = vmx_post_block,
8024 .pmu_ops = &intel_pmu_ops,
8026 .update_pi_irte = vmx_update_pi_irte,
8028 #ifdef CONFIG_X86_64
8029 .set_hv_timer = vmx_set_hv_timer,
8030 .cancel_hv_timer = vmx_cancel_hv_timer,
8033 .setup_mce = vmx_setup_mce,
8035 .smi_allowed = vmx_smi_allowed,
8036 .pre_enter_smm = vmx_pre_enter_smm,
8037 .pre_leave_smm = vmx_pre_leave_smm,
8038 .enable_smi_window = enable_smi_window,
8040 .check_nested_events = NULL,
8041 .get_nested_state = NULL,
8042 .set_nested_state = NULL,
8043 .get_vmcs12_pages = NULL,
8044 .nested_enable_evmcs = NULL,
8045 .nested_get_evmcs_version = NULL,
8046 .need_emulation_on_page_fault = vmx_need_emulation_on_page_fault,
8047 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
8050 static void vmx_cleanup_l1d_flush(void)
8052 if (vmx_l1d_flush_pages) {
8053 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8054 vmx_l1d_flush_pages = NULL;
8056 /* Restore state so sysfs ignores VMX */
8057 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8060 static void vmx_exit(void)
8062 #ifdef CONFIG_KEXEC_CORE
8063 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8069 #if IS_ENABLED(CONFIG_HYPERV)
8070 if (static_branch_unlikely(&enable_evmcs)) {
8072 struct hv_vp_assist_page *vp_ap;
8074 * Reset everything to support using non-enlightened VMCS
8075 * access later (e.g. when we reload the module with
8076 * enlightened_vmcs=0)
8078 for_each_online_cpu(cpu) {
8079 vp_ap = hv_get_vp_assist_page(cpu);
8084 vp_ap->nested_control.features.directhypercall = 0;
8085 vp_ap->current_nested_vmcs = 0;
8086 vp_ap->enlighten_vmentry = 0;
8089 static_branch_disable(&enable_evmcs);
8092 vmx_cleanup_l1d_flush();
8094 module_exit(vmx_exit);
8096 static int __init vmx_init(void)
8100 #if IS_ENABLED(CONFIG_HYPERV)
8102 * Enlightened VMCS usage should be recommended and the host needs
8103 * to support eVMCS v1 or above. We can also disable eVMCS support
8104 * with module parameter.
8106 if (enlightened_vmcs &&
8107 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8108 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8109 KVM_EVMCS_VERSION) {
8112 /* Check that we have assist pages on all online CPUs */
8113 for_each_online_cpu(cpu) {
8114 if (!hv_get_vp_assist_page(cpu)) {
8115 enlightened_vmcs = false;
8120 if (enlightened_vmcs) {
8121 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8122 static_branch_enable(&enable_evmcs);
8125 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8126 vmx_x86_ops.enable_direct_tlbflush
8127 = hv_enable_direct_tlbflush;
8130 enlightened_vmcs = false;
8134 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
8135 __alignof__(struct vcpu_vmx), THIS_MODULE);
8140 * Must be called after kvm_init() so enable_ept is properly set
8141 * up. Hand the parameter mitigation value in which was stored in
8142 * the pre module init parser. If no parameter was given, it will
8143 * contain 'auto' which will be turned into the default 'cond'
8146 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8152 vmx_setup_fb_clear_ctrl();
8154 for_each_possible_cpu(cpu) {
8155 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8157 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
8158 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
8161 #ifdef CONFIG_KEXEC_CORE
8162 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8163 crash_vmclear_local_loaded_vmcss);
8165 vmx_check_vmcs12_offsets();
8169 module_init(vmx_init);