1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <linux/highmem.h>
17 #include <linux/hrtimer.h>
18 #include <linux/kernel.h>
19 #include <linux/kvm_host.h>
20 #include <linux/module.h>
21 #include <linux/moduleparam.h>
22 #include <linux/mod_devicetable.h>
24 #include <linux/objtool.h>
25 #include <linux/sched.h>
26 #include <linux/sched/smt.h>
27 #include <linux/slab.h>
28 #include <linux/tboot.h>
29 #include <linux/trace_events.h>
30 #include <linux/entry-kvm.h>
35 #include <asm/cpu_device_id.h>
36 #include <asm/debugreg.h>
38 #include <asm/fpu/internal.h>
40 #include <asm/irq_remapping.h>
41 #include <asm/kexec.h>
42 #include <asm/perf_event.h>
43 #include <asm/mmu_context.h>
44 #include <asm/mshyperv.h>
45 #include <asm/mwait.h>
46 #include <asm/spec-ctrl.h>
47 #include <asm/virtext.h>
50 #include "capabilities.h"
55 #include "kvm_cache_regs.h"
67 MODULE_AUTHOR("Qumranet");
68 MODULE_LICENSE("GPL");
71 static const struct x86_cpu_id vmx_cpu_id[] = {
72 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
75 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
78 bool __read_mostly enable_vpid = 1;
79 module_param_named(vpid, enable_vpid, bool, 0444);
81 static bool __read_mostly enable_vnmi = 1;
82 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
84 bool __read_mostly flexpriority_enabled = 1;
85 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
87 bool __read_mostly enable_ept = 1;
88 module_param_named(ept, enable_ept, bool, S_IRUGO);
90 bool __read_mostly enable_unrestricted_guest = 1;
91 module_param_named(unrestricted_guest,
92 enable_unrestricted_guest, bool, S_IRUGO);
94 bool __read_mostly enable_ept_ad_bits = 1;
95 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
97 static bool __read_mostly emulate_invalid_guest_state = true;
98 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
100 static bool __read_mostly fasteoi = 1;
101 module_param(fasteoi, bool, S_IRUGO);
103 bool __read_mostly enable_apicv = 1;
104 module_param(enable_apicv, bool, S_IRUGO);
107 * If nested=1, nested virtualization is supported, i.e., guests may use
108 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
109 * use VMX instructions.
111 static bool __read_mostly nested = 1;
112 module_param(nested, bool, S_IRUGO);
114 bool __read_mostly enable_pml = 1;
115 module_param_named(pml, enable_pml, bool, S_IRUGO);
117 static bool __read_mostly dump_invalid_vmcs = 0;
118 module_param(dump_invalid_vmcs, bool, 0644);
120 #define MSR_BITMAP_MODE_X2APIC 1
121 #define MSR_BITMAP_MODE_X2APIC_APICV 2
123 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
125 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
126 static int __read_mostly cpu_preemption_timer_multi;
127 static bool __read_mostly enable_preemption_timer = 1;
129 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
132 extern bool __read_mostly allow_smaller_maxphyaddr;
133 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
135 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
136 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
137 #define KVM_VM_CR0_ALWAYS_ON \
138 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
139 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
141 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
142 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
143 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
145 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
147 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
148 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
149 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
150 RTIT_STATUS_BYTECNT))
153 * List of MSRs that can be directly passed to the guest.
154 * In addition to these x2apic and PT MSRs are handled specially.
156 static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
165 MSR_IA32_SYSENTER_CS,
166 MSR_IA32_SYSENTER_ESP,
167 MSR_IA32_SYSENTER_EIP,
169 MSR_CORE_C3_RESIDENCY,
170 MSR_CORE_C6_RESIDENCY,
171 MSR_CORE_C7_RESIDENCY,
175 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
176 * ple_gap: upper bound on the amount of time between two successive
177 * executions of PAUSE in a loop. Also indicate if ple enabled.
178 * According to test, this time is usually smaller than 128 cycles.
179 * ple_window: upper bound on the amount of time a guest is allowed to execute
180 * in a PAUSE loop. Tests indicate that most spinlocks are held for
181 * less than 2^12 cycles
182 * Time is measured based on a counter that runs at the same rate as the TSC,
183 * refer SDM volume 3b section 21.6.13 & 22.1.3.
185 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
186 module_param(ple_gap, uint, 0444);
188 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
189 module_param(ple_window, uint, 0444);
191 /* Default doubles per-vcpu window every exit. */
192 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
193 module_param(ple_window_grow, uint, 0444);
195 /* Default resets per-vcpu window every exit to ple_window. */
196 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
197 module_param(ple_window_shrink, uint, 0444);
199 /* Default is to compute the maximum so we can never overflow. */
200 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
201 module_param(ple_window_max, uint, 0444);
203 /* Default is SYSTEM mode, 1 for host-guest mode */
204 int __read_mostly pt_mode = PT_MODE_SYSTEM;
205 module_param(pt_mode, int, S_IRUGO);
207 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
208 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
209 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
211 /* Storage for pre module init parameter parsing */
212 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
214 static const struct {
217 } vmentry_l1d_param[] = {
218 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
219 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
220 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
221 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
222 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
223 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
226 #define L1D_CACHE_ORDER 4
227 static void *vmx_l1d_flush_pages;
229 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
234 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
235 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
240 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
244 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
247 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
248 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
249 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
254 /* If set to auto use the default l1tf mitigation method */
255 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
256 switch (l1tf_mitigation) {
257 case L1TF_MITIGATION_OFF:
258 l1tf = VMENTER_L1D_FLUSH_NEVER;
260 case L1TF_MITIGATION_FLUSH_NOWARN:
261 case L1TF_MITIGATION_FLUSH:
262 case L1TF_MITIGATION_FLUSH_NOSMT:
263 l1tf = VMENTER_L1D_FLUSH_COND;
265 case L1TF_MITIGATION_FULL:
266 case L1TF_MITIGATION_FULL_FORCE:
267 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
270 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
271 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
274 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
275 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
277 * This allocation for vmx_l1d_flush_pages is not tied to a VM
278 * lifetime and so should not be charged to a memcg.
280 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
283 vmx_l1d_flush_pages = page_address(page);
286 * Initialize each page with a different pattern in
287 * order to protect against KSM in the nested
288 * virtualization case.
290 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
291 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
296 l1tf_vmx_mitigation = l1tf;
298 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
299 static_branch_enable(&vmx_l1d_should_flush);
301 static_branch_disable(&vmx_l1d_should_flush);
303 if (l1tf == VMENTER_L1D_FLUSH_COND)
304 static_branch_enable(&vmx_l1d_flush_cond);
306 static_branch_disable(&vmx_l1d_flush_cond);
310 static int vmentry_l1d_flush_parse(const char *s)
315 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
316 if (vmentry_l1d_param[i].for_parse &&
317 sysfs_streq(s, vmentry_l1d_param[i].option))
324 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
328 l1tf = vmentry_l1d_flush_parse(s);
332 if (!boot_cpu_has(X86_BUG_L1TF))
336 * Has vmx_init() run already? If not then this is the pre init
337 * parameter parsing. In that case just store the value and let
338 * vmx_init() do the proper setup after enable_ept has been
341 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
342 vmentry_l1d_flush_param = l1tf;
346 mutex_lock(&vmx_l1d_flush_mutex);
347 ret = vmx_setup_l1d_flush(l1tf);
348 mutex_unlock(&vmx_l1d_flush_mutex);
352 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
354 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
355 return sprintf(s, "???\n");
357 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
360 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
361 .set = vmentry_l1d_flush_set,
362 .get = vmentry_l1d_flush_get,
364 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
366 static u32 vmx_segment_access_rights(struct kvm_segment *var);
368 void vmx_vmexit(void);
370 #define vmx_insn_failed(fmt...) \
373 pr_warn_ratelimited(fmt); \
376 asmlinkage void vmread_error(unsigned long field, bool fault)
379 kvm_spurious_fault();
381 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
384 noinline void vmwrite_error(unsigned long field, unsigned long value)
386 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
387 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
390 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
392 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
395 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
397 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
400 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
402 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
406 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
408 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
412 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
413 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
415 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
416 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
418 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
420 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
421 static DEFINE_SPINLOCK(vmx_vpid_lock);
423 struct vmcs_config vmcs_config;
424 struct vmx_capability vmx_capability;
426 #define VMX_SEGMENT_FIELD(seg) \
427 [VCPU_SREG_##seg] = { \
428 .selector = GUEST_##seg##_SELECTOR, \
429 .base = GUEST_##seg##_BASE, \
430 .limit = GUEST_##seg##_LIMIT, \
431 .ar_bytes = GUEST_##seg##_AR_BYTES, \
434 static const struct kvm_vmx_segment_field {
439 } kvm_vmx_segment_fields[] = {
440 VMX_SEGMENT_FIELD(CS),
441 VMX_SEGMENT_FIELD(DS),
442 VMX_SEGMENT_FIELD(ES),
443 VMX_SEGMENT_FIELD(FS),
444 VMX_SEGMENT_FIELD(GS),
445 VMX_SEGMENT_FIELD(SS),
446 VMX_SEGMENT_FIELD(TR),
447 VMX_SEGMENT_FIELD(LDTR),
450 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
452 vmx->segment_cache.bitmask = 0;
455 static unsigned long host_idt_base;
458 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
459 * will emulate SYSCALL in legacy mode if the vendor string in guest
460 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
461 * support this emulation, IA32_STAR must always be included in
462 * vmx_uret_msrs_list[], even in i386 builds.
464 static const u32 vmx_uret_msrs_list[] = {
466 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
468 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
472 #if IS_ENABLED(CONFIG_HYPERV)
473 static bool __read_mostly enlightened_vmcs = true;
474 module_param(enlightened_vmcs, bool, 0444);
476 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
479 struct kvm_tlb_range *range = data;
481 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
485 static inline int hv_remote_flush_root_ept(hpa_t root_ept,
486 struct kvm_tlb_range *range)
489 return hyperv_flush_guest_mapping_range(root_ept,
490 kvm_fill_hv_flush_list_func, (void *)range);
492 return hyperv_flush_guest_mapping(root_ept);
495 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
496 struct kvm_tlb_range *range)
498 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
499 struct kvm_vcpu *vcpu;
500 int ret = 0, i, nr_unique_valid_roots;
503 spin_lock(&kvm_vmx->hv_root_ept_lock);
505 if (!VALID_PAGE(kvm_vmx->hv_root_ept)) {
506 nr_unique_valid_roots = 0;
509 * Flush all valid roots, and see if all vCPUs have converged
510 * on a common root, in which case future flushes can skip the
511 * loop and flush the common root.
513 kvm_for_each_vcpu(i, vcpu, kvm) {
514 root = to_vmx(vcpu)->hv_root_ept;
515 if (!VALID_PAGE(root) || root == kvm_vmx->hv_root_ept)
519 * Set the tracked root to the first valid root. Keep
520 * this root for the entirety of the loop even if more
521 * roots are encountered as a low effort optimization
522 * to avoid flushing the same (first) root again.
524 if (++nr_unique_valid_roots == 1)
525 kvm_vmx->hv_root_ept = root;
528 ret = hv_remote_flush_root_ept(root, range);
531 * Stop processing roots if a failure occurred and
532 * multiple valid roots have already been detected.
534 if (ret && nr_unique_valid_roots > 1)
539 * The optimized flush of a single root can't be used if there
540 * are multiple valid roots (obviously).
542 if (nr_unique_valid_roots > 1)
543 kvm_vmx->hv_root_ept = INVALID_PAGE;
545 ret = hv_remote_flush_root_ept(kvm_vmx->hv_root_ept, range);
548 spin_unlock(&kvm_vmx->hv_root_ept_lock);
551 static int hv_remote_flush_tlb(struct kvm *kvm)
553 return hv_remote_flush_tlb_with_range(kvm, NULL);
556 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
558 struct hv_enlightened_vmcs *evmcs;
559 struct hv_partition_assist_pg **p_hv_pa_pg =
560 &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
562 * Synthetic VM-Exit is not enabled in current code and so All
563 * evmcs in singe VM shares same assist page.
566 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
571 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
573 evmcs->partition_assist_page =
575 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
576 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
581 #endif /* IS_ENABLED(CONFIG_HYPERV) */
583 static void hv_track_root_ept(struct kvm_vcpu *vcpu, hpa_t root_ept)
585 #if IS_ENABLED(CONFIG_HYPERV)
586 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
588 if (kvm_x86_ops.tlb_remote_flush == hv_remote_flush_tlb) {
589 spin_lock(&kvm_vmx->hv_root_ept_lock);
590 to_vmx(vcpu)->hv_root_ept = root_ept;
591 if (root_ept != kvm_vmx->hv_root_ept)
592 kvm_vmx->hv_root_ept = INVALID_PAGE;
593 spin_unlock(&kvm_vmx->hv_root_ept_lock);
599 * Comment's format: document - errata name - stepping - processor name.
601 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
603 static u32 vmx_preemption_cpu_tfms[] = {
604 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
606 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
607 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
608 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
610 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
612 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
613 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
615 * 320767.pdf - AAP86 - B1 -
616 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
619 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
621 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
623 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
625 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
626 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
627 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
629 /* Xeon E3-1220 V2 */
633 static inline bool cpu_has_broken_vmx_preemption_timer(void)
635 u32 eax = cpuid_eax(0x00000001), i;
637 /* Clear the reserved bits */
638 eax &= ~(0x3U << 14 | 0xfU << 28);
639 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
640 if (eax == vmx_preemption_cpu_tfms[i])
646 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
648 return flexpriority_enabled && lapic_in_kernel(vcpu);
651 static inline bool report_flexpriority(void)
653 return flexpriority_enabled;
656 static int possible_passthrough_msr_slot(u32 msr)
660 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
661 if (vmx_possible_passthrough_msrs[i] == msr)
667 static bool is_valid_passthrough_msr(u32 msr)
672 case 0x800 ... 0x8ff:
673 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
675 case MSR_IA32_RTIT_STATUS:
676 case MSR_IA32_RTIT_OUTPUT_BASE:
677 case MSR_IA32_RTIT_OUTPUT_MASK:
678 case MSR_IA32_RTIT_CR3_MATCH:
679 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
680 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
683 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
684 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
685 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
686 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
687 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
688 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
692 r = possible_passthrough_msr_slot(msr) != -ENOENT;
694 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
699 static inline int __vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
703 for (i = 0; i < vmx->nr_uret_msrs; ++i)
704 if (vmx_uret_msrs_list[vmx->guest_uret_msrs[i].slot] == msr)
709 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
713 i = __vmx_find_uret_msr(vmx, msr);
715 return &vmx->guest_uret_msrs[i];
719 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
720 struct vmx_uret_msr *msr, u64 data)
724 u64 old_msr_data = msr->data;
726 if (msr - vmx->guest_uret_msrs < vmx->nr_active_uret_msrs) {
728 ret = kvm_set_user_return_msr(msr->slot, msr->data, msr->mask);
731 msr->data = old_msr_data;
736 #ifdef CONFIG_KEXEC_CORE
737 static void crash_vmclear_local_loaded_vmcss(void)
739 int cpu = raw_smp_processor_id();
740 struct loaded_vmcs *v;
742 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
743 loaded_vmcss_on_cpu_link)
746 #endif /* CONFIG_KEXEC_CORE */
748 static void __loaded_vmcs_clear(void *arg)
750 struct loaded_vmcs *loaded_vmcs = arg;
751 int cpu = raw_smp_processor_id();
753 if (loaded_vmcs->cpu != cpu)
754 return; /* vcpu migration can race with cpu offline */
755 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
756 per_cpu(current_vmcs, cpu) = NULL;
758 vmcs_clear(loaded_vmcs->vmcs);
759 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
760 vmcs_clear(loaded_vmcs->shadow_vmcs);
762 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
765 * Ensure all writes to loaded_vmcs, including deleting it from its
766 * current percpu list, complete before setting loaded_vmcs->vcpu to
767 * -1, otherwise a different cpu can see vcpu == -1 first and add
768 * loaded_vmcs to its percpu list before it's deleted from this cpu's
769 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
773 loaded_vmcs->cpu = -1;
774 loaded_vmcs->launched = 0;
777 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
779 int cpu = loaded_vmcs->cpu;
782 smp_call_function_single(cpu,
783 __loaded_vmcs_clear, loaded_vmcs, 1);
786 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
790 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
792 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
793 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
794 vmx->segment_cache.bitmask = 0;
796 ret = vmx->segment_cache.bitmask & mask;
797 vmx->segment_cache.bitmask |= mask;
801 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
803 u16 *p = &vmx->segment_cache.seg[seg].selector;
805 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
806 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
810 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
812 ulong *p = &vmx->segment_cache.seg[seg].base;
814 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
815 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
819 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
821 u32 *p = &vmx->segment_cache.seg[seg].limit;
823 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
824 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
828 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
830 u32 *p = &vmx->segment_cache.seg[seg].ar;
832 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
833 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
837 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
841 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
842 (1u << DB_VECTOR) | (1u << AC_VECTOR);
844 * Guest access to VMware backdoor ports could legitimately
845 * trigger #GP because of TSS I/O permission bitmap.
846 * We intercept those #GP and allow access to them anyway
849 if (enable_vmware_backdoor)
850 eb |= (1u << GP_VECTOR);
851 if ((vcpu->guest_debug &
852 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
853 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
854 eb |= 1u << BP_VECTOR;
855 if (to_vmx(vcpu)->rmode.vm86_active)
857 if (!vmx_need_pf_intercept(vcpu))
858 eb &= ~(1u << PF_VECTOR);
860 /* When we are running a nested L2 guest and L1 specified for it a
861 * certain exception bitmap, we must trap the same exceptions and pass
862 * them to L1. When running L2, we will only handle the exceptions
863 * specified above if L1 did not want them.
865 if (is_guest_mode(vcpu))
866 eb |= get_vmcs12(vcpu)->exception_bitmap;
869 * If EPT is enabled, #PF is only trapped if MAXPHYADDR is mismatched
870 * between guest and host. In that case we only care about present
871 * faults. For vmcs02, however, PFEC_MASK and PFEC_MATCH are set in
872 * prepare_vmcs02_rare.
874 bool selective_pf_trap = enable_ept && (eb & (1u << PF_VECTOR));
875 int mask = selective_pf_trap ? PFERR_PRESENT_MASK : 0;
876 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
877 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, mask);
880 vmcs_write32(EXCEPTION_BITMAP, eb);
884 * Check if MSR is intercepted for currently loaded MSR bitmap.
886 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
888 unsigned long *msr_bitmap;
889 int f = sizeof(unsigned long);
891 if (!cpu_has_vmx_msr_bitmap())
894 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
897 return !!test_bit(msr, msr_bitmap + 0x800 / f);
898 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
900 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
906 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
907 unsigned long entry, unsigned long exit)
909 vm_entry_controls_clearbit(vmx, entry);
910 vm_exit_controls_clearbit(vmx, exit);
913 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
917 for (i = 0; i < m->nr; ++i) {
918 if (m->val[i].index == msr)
924 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
927 struct msr_autoload *m = &vmx->msr_autoload;
931 if (cpu_has_load_ia32_efer()) {
932 clear_atomic_switch_msr_special(vmx,
933 VM_ENTRY_LOAD_IA32_EFER,
934 VM_EXIT_LOAD_IA32_EFER);
938 case MSR_CORE_PERF_GLOBAL_CTRL:
939 if (cpu_has_load_perf_global_ctrl()) {
940 clear_atomic_switch_msr_special(vmx,
941 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
942 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
947 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
951 m->guest.val[i] = m->guest.val[m->guest.nr];
952 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
955 i = vmx_find_loadstore_msr_slot(&m->host, msr);
960 m->host.val[i] = m->host.val[m->host.nr];
961 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
964 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
965 unsigned long entry, unsigned long exit,
966 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
967 u64 guest_val, u64 host_val)
969 vmcs_write64(guest_val_vmcs, guest_val);
970 if (host_val_vmcs != HOST_IA32_EFER)
971 vmcs_write64(host_val_vmcs, host_val);
972 vm_entry_controls_setbit(vmx, entry);
973 vm_exit_controls_setbit(vmx, exit);
976 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
977 u64 guest_val, u64 host_val, bool entry_only)
980 struct msr_autoload *m = &vmx->msr_autoload;
984 if (cpu_has_load_ia32_efer()) {
985 add_atomic_switch_msr_special(vmx,
986 VM_ENTRY_LOAD_IA32_EFER,
987 VM_EXIT_LOAD_IA32_EFER,
990 guest_val, host_val);
994 case MSR_CORE_PERF_GLOBAL_CTRL:
995 if (cpu_has_load_perf_global_ctrl()) {
996 add_atomic_switch_msr_special(vmx,
997 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
998 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
999 GUEST_IA32_PERF_GLOBAL_CTRL,
1000 HOST_IA32_PERF_GLOBAL_CTRL,
1001 guest_val, host_val);
1005 case MSR_IA32_PEBS_ENABLE:
1006 /* PEBS needs a quiescent period after being disabled (to write
1007 * a record). Disabling PEBS through VMX MSR swapping doesn't
1008 * provide that period, so a CPU could write host's record into
1011 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
1014 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
1016 j = vmx_find_loadstore_msr_slot(&m->host, msr);
1018 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
1019 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
1020 printk_once(KERN_WARNING "Not enough msr switch entries. "
1021 "Can't add msr %x\n", msr);
1026 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1028 m->guest.val[i].index = msr;
1029 m->guest.val[i].value = guest_val;
1036 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1038 m->host.val[j].index = msr;
1039 m->host.val[j].value = host_val;
1042 static bool update_transition_efer(struct vcpu_vmx *vmx)
1044 u64 guest_efer = vmx->vcpu.arch.efer;
1045 u64 ignore_bits = 0;
1048 /* Shadow paging assumes NX to be available. */
1050 guest_efer |= EFER_NX;
1053 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1055 ignore_bits |= EFER_SCE;
1056 #ifdef CONFIG_X86_64
1057 ignore_bits |= EFER_LMA | EFER_LME;
1058 /* SCE is meaningful only in long mode on Intel */
1059 if (guest_efer & EFER_LMA)
1060 ignore_bits &= ~(u64)EFER_SCE;
1064 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1065 * On CPUs that support "load IA32_EFER", always switch EFER
1066 * atomically, since it's faster than switching it manually.
1068 if (cpu_has_load_ia32_efer() ||
1069 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1070 if (!(guest_efer & EFER_LMA))
1071 guest_efer &= ~EFER_LME;
1072 if (guest_efer != host_efer)
1073 add_atomic_switch_msr(vmx, MSR_EFER,
1074 guest_efer, host_efer, false);
1076 clear_atomic_switch_msr(vmx, MSR_EFER);
1080 i = __vmx_find_uret_msr(vmx, MSR_EFER);
1084 clear_atomic_switch_msr(vmx, MSR_EFER);
1086 guest_efer &= ~ignore_bits;
1087 guest_efer |= host_efer & ignore_bits;
1089 vmx->guest_uret_msrs[i].data = guest_efer;
1090 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1095 #ifdef CONFIG_X86_32
1097 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1098 * VMCS rather than the segment table. KVM uses this helper to figure
1099 * out the current bases to poke them into the VMCS before entry.
1101 static unsigned long segment_base(u16 selector)
1103 struct desc_struct *table;
1106 if (!(selector & ~SEGMENT_RPL_MASK))
1109 table = get_current_gdt_ro();
1111 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1112 u16 ldt_selector = kvm_read_ldt();
1114 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1117 table = (struct desc_struct *)segment_base(ldt_selector);
1119 v = get_desc_base(&table[selector >> 3]);
1124 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1126 return vmx_pt_mode_is_host_guest() &&
1127 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1130 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1132 /* The base must be 128-byte aligned and a legal physical address. */
1133 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1136 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1140 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1141 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1142 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1143 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1144 for (i = 0; i < addr_range; i++) {
1145 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1146 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1150 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1154 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1155 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1156 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1157 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1158 for (i = 0; i < addr_range; i++) {
1159 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1160 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1164 static void pt_guest_enter(struct vcpu_vmx *vmx)
1166 if (vmx_pt_mode_is_system())
1170 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1171 * Save host state before VM entry.
1173 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1174 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1175 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1176 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1177 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1181 static void pt_guest_exit(struct vcpu_vmx *vmx)
1183 if (vmx_pt_mode_is_system())
1186 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1187 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1188 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1191 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1192 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1195 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1196 unsigned long fs_base, unsigned long gs_base)
1198 if (unlikely(fs_sel != host->fs_sel)) {
1200 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1202 vmcs_write16(HOST_FS_SELECTOR, 0);
1203 host->fs_sel = fs_sel;
1205 if (unlikely(gs_sel != host->gs_sel)) {
1207 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1209 vmcs_write16(HOST_GS_SELECTOR, 0);
1210 host->gs_sel = gs_sel;
1212 if (unlikely(fs_base != host->fs_base)) {
1213 vmcs_writel(HOST_FS_BASE, fs_base);
1214 host->fs_base = fs_base;
1216 if (unlikely(gs_base != host->gs_base)) {
1217 vmcs_writel(HOST_GS_BASE, gs_base);
1218 host->gs_base = gs_base;
1222 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1224 struct vcpu_vmx *vmx = to_vmx(vcpu);
1225 struct vmcs_host_state *host_state;
1226 #ifdef CONFIG_X86_64
1227 int cpu = raw_smp_processor_id();
1229 unsigned long fs_base, gs_base;
1233 vmx->req_immediate_exit = false;
1236 * Note that guest MSRs to be saved/restored can also be changed
1237 * when guest state is loaded. This happens when guest transitions
1238 * to/from long-mode by setting MSR_EFER.LMA.
1240 if (!vmx->guest_uret_msrs_loaded) {
1241 vmx->guest_uret_msrs_loaded = true;
1242 for (i = 0; i < vmx->nr_active_uret_msrs; ++i)
1243 kvm_set_user_return_msr(vmx->guest_uret_msrs[i].slot,
1244 vmx->guest_uret_msrs[i].data,
1245 vmx->guest_uret_msrs[i].mask);
1249 if (vmx->nested.need_vmcs12_to_shadow_sync)
1250 nested_sync_vmcs12_to_shadow(vcpu);
1252 if (vmx->guest_state_loaded)
1255 host_state = &vmx->loaded_vmcs->host_state;
1258 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1259 * allow segment selectors with cpl > 0 or ti == 1.
1261 host_state->ldt_sel = kvm_read_ldt();
1263 #ifdef CONFIG_X86_64
1264 savesegment(ds, host_state->ds_sel);
1265 savesegment(es, host_state->es_sel);
1267 gs_base = cpu_kernelmode_gs_base(cpu);
1268 if (likely(is_64bit_mm(current->mm))) {
1269 current_save_fsgs();
1270 fs_sel = current->thread.fsindex;
1271 gs_sel = current->thread.gsindex;
1272 fs_base = current->thread.fsbase;
1273 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1275 savesegment(fs, fs_sel);
1276 savesegment(gs, gs_sel);
1277 fs_base = read_msr(MSR_FS_BASE);
1278 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1281 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1283 savesegment(fs, fs_sel);
1284 savesegment(gs, gs_sel);
1285 fs_base = segment_base(fs_sel);
1286 gs_base = segment_base(gs_sel);
1289 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1290 vmx->guest_state_loaded = true;
1293 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1295 struct vmcs_host_state *host_state;
1297 if (!vmx->guest_state_loaded)
1300 host_state = &vmx->loaded_vmcs->host_state;
1302 ++vmx->vcpu.stat.host_state_reload;
1304 #ifdef CONFIG_X86_64
1305 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1307 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1308 kvm_load_ldt(host_state->ldt_sel);
1309 #ifdef CONFIG_X86_64
1310 load_gs_index(host_state->gs_sel);
1312 loadsegment(gs, host_state->gs_sel);
1315 if (host_state->fs_sel & 7)
1316 loadsegment(fs, host_state->fs_sel);
1317 #ifdef CONFIG_X86_64
1318 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1319 loadsegment(ds, host_state->ds_sel);
1320 loadsegment(es, host_state->es_sel);
1323 invalidate_tss_limit();
1324 #ifdef CONFIG_X86_64
1325 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1327 load_fixmap_gdt(raw_smp_processor_id());
1328 vmx->guest_state_loaded = false;
1329 vmx->guest_uret_msrs_loaded = false;
1332 #ifdef CONFIG_X86_64
1333 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1336 if (vmx->guest_state_loaded)
1337 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1339 return vmx->msr_guest_kernel_gs_base;
1342 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1345 if (vmx->guest_state_loaded)
1346 wrmsrl(MSR_KERNEL_GS_BASE, data);
1348 vmx->msr_guest_kernel_gs_base = data;
1352 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1353 struct loaded_vmcs *buddy)
1355 struct vcpu_vmx *vmx = to_vmx(vcpu);
1356 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1359 if (!already_loaded) {
1360 loaded_vmcs_clear(vmx->loaded_vmcs);
1361 local_irq_disable();
1364 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1365 * this cpu's percpu list, otherwise it may not yet be deleted
1366 * from its previous cpu's percpu list. Pairs with the
1367 * smb_wmb() in __loaded_vmcs_clear().
1371 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1372 &per_cpu(loaded_vmcss_on_cpu, cpu));
1376 prev = per_cpu(current_vmcs, cpu);
1377 if (prev != vmx->loaded_vmcs->vmcs) {
1378 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1379 vmcs_load(vmx->loaded_vmcs->vmcs);
1382 * No indirect branch prediction barrier needed when switching
1383 * the active VMCS within a guest, e.g. on nested VM-Enter.
1384 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1386 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1387 indirect_branch_prediction_barrier();
1390 if (!already_loaded) {
1391 void *gdt = get_current_gdt_ro();
1392 unsigned long sysenter_esp;
1395 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1396 * TLB entries from its previous association with the vCPU.
1398 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1401 * Linux uses per-cpu TSS and GDT, so set these when switching
1402 * processors. See 22.2.4.
1404 vmcs_writel(HOST_TR_BASE,
1405 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1406 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1408 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1409 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1411 vmx->loaded_vmcs->cpu = cpu;
1414 /* Setup TSC multiplier */
1415 if (kvm_has_tsc_control &&
1416 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1417 decache_tsc_multiplier(vmx);
1421 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1422 * vcpu mutex is already taken.
1424 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1426 struct vcpu_vmx *vmx = to_vmx(vcpu);
1428 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1430 vmx_vcpu_pi_load(vcpu, cpu);
1432 vmx->host_debugctlmsr = get_debugctlmsr();
1435 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1437 vmx_vcpu_pi_put(vcpu);
1439 vmx_prepare_switch_to_host(to_vmx(vcpu));
1442 static bool emulation_required(struct kvm_vcpu *vcpu)
1444 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1447 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1449 struct vcpu_vmx *vmx = to_vmx(vcpu);
1450 unsigned long rflags, save_rflags;
1452 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1453 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1454 rflags = vmcs_readl(GUEST_RFLAGS);
1455 if (vmx->rmode.vm86_active) {
1456 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1457 save_rflags = vmx->rmode.save_rflags;
1458 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1460 vmx->rflags = rflags;
1465 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1467 struct vcpu_vmx *vmx = to_vmx(vcpu);
1468 unsigned long old_rflags;
1470 if (is_unrestricted_guest(vcpu)) {
1471 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1472 vmx->rflags = rflags;
1473 vmcs_writel(GUEST_RFLAGS, rflags);
1477 old_rflags = vmx_get_rflags(vcpu);
1478 vmx->rflags = rflags;
1479 if (vmx->rmode.vm86_active) {
1480 vmx->rmode.save_rflags = rflags;
1481 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1483 vmcs_writel(GUEST_RFLAGS, rflags);
1485 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1486 vmx->emulation_required = emulation_required(vcpu);
1489 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1491 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1494 if (interruptibility & GUEST_INTR_STATE_STI)
1495 ret |= KVM_X86_SHADOW_INT_STI;
1496 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1497 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1502 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1504 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1505 u32 interruptibility = interruptibility_old;
1507 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1509 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1510 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1511 else if (mask & KVM_X86_SHADOW_INT_STI)
1512 interruptibility |= GUEST_INTR_STATE_STI;
1514 if ((interruptibility != interruptibility_old))
1515 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1518 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1520 struct vcpu_vmx *vmx = to_vmx(vcpu);
1521 unsigned long value;
1524 * Any MSR write that attempts to change bits marked reserved will
1527 if (data & vmx->pt_desc.ctl_bitmask)
1531 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1532 * result in a #GP unless the same write also clears TraceEn.
1534 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1535 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1539 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1540 * and FabricEn would cause #GP, if
1541 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1543 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1544 !(data & RTIT_CTL_FABRIC_EN) &&
1545 !intel_pt_validate_cap(vmx->pt_desc.caps,
1546 PT_CAP_single_range_output))
1550 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1551 * utilize encodings marked reserved will cause a #GP fault.
1553 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1554 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1555 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1556 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1558 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1559 PT_CAP_cycle_thresholds);
1560 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1561 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1562 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1564 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1565 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1566 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1567 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1571 * If ADDRx_CFG is reserved or the encodings is >2 will
1572 * cause a #GP fault.
1574 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1575 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1577 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1578 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1580 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1581 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1583 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1584 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1590 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
1593 * Emulation of instructions in SGX enclaves is impossible as RIP does
1594 * not point tthe failing instruction, and even if it did, the code
1595 * stream is inaccessible. Inject #UD instead of exiting to userspace
1596 * so that guest userspace can't DoS the guest simply by triggering
1597 * emulation (enclaves are CPL3 only).
1599 if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1600 kvm_queue_exception(vcpu, UD_VECTOR);
1606 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1608 union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1609 unsigned long rip, orig_rip;
1613 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1614 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1615 * set when EPT misconfig occurs. In practice, real hardware updates
1616 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1617 * (namely Hyper-V) don't set it due to it being undefined behavior,
1618 * i.e. we end up advancing IP with some random value.
1620 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1621 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1622 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1625 * Emulating an enclave's instructions isn't supported as KVM
1626 * cannot access the enclave's memory or its true RIP, e.g. the
1627 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1628 * the RIP that actually triggered the VM-Exit. But, because
1629 * most instructions that cause VM-Exit will #UD in an enclave,
1630 * most instruction-based VM-Exits simply do not occur.
1632 * There are a few exceptions, notably the debug instructions
1633 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1634 * and generate #DB/#BP as expected, which KVM might intercept.
1635 * But again, the CPU does the dirty work and saves an instr
1636 * length of zero so VMMs don't shoot themselves in the foot.
1637 * WARN if KVM tries to skip a non-zero length instruction on
1638 * a VM-Exit from an enclave.
1643 WARN(exit_reason.enclave_mode,
1644 "KVM: skipping instruction after SGX enclave VM-Exit");
1646 orig_rip = kvm_rip_read(vcpu);
1647 rip = orig_rip + instr_len;
1648 #ifdef CONFIG_X86_64
1650 * We need to mask out the high 32 bits of RIP if not in 64-bit
1651 * mode, but just finding out that we are in 64-bit mode is
1652 * quite expensive. Only do it if there was a carry.
1654 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1657 kvm_rip_write(vcpu, rip);
1659 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1664 /* skipping an emulated instruction also counts */
1665 vmx_set_interrupt_shadow(vcpu, 0);
1671 * Recognizes a pending MTF VM-exit and records the nested state for later
1674 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1676 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1677 struct vcpu_vmx *vmx = to_vmx(vcpu);
1679 if (!is_guest_mode(vcpu))
1683 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1684 * T-bit traps. As instruction emulation is completed (i.e. at the
1685 * instruction boundary), any #DB exception pending delivery must be a
1686 * debug-trap. Record the pending MTF state to be delivered in
1687 * vmx_check_nested_events().
1689 if (nested_cpu_has_mtf(vmcs12) &&
1690 (!vcpu->arch.exception.pending ||
1691 vcpu->arch.exception.nr == DB_VECTOR))
1692 vmx->nested.mtf_pending = true;
1694 vmx->nested.mtf_pending = false;
1697 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1699 vmx_update_emulated_instruction(vcpu);
1700 return skip_emulated_instruction(vcpu);
1703 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1706 * Ensure that we clear the HLT state in the VMCS. We don't need to
1707 * explicitly skip the instruction because if the HLT state is set,
1708 * then the instruction is already executing and RIP has already been
1711 if (kvm_hlt_in_guest(vcpu->kvm) &&
1712 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1713 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1716 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1718 struct vcpu_vmx *vmx = to_vmx(vcpu);
1719 unsigned nr = vcpu->arch.exception.nr;
1720 bool has_error_code = vcpu->arch.exception.has_error_code;
1721 u32 error_code = vcpu->arch.exception.error_code;
1722 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1724 kvm_deliver_exception_payload(vcpu);
1726 if (has_error_code) {
1727 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1728 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1731 if (vmx->rmode.vm86_active) {
1733 if (kvm_exception_is_soft(nr))
1734 inc_eip = vcpu->arch.event_exit_inst_len;
1735 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1739 WARN_ON_ONCE(vmx->emulation_required);
1741 if (kvm_exception_is_soft(nr)) {
1742 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1743 vmx->vcpu.arch.event_exit_inst_len);
1744 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1746 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1748 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1750 vmx_clear_hlt(vcpu);
1753 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr)
1755 struct vmx_uret_msr tmp;
1758 from = __vmx_find_uret_msr(vmx, msr);
1761 to = vmx->nr_active_uret_msrs++;
1763 tmp = vmx->guest_uret_msrs[to];
1764 vmx->guest_uret_msrs[to] = vmx->guest_uret_msrs[from];
1765 vmx->guest_uret_msrs[from] = tmp;
1769 * Set up the vmcs to automatically save and restore system
1770 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1771 * mode, as fiddling with msrs is very expensive.
1773 static void setup_msrs(struct vcpu_vmx *vmx)
1775 vmx->guest_uret_msrs_loaded = false;
1776 vmx->nr_active_uret_msrs = 0;
1777 #ifdef CONFIG_X86_64
1779 * The SYSCALL MSRs are only needed on long mode guests, and only
1780 * when EFER.SCE is set.
1782 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1783 vmx_setup_uret_msr(vmx, MSR_STAR);
1784 vmx_setup_uret_msr(vmx, MSR_LSTAR);
1785 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK);
1788 if (update_transition_efer(vmx))
1789 vmx_setup_uret_msr(vmx, MSR_EFER);
1791 if (guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1792 vmx_setup_uret_msr(vmx, MSR_TSC_AUX);
1794 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL);
1796 if (cpu_has_vmx_msr_bitmap())
1797 vmx_update_msr_bitmap(&vmx->vcpu);
1800 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1802 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1803 u64 g_tsc_offset = 0;
1806 * We're here if L1 chose not to trap WRMSR to TSC. According
1807 * to the spec, this should set L1's TSC; The offset that L1
1808 * set for L2 remains unchanged, and still needs to be added
1809 * to the newly set TSC to get L2's TSC.
1811 if (is_guest_mode(vcpu) &&
1812 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
1813 g_tsc_offset = vmcs12->tsc_offset;
1815 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1816 vcpu->arch.tsc_offset - g_tsc_offset,
1818 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1819 return offset + g_tsc_offset;
1823 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1824 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1825 * all guests if the "nested" module option is off, and can also be disabled
1826 * for a single guest by disabling its VMX cpuid bit.
1828 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1830 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1833 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1836 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1838 return !(val & ~valid_bits);
1841 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1843 switch (msr->index) {
1844 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1847 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1848 case MSR_IA32_PERF_CAPABILITIES:
1849 msr->data = vmx_get_perf_capabilities();
1852 return KVM_MSR_RET_INVALID;
1857 * Reads an msr value (of 'msr_index') into 'pdata'.
1858 * Returns 0 on success, non-0 otherwise.
1859 * Assumes vcpu_load() was already called.
1861 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1863 struct vcpu_vmx *vmx = to_vmx(vcpu);
1864 struct vmx_uret_msr *msr;
1867 switch (msr_info->index) {
1868 #ifdef CONFIG_X86_64
1870 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1873 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1875 case MSR_KERNEL_GS_BASE:
1876 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1880 return kvm_get_msr_common(vcpu, msr_info);
1881 case MSR_IA32_TSX_CTRL:
1882 if (!msr_info->host_initiated &&
1883 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1886 case MSR_IA32_UMWAIT_CONTROL:
1887 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1890 msr_info->data = vmx->msr_ia32_umwait_control;
1892 case MSR_IA32_SPEC_CTRL:
1893 if (!msr_info->host_initiated &&
1894 !guest_has_spec_ctrl_msr(vcpu))
1897 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1899 case MSR_IA32_SYSENTER_CS:
1900 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1902 case MSR_IA32_SYSENTER_EIP:
1903 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1905 case MSR_IA32_SYSENTER_ESP:
1906 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1908 case MSR_IA32_BNDCFGS:
1909 if (!kvm_mpx_supported() ||
1910 (!msr_info->host_initiated &&
1911 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1913 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1915 case MSR_IA32_MCG_EXT_CTL:
1916 if (!msr_info->host_initiated &&
1917 !(vmx->msr_ia32_feature_control &
1918 FEAT_CTL_LMCE_ENABLED))
1920 msr_info->data = vcpu->arch.mcg_ext_ctl;
1922 case MSR_IA32_FEAT_CTL:
1923 msr_info->data = vmx->msr_ia32_feature_control;
1925 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
1926 if (!msr_info->host_initiated &&
1927 !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
1929 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
1930 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
1932 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1933 if (!nested_vmx_allowed(vcpu))
1935 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1939 * Enlightened VMCS v1 doesn't have certain fields, but buggy
1940 * Hyper-V versions are still trying to use corresponding
1941 * features when they are exposed. Filter out the essential
1944 if (!msr_info->host_initiated &&
1945 vmx->nested.enlightened_vmcs_enabled)
1946 nested_evmcs_filter_control_msr(msr_info->index,
1949 case MSR_IA32_RTIT_CTL:
1950 if (!vmx_pt_mode_is_host_guest())
1952 msr_info->data = vmx->pt_desc.guest.ctl;
1954 case MSR_IA32_RTIT_STATUS:
1955 if (!vmx_pt_mode_is_host_guest())
1957 msr_info->data = vmx->pt_desc.guest.status;
1959 case MSR_IA32_RTIT_CR3_MATCH:
1960 if (!vmx_pt_mode_is_host_guest() ||
1961 !intel_pt_validate_cap(vmx->pt_desc.caps,
1962 PT_CAP_cr3_filtering))
1964 msr_info->data = vmx->pt_desc.guest.cr3_match;
1966 case MSR_IA32_RTIT_OUTPUT_BASE:
1967 if (!vmx_pt_mode_is_host_guest() ||
1968 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1969 PT_CAP_topa_output) &&
1970 !intel_pt_validate_cap(vmx->pt_desc.caps,
1971 PT_CAP_single_range_output)))
1973 msr_info->data = vmx->pt_desc.guest.output_base;
1975 case MSR_IA32_RTIT_OUTPUT_MASK:
1976 if (!vmx_pt_mode_is_host_guest() ||
1977 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1978 PT_CAP_topa_output) &&
1979 !intel_pt_validate_cap(vmx->pt_desc.caps,
1980 PT_CAP_single_range_output)))
1982 msr_info->data = vmx->pt_desc.guest.output_mask;
1984 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1985 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1986 if (!vmx_pt_mode_is_host_guest() ||
1987 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1988 PT_CAP_num_address_ranges)))
1991 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1993 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1996 if (!msr_info->host_initiated &&
1997 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2000 case MSR_IA32_DEBUGCTLMSR:
2001 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
2005 msr = vmx_find_uret_msr(vmx, msr_info->index);
2007 msr_info->data = msr->data;
2010 return kvm_get_msr_common(vcpu, msr_info);
2016 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
2019 #ifdef CONFIG_X86_64
2020 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
2023 return (unsigned long)data;
2026 static u64 vcpu_supported_debugctl(struct kvm_vcpu *vcpu)
2028 u64 debugctl = vmx_supported_debugctl();
2030 if (!intel_pmu_lbr_is_enabled(vcpu))
2031 debugctl &= ~DEBUGCTLMSR_LBR_MASK;
2037 * Writes msr value into the appropriate "register".
2038 * Returns 0 on success, non-0 otherwise.
2039 * Assumes vcpu_load() was already called.
2041 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2043 struct vcpu_vmx *vmx = to_vmx(vcpu);
2044 struct vmx_uret_msr *msr;
2046 u32 msr_index = msr_info->index;
2047 u64 data = msr_info->data;
2050 switch (msr_index) {
2052 ret = kvm_set_msr_common(vcpu, msr_info);
2054 #ifdef CONFIG_X86_64
2056 vmx_segment_cache_clear(vmx);
2057 vmcs_writel(GUEST_FS_BASE, data);
2060 vmx_segment_cache_clear(vmx);
2061 vmcs_writel(GUEST_GS_BASE, data);
2063 case MSR_KERNEL_GS_BASE:
2064 vmx_write_guest_kernel_gs_base(vmx, data);
2067 case MSR_IA32_SYSENTER_CS:
2068 if (is_guest_mode(vcpu))
2069 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2070 vmcs_write32(GUEST_SYSENTER_CS, data);
2072 case MSR_IA32_SYSENTER_EIP:
2073 if (is_guest_mode(vcpu)) {
2074 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2075 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2077 vmcs_writel(GUEST_SYSENTER_EIP, data);
2079 case MSR_IA32_SYSENTER_ESP:
2080 if (is_guest_mode(vcpu)) {
2081 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2082 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2084 vmcs_writel(GUEST_SYSENTER_ESP, data);
2086 case MSR_IA32_DEBUGCTLMSR: {
2087 u64 invalid = data & ~vcpu_supported_debugctl(vcpu);
2088 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2089 if (report_ignored_msrs)
2090 vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
2092 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2093 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2099 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2100 VM_EXIT_SAVE_DEBUG_CONTROLS)
2101 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2103 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2104 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2105 (data & DEBUGCTLMSR_LBR))
2106 intel_pmu_create_guest_lbr_event(vcpu);
2109 case MSR_IA32_BNDCFGS:
2110 if (!kvm_mpx_supported() ||
2111 (!msr_info->host_initiated &&
2112 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2114 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2115 (data & MSR_IA32_BNDCFGS_RSVD))
2117 vmcs_write64(GUEST_BNDCFGS, data);
2119 case MSR_IA32_UMWAIT_CONTROL:
2120 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2123 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2124 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2127 vmx->msr_ia32_umwait_control = data;
2129 case MSR_IA32_SPEC_CTRL:
2130 if (!msr_info->host_initiated &&
2131 !guest_has_spec_ctrl_msr(vcpu))
2134 if (kvm_spec_ctrl_test_value(data))
2137 vmx->spec_ctrl = data;
2143 * When it's written (to non-zero) for the first time, pass
2147 * The handling of the MSR bitmap for L2 guests is done in
2148 * nested_vmx_prepare_msr_bitmap. We should not touch the
2149 * vmcs02.msr_bitmap here since it gets completely overwritten
2150 * in the merging. We update the vmcs01 here for L1 as well
2151 * since it will end up touching the MSR anyway now.
2153 vmx_disable_intercept_for_msr(vcpu,
2157 case MSR_IA32_TSX_CTRL:
2158 if (!msr_info->host_initiated &&
2159 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2161 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2164 case MSR_IA32_PRED_CMD:
2165 if (!msr_info->host_initiated &&
2166 !guest_has_pred_cmd_msr(vcpu))
2169 if (data & ~PRED_CMD_IBPB)
2171 if (!boot_cpu_has(X86_FEATURE_IBPB))
2176 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2180 * When it's written (to non-zero) for the first time, pass
2184 * The handling of the MSR bitmap for L2 guests is done in
2185 * nested_vmx_prepare_msr_bitmap. We should not touch the
2186 * vmcs02.msr_bitmap here since it gets completely overwritten
2189 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
2191 case MSR_IA32_CR_PAT:
2192 if (!kvm_pat_valid(data))
2195 if (is_guest_mode(vcpu) &&
2196 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2197 get_vmcs12(vcpu)->guest_ia32_pat = data;
2199 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2200 vmcs_write64(GUEST_IA32_PAT, data);
2201 vcpu->arch.pat = data;
2204 ret = kvm_set_msr_common(vcpu, msr_info);
2206 case MSR_IA32_TSC_ADJUST:
2207 ret = kvm_set_msr_common(vcpu, msr_info);
2209 case MSR_IA32_MCG_EXT_CTL:
2210 if ((!msr_info->host_initiated &&
2211 !(to_vmx(vcpu)->msr_ia32_feature_control &
2212 FEAT_CTL_LMCE_ENABLED)) ||
2213 (data & ~MCG_EXT_CTL_LMCE_EN))
2215 vcpu->arch.mcg_ext_ctl = data;
2217 case MSR_IA32_FEAT_CTL:
2218 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2219 (to_vmx(vcpu)->msr_ia32_feature_control &
2220 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2222 vmx->msr_ia32_feature_control = data;
2223 if (msr_info->host_initiated && data == 0)
2224 vmx_leave_nested(vcpu);
2226 /* SGX may be enabled/disabled by guest's firmware */
2227 vmx_write_encls_bitmap(vcpu, NULL);
2229 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2231 * On real hardware, the LE hash MSRs are writable before
2232 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2233 * at which point SGX related bits in IA32_FEATURE_CONTROL
2236 * KVM does not emulate SGX activation for simplicity, so
2237 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2238 * is unlocked. This is technically not architectural
2239 * behavior, but it's close enough.
2241 if (!msr_info->host_initiated &&
2242 (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2243 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2244 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2246 vmx->msr_ia32_sgxlepubkeyhash
2247 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2249 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2250 if (!msr_info->host_initiated)
2251 return 1; /* they are read-only */
2252 if (!nested_vmx_allowed(vcpu))
2254 return vmx_set_vmx_msr(vcpu, msr_index, data);
2255 case MSR_IA32_RTIT_CTL:
2256 if (!vmx_pt_mode_is_host_guest() ||
2257 vmx_rtit_ctl_check(vcpu, data) ||
2260 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2261 vmx->pt_desc.guest.ctl = data;
2262 pt_update_intercept_for_msr(vcpu);
2264 case MSR_IA32_RTIT_STATUS:
2265 if (!pt_can_write_msr(vmx))
2267 if (data & MSR_IA32_RTIT_STATUS_MASK)
2269 vmx->pt_desc.guest.status = data;
2271 case MSR_IA32_RTIT_CR3_MATCH:
2272 if (!pt_can_write_msr(vmx))
2274 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2275 PT_CAP_cr3_filtering))
2277 vmx->pt_desc.guest.cr3_match = data;
2279 case MSR_IA32_RTIT_OUTPUT_BASE:
2280 if (!pt_can_write_msr(vmx))
2282 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2283 PT_CAP_topa_output) &&
2284 !intel_pt_validate_cap(vmx->pt_desc.caps,
2285 PT_CAP_single_range_output))
2287 if (!pt_output_base_valid(vcpu, data))
2289 vmx->pt_desc.guest.output_base = data;
2291 case MSR_IA32_RTIT_OUTPUT_MASK:
2292 if (!pt_can_write_msr(vmx))
2294 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2295 PT_CAP_topa_output) &&
2296 !intel_pt_validate_cap(vmx->pt_desc.caps,
2297 PT_CAP_single_range_output))
2299 vmx->pt_desc.guest.output_mask = data;
2301 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2302 if (!pt_can_write_msr(vmx))
2304 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2305 if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2306 PT_CAP_num_address_ranges))
2308 if (is_noncanonical_address(data, vcpu))
2311 vmx->pt_desc.guest.addr_b[index / 2] = data;
2313 vmx->pt_desc.guest.addr_a[index / 2] = data;
2316 if (!msr_info->host_initiated &&
2317 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2319 /* Check reserved bit, higher 32 bits should be zero */
2320 if ((data >> 32) != 0)
2323 case MSR_IA32_PERF_CAPABILITIES:
2324 if (data && !vcpu_to_pmu(vcpu)->version)
2326 if (data & PMU_CAP_LBR_FMT) {
2327 if ((data & PMU_CAP_LBR_FMT) !=
2328 (vmx_get_perf_capabilities() & PMU_CAP_LBR_FMT))
2330 if (!intel_pmu_lbr_is_compatible(vcpu))
2333 ret = kvm_set_msr_common(vcpu, msr_info);
2338 msr = vmx_find_uret_msr(vmx, msr_index);
2340 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2342 ret = kvm_set_msr_common(vcpu, msr_info);
2348 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2350 unsigned long guest_owned_bits;
2352 kvm_register_mark_available(vcpu, reg);
2356 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2359 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2361 case VCPU_EXREG_PDPTR:
2363 ept_save_pdptrs(vcpu);
2365 case VCPU_EXREG_CR0:
2366 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2368 vcpu->arch.cr0 &= ~guest_owned_bits;
2369 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2371 case VCPU_EXREG_CR3:
2372 if (is_unrestricted_guest(vcpu) ||
2373 (enable_ept && is_paging(vcpu)))
2374 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2376 case VCPU_EXREG_CR4:
2377 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2379 vcpu->arch.cr4 &= ~guest_owned_bits;
2380 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2388 static __init int cpu_has_kvm_support(void)
2390 return cpu_has_vmx();
2393 static __init int vmx_disabled_by_bios(void)
2395 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2396 !boot_cpu_has(X86_FEATURE_VMX);
2399 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2403 cr4_set_bits(X86_CR4_VMXE);
2405 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2406 _ASM_EXTABLE(1b, %l[fault])
2407 : : [vmxon_pointer] "m"(vmxon_pointer)
2412 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2413 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2414 cr4_clear_bits(X86_CR4_VMXE);
2419 static int hardware_enable(void)
2421 int cpu = raw_smp_processor_id();
2422 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2425 if (cr4_read_shadow() & X86_CR4_VMXE)
2429 * This can happen if we hot-added a CPU but failed to allocate
2430 * VP assist page for it.
2432 if (static_branch_unlikely(&enable_evmcs) &&
2433 !hv_get_vp_assist_page(cpu))
2436 intel_pt_handle_vmx(1);
2438 r = kvm_cpu_vmxon(phys_addr);
2440 intel_pt_handle_vmx(0);
2450 static void vmclear_local_loaded_vmcss(void)
2452 int cpu = raw_smp_processor_id();
2453 struct loaded_vmcs *v, *n;
2455 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2456 loaded_vmcss_on_cpu_link)
2457 __loaded_vmcs_clear(v);
2460 static void hardware_disable(void)
2462 vmclear_local_loaded_vmcss();
2465 kvm_spurious_fault();
2467 intel_pt_handle_vmx(0);
2471 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2472 * directly instead of going through cpu_has(), to ensure KVM is trapping
2473 * ENCLS whenever it's supported in hardware. It does not matter whether
2474 * the host OS supports or has enabled SGX.
2476 static bool cpu_has_sgx(void)
2478 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2481 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2482 u32 msr, u32 *result)
2484 u32 vmx_msr_low, vmx_msr_high;
2485 u32 ctl = ctl_min | ctl_opt;
2487 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2489 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2490 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2492 /* Ensure minimum (required) set of control bits are supported. */
2500 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2501 struct vmx_capability *vmx_cap)
2503 u32 vmx_msr_low, vmx_msr_high;
2504 u32 min, opt, min2, opt2;
2505 u32 _pin_based_exec_control = 0;
2506 u32 _cpu_based_exec_control = 0;
2507 u32 _cpu_based_2nd_exec_control = 0;
2508 u32 _vmexit_control = 0;
2509 u32 _vmentry_control = 0;
2511 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2512 min = CPU_BASED_HLT_EXITING |
2513 #ifdef CONFIG_X86_64
2514 CPU_BASED_CR8_LOAD_EXITING |
2515 CPU_BASED_CR8_STORE_EXITING |
2517 CPU_BASED_CR3_LOAD_EXITING |
2518 CPU_BASED_CR3_STORE_EXITING |
2519 CPU_BASED_UNCOND_IO_EXITING |
2520 CPU_BASED_MOV_DR_EXITING |
2521 CPU_BASED_USE_TSC_OFFSETTING |
2522 CPU_BASED_MWAIT_EXITING |
2523 CPU_BASED_MONITOR_EXITING |
2524 CPU_BASED_INVLPG_EXITING |
2525 CPU_BASED_RDPMC_EXITING;
2527 opt = CPU_BASED_TPR_SHADOW |
2528 CPU_BASED_USE_MSR_BITMAPS |
2529 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2530 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2531 &_cpu_based_exec_control) < 0)
2533 #ifdef CONFIG_X86_64
2534 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2535 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2536 ~CPU_BASED_CR8_STORE_EXITING;
2538 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2540 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2541 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2542 SECONDARY_EXEC_WBINVD_EXITING |
2543 SECONDARY_EXEC_ENABLE_VPID |
2544 SECONDARY_EXEC_ENABLE_EPT |
2545 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2546 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2547 SECONDARY_EXEC_DESC |
2548 SECONDARY_EXEC_ENABLE_RDTSCP |
2549 SECONDARY_EXEC_ENABLE_INVPCID |
2550 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2551 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2552 SECONDARY_EXEC_SHADOW_VMCS |
2553 SECONDARY_EXEC_XSAVES |
2554 SECONDARY_EXEC_RDSEED_EXITING |
2555 SECONDARY_EXEC_RDRAND_EXITING |
2556 SECONDARY_EXEC_ENABLE_PML |
2557 SECONDARY_EXEC_TSC_SCALING |
2558 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2559 SECONDARY_EXEC_PT_USE_GPA |
2560 SECONDARY_EXEC_PT_CONCEAL_VMX |
2561 SECONDARY_EXEC_ENABLE_VMFUNC |
2562 SECONDARY_EXEC_BUS_LOCK_DETECTION;
2564 opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2565 if (adjust_vmx_controls(min2, opt2,
2566 MSR_IA32_VMX_PROCBASED_CTLS2,
2567 &_cpu_based_2nd_exec_control) < 0)
2570 #ifndef CONFIG_X86_64
2571 if (!(_cpu_based_2nd_exec_control &
2572 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2573 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2576 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2577 _cpu_based_2nd_exec_control &= ~(
2578 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2579 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2580 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2582 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2583 &vmx_cap->ept, &vmx_cap->vpid);
2585 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2586 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2588 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2589 CPU_BASED_CR3_STORE_EXITING |
2590 CPU_BASED_INVLPG_EXITING);
2591 } else if (vmx_cap->ept) {
2593 pr_warn_once("EPT CAP should not exist if not support "
2594 "1-setting enable EPT VM-execution control\n");
2596 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2599 pr_warn_once("VPID CAP should not exist if not support "
2600 "1-setting enable VPID VM-execution control\n");
2603 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2604 #ifdef CONFIG_X86_64
2605 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2607 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2608 VM_EXIT_LOAD_IA32_PAT |
2609 VM_EXIT_LOAD_IA32_EFER |
2610 VM_EXIT_CLEAR_BNDCFGS |
2611 VM_EXIT_PT_CONCEAL_PIP |
2612 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2613 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2614 &_vmexit_control) < 0)
2617 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2618 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2619 PIN_BASED_VMX_PREEMPTION_TIMER;
2620 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2621 &_pin_based_exec_control) < 0)
2624 if (cpu_has_broken_vmx_preemption_timer())
2625 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2626 if (!(_cpu_based_2nd_exec_control &
2627 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2628 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2630 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2631 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2632 VM_ENTRY_LOAD_IA32_PAT |
2633 VM_ENTRY_LOAD_IA32_EFER |
2634 VM_ENTRY_LOAD_BNDCFGS |
2635 VM_ENTRY_PT_CONCEAL_PIP |
2636 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2637 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2638 &_vmentry_control) < 0)
2642 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2643 * can't be used due to an errata where VM Exit may incorrectly clear
2644 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2645 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2647 if (boot_cpu_data.x86 == 0x6) {
2648 switch (boot_cpu_data.x86_model) {
2649 case 26: /* AAK155 */
2650 case 30: /* AAP115 */
2651 case 37: /* AAT100 */
2652 case 44: /* BC86,AAY89,BD102 */
2654 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2655 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2656 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2657 "does not work properly. Using workaround\n");
2665 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2667 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2668 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2671 #ifdef CONFIG_X86_64
2672 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2673 if (vmx_msr_high & (1u<<16))
2677 /* Require Write-Back (WB) memory type for VMCS accesses. */
2678 if (((vmx_msr_high >> 18) & 15) != 6)
2681 vmcs_conf->size = vmx_msr_high & 0x1fff;
2682 vmcs_conf->order = get_order(vmcs_conf->size);
2683 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2685 vmcs_conf->revision_id = vmx_msr_low;
2687 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2688 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2689 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2690 vmcs_conf->vmexit_ctrl = _vmexit_control;
2691 vmcs_conf->vmentry_ctrl = _vmentry_control;
2693 #if IS_ENABLED(CONFIG_HYPERV)
2694 if (enlightened_vmcs)
2695 evmcs_sanitize_exec_ctrls(vmcs_conf);
2701 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2703 int node = cpu_to_node(cpu);
2707 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2710 vmcs = page_address(pages);
2711 memset(vmcs, 0, vmcs_config.size);
2713 /* KVM supports Enlightened VMCS v1 only */
2714 if (static_branch_unlikely(&enable_evmcs))
2715 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2717 vmcs->hdr.revision_id = vmcs_config.revision_id;
2720 vmcs->hdr.shadow_vmcs = 1;
2724 void free_vmcs(struct vmcs *vmcs)
2726 free_pages((unsigned long)vmcs, vmcs_config.order);
2730 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2732 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2734 if (!loaded_vmcs->vmcs)
2736 loaded_vmcs_clear(loaded_vmcs);
2737 free_vmcs(loaded_vmcs->vmcs);
2738 loaded_vmcs->vmcs = NULL;
2739 if (loaded_vmcs->msr_bitmap)
2740 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2741 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2744 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2746 loaded_vmcs->vmcs = alloc_vmcs(false);
2747 if (!loaded_vmcs->vmcs)
2750 vmcs_clear(loaded_vmcs->vmcs);
2752 loaded_vmcs->shadow_vmcs = NULL;
2753 loaded_vmcs->hv_timer_soft_disabled = false;
2754 loaded_vmcs->cpu = -1;
2755 loaded_vmcs->launched = 0;
2757 if (cpu_has_vmx_msr_bitmap()) {
2758 loaded_vmcs->msr_bitmap = (unsigned long *)
2759 __get_free_page(GFP_KERNEL_ACCOUNT);
2760 if (!loaded_vmcs->msr_bitmap)
2762 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2764 if (IS_ENABLED(CONFIG_HYPERV) &&
2765 static_branch_unlikely(&enable_evmcs) &&
2766 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2767 struct hv_enlightened_vmcs *evmcs =
2768 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2770 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2774 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2775 memset(&loaded_vmcs->controls_shadow, 0,
2776 sizeof(struct vmcs_controls_shadow));
2781 free_loaded_vmcs(loaded_vmcs);
2785 static void free_kvm_area(void)
2789 for_each_possible_cpu(cpu) {
2790 free_vmcs(per_cpu(vmxarea, cpu));
2791 per_cpu(vmxarea, cpu) = NULL;
2795 static __init int alloc_kvm_area(void)
2799 for_each_possible_cpu(cpu) {
2802 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2809 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2810 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2811 * revision_id reported by MSR_IA32_VMX_BASIC.
2813 * However, even though not explicitly documented by
2814 * TLFS, VMXArea passed as VMXON argument should
2815 * still be marked with revision_id reported by
2818 if (static_branch_unlikely(&enable_evmcs))
2819 vmcs->hdr.revision_id = vmcs_config.revision_id;
2821 per_cpu(vmxarea, cpu) = vmcs;
2826 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2827 struct kvm_segment *save)
2829 if (!emulate_invalid_guest_state) {
2831 * CS and SS RPL should be equal during guest entry according
2832 * to VMX spec, but in reality it is not always so. Since vcpu
2833 * is in the middle of the transition from real mode to
2834 * protected mode it is safe to assume that RPL 0 is a good
2837 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2838 save->selector &= ~SEGMENT_RPL_MASK;
2839 save->dpl = save->selector & SEGMENT_RPL_MASK;
2842 vmx_set_segment(vcpu, save, seg);
2845 static void enter_pmode(struct kvm_vcpu *vcpu)
2847 unsigned long flags;
2848 struct vcpu_vmx *vmx = to_vmx(vcpu);
2851 * Update real mode segment cache. It may be not up-to-date if segment
2852 * register was written while vcpu was in a guest mode.
2854 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2855 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2856 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2857 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2858 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2859 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2861 vmx->rmode.vm86_active = 0;
2863 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2865 flags = vmcs_readl(GUEST_RFLAGS);
2866 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2867 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2868 vmcs_writel(GUEST_RFLAGS, flags);
2870 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2871 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2873 vmx_update_exception_bitmap(vcpu);
2875 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2876 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2877 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2878 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2879 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2880 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2883 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2885 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2886 struct kvm_segment var = *save;
2889 if (seg == VCPU_SREG_CS)
2892 if (!emulate_invalid_guest_state) {
2893 var.selector = var.base >> 4;
2894 var.base = var.base & 0xffff0;
2904 if (save->base & 0xf)
2905 printk_once(KERN_WARNING "kvm: segment base is not "
2906 "paragraph aligned when entering "
2907 "protected mode (seg=%d)", seg);
2910 vmcs_write16(sf->selector, var.selector);
2911 vmcs_writel(sf->base, var.base);
2912 vmcs_write32(sf->limit, var.limit);
2913 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2916 static void enter_rmode(struct kvm_vcpu *vcpu)
2918 unsigned long flags;
2919 struct vcpu_vmx *vmx = to_vmx(vcpu);
2920 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2922 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2923 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2924 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2925 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2926 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2927 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2928 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2930 vmx->rmode.vm86_active = 1;
2933 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2934 * vcpu. Warn the user that an update is overdue.
2936 if (!kvm_vmx->tss_addr)
2937 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2938 "called before entering vcpu\n");
2940 vmx_segment_cache_clear(vmx);
2942 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2943 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2944 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2946 flags = vmcs_readl(GUEST_RFLAGS);
2947 vmx->rmode.save_rflags = flags;
2949 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2951 vmcs_writel(GUEST_RFLAGS, flags);
2952 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2953 vmx_update_exception_bitmap(vcpu);
2955 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2956 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2957 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2958 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2959 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2960 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2962 kvm_mmu_reset_context(vcpu);
2965 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2967 struct vcpu_vmx *vmx = to_vmx(vcpu);
2968 struct vmx_uret_msr *msr = vmx_find_uret_msr(vmx, MSR_EFER);
2970 /* Nothing to do if hardware doesn't support EFER. */
2974 vcpu->arch.efer = efer;
2975 if (efer & EFER_LMA) {
2976 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2979 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2981 msr->data = efer & ~EFER_LME;
2987 #ifdef CONFIG_X86_64
2989 static void enter_lmode(struct kvm_vcpu *vcpu)
2993 vmx_segment_cache_clear(to_vmx(vcpu));
2995 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2996 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2997 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2999 vmcs_write32(GUEST_TR_AR_BYTES,
3000 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
3001 | VMX_AR_TYPE_BUSY_64_TSS);
3003 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3006 static void exit_lmode(struct kvm_vcpu *vcpu)
3008 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3009 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3014 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
3016 struct vcpu_vmx *vmx = to_vmx(vcpu);
3019 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
3020 * the CPU is not required to invalidate guest-physical mappings on
3021 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
3022 * associated with the root EPT structure and not any particular VPID
3023 * (INVVPID also isn't required to invalidate guest-physical mappings).
3027 } else if (enable_vpid) {
3028 if (cpu_has_vmx_invvpid_global()) {
3029 vpid_sync_vcpu_global();
3031 vpid_sync_vcpu_single(vmx->vpid);
3032 vpid_sync_vcpu_single(vmx->nested.vpid02);
3037 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
3039 struct kvm_mmu *mmu = vcpu->arch.mmu;
3040 u64 root_hpa = mmu->root_hpa;
3042 /* No flush required if the current context is invalid. */
3043 if (!VALID_PAGE(root_hpa))
3047 ept_sync_context(construct_eptp(vcpu, root_hpa,
3048 mmu->shadow_root_level));
3049 else if (!is_guest_mode(vcpu))
3050 vpid_sync_context(to_vmx(vcpu)->vpid);
3052 vpid_sync_context(nested_get_vpid02(vcpu));
3055 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3058 * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
3059 * vmx_flush_tlb_guest() for an explanation of why this is ok.
3061 vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
3064 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3067 * vpid_sync_context() is a nop if vmx->vpid==0, e.g. if enable_vpid==0
3068 * or a vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit
3069 * are required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3070 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3071 * i.e. no explicit INVVPID is necessary.
3073 vpid_sync_context(to_vmx(vcpu)->vpid);
3076 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3078 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3080 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3083 if (is_pae_paging(vcpu)) {
3084 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3085 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3086 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3087 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3091 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3093 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3095 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3098 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3099 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3100 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3101 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3103 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
3106 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3108 struct kvm_vcpu *vcpu)
3110 struct vcpu_vmx *vmx = to_vmx(vcpu);
3112 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3113 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3114 if (!(cr0 & X86_CR0_PG)) {
3115 /* From paging/starting to nonpaging */
3116 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3117 CPU_BASED_CR3_STORE_EXITING);
3118 vcpu->arch.cr0 = cr0;
3119 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3120 } else if (!is_paging(vcpu)) {
3121 /* From nonpaging to paging */
3122 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3123 CPU_BASED_CR3_STORE_EXITING);
3124 vcpu->arch.cr0 = cr0;
3125 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3128 if (!(cr0 & X86_CR0_WP))
3129 *hw_cr0 &= ~X86_CR0_WP;
3132 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3134 struct vcpu_vmx *vmx = to_vmx(vcpu);
3135 unsigned long hw_cr0;
3137 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3138 if (is_unrestricted_guest(vcpu))
3139 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3141 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3143 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3146 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3150 #ifdef CONFIG_X86_64
3151 if (vcpu->arch.efer & EFER_LME) {
3152 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3154 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3159 if (enable_ept && !is_unrestricted_guest(vcpu))
3160 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3162 vmcs_writel(CR0_READ_SHADOW, cr0);
3163 vmcs_writel(GUEST_CR0, hw_cr0);
3164 vcpu->arch.cr0 = cr0;
3165 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3167 /* depends on vcpu->arch.cr0 to be set to a new value */
3168 vmx->emulation_required = emulation_required(vcpu);
3171 static int vmx_get_max_tdp_level(void)
3173 if (cpu_has_vmx_ept_5levels())
3178 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3180 u64 eptp = VMX_EPTP_MT_WB;
3182 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3184 if (enable_ept_ad_bits &&
3185 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3186 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3192 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3195 struct kvm *kvm = vcpu->kvm;
3196 bool update_guest_cr3 = true;
3197 unsigned long guest_cr3;
3201 eptp = construct_eptp(vcpu, root_hpa, root_level);
3202 vmcs_write64(EPT_POINTER, eptp);
3204 hv_track_root_ept(vcpu, root_hpa);
3206 if (!enable_unrestricted_guest && !is_paging(vcpu))
3207 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3208 else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3209 guest_cr3 = vcpu->arch.cr3;
3210 else /* vmcs01.GUEST_CR3 is already up-to-date. */
3211 update_guest_cr3 = false;
3212 vmx_ept_load_pdptrs(vcpu);
3214 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3217 if (update_guest_cr3)
3218 vmcs_writel(GUEST_CR3, guest_cr3);
3221 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3224 * We operate under the default treatment of SMM, so VMX cannot be
3225 * enabled under SMM. Note, whether or not VMXE is allowed at all is
3226 * handled by kvm_is_valid_cr4().
3228 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3231 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3237 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3239 unsigned long old_cr4 = vcpu->arch.cr4;
3240 struct vcpu_vmx *vmx = to_vmx(vcpu);
3242 * Pass through host's Machine Check Enable value to hw_cr4, which
3243 * is in force while we are in guest mode. Do not let guests control
3244 * this bit, even if host CR4.MCE == 0.
3246 unsigned long hw_cr4;
3248 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3249 if (is_unrestricted_guest(vcpu))
3250 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3251 else if (vmx->rmode.vm86_active)
3252 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3254 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3256 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3257 if (cr4 & X86_CR4_UMIP) {
3258 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3259 hw_cr4 &= ~X86_CR4_UMIP;
3260 } else if (!is_guest_mode(vcpu) ||
3261 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3262 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3266 vcpu->arch.cr4 = cr4;
3267 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3269 if (!is_unrestricted_guest(vcpu)) {
3271 if (!is_paging(vcpu)) {
3272 hw_cr4 &= ~X86_CR4_PAE;
3273 hw_cr4 |= X86_CR4_PSE;
3274 } else if (!(cr4 & X86_CR4_PAE)) {
3275 hw_cr4 &= ~X86_CR4_PAE;
3280 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3281 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3282 * to be manually disabled when guest switches to non-paging
3285 * If !enable_unrestricted_guest, the CPU is always running
3286 * with CR0.PG=1 and CR4 needs to be modified.
3287 * If enable_unrestricted_guest, the CPU automatically
3288 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3290 if (!is_paging(vcpu))
3291 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3294 vmcs_writel(CR4_READ_SHADOW, cr4);
3295 vmcs_writel(GUEST_CR4, hw_cr4);
3297 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3298 kvm_update_cpuid_runtime(vcpu);
3301 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3303 struct vcpu_vmx *vmx = to_vmx(vcpu);
3306 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3307 *var = vmx->rmode.segs[seg];
3308 if (seg == VCPU_SREG_TR
3309 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3311 var->base = vmx_read_guest_seg_base(vmx, seg);
3312 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3315 var->base = vmx_read_guest_seg_base(vmx, seg);
3316 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3317 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3318 ar = vmx_read_guest_seg_ar(vmx, seg);
3319 var->unusable = (ar >> 16) & 1;
3320 var->type = ar & 15;
3321 var->s = (ar >> 4) & 1;
3322 var->dpl = (ar >> 5) & 3;
3324 * Some userspaces do not preserve unusable property. Since usable
3325 * segment has to be present according to VMX spec we can use present
3326 * property to amend userspace bug by making unusable segment always
3327 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3328 * segment as unusable.
3330 var->present = !var->unusable;
3331 var->avl = (ar >> 12) & 1;
3332 var->l = (ar >> 13) & 1;
3333 var->db = (ar >> 14) & 1;
3334 var->g = (ar >> 15) & 1;
3337 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3339 struct kvm_segment s;
3341 if (to_vmx(vcpu)->rmode.vm86_active) {
3342 vmx_get_segment(vcpu, &s, seg);
3345 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3348 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3350 struct vcpu_vmx *vmx = to_vmx(vcpu);
3352 if (unlikely(vmx->rmode.vm86_active))
3355 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3356 return VMX_AR_DPL(ar);
3360 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3364 if (var->unusable || !var->present)
3367 ar = var->type & 15;
3368 ar |= (var->s & 1) << 4;
3369 ar |= (var->dpl & 3) << 5;
3370 ar |= (var->present & 1) << 7;
3371 ar |= (var->avl & 1) << 12;
3372 ar |= (var->l & 1) << 13;
3373 ar |= (var->db & 1) << 14;
3374 ar |= (var->g & 1) << 15;
3380 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3382 struct vcpu_vmx *vmx = to_vmx(vcpu);
3383 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3385 vmx_segment_cache_clear(vmx);
3387 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3388 vmx->rmode.segs[seg] = *var;
3389 if (seg == VCPU_SREG_TR)
3390 vmcs_write16(sf->selector, var->selector);
3392 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3396 vmcs_writel(sf->base, var->base);
3397 vmcs_write32(sf->limit, var->limit);
3398 vmcs_write16(sf->selector, var->selector);
3401 * Fix the "Accessed" bit in AR field of segment registers for older
3403 * IA32 arch specifies that at the time of processor reset the
3404 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3405 * is setting it to 0 in the userland code. This causes invalid guest
3406 * state vmexit when "unrestricted guest" mode is turned on.
3407 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3408 * tree. Newer qemu binaries with that qemu fix would not need this
3411 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3412 var->type |= 0x1; /* Accessed */
3414 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3417 vmx->emulation_required = emulation_required(vcpu);
3420 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3422 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3424 *db = (ar >> 14) & 1;
3425 *l = (ar >> 13) & 1;
3428 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3430 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3431 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3434 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3436 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3437 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3440 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3442 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3443 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3446 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3448 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3449 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3452 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3454 struct kvm_segment var;
3457 vmx_get_segment(vcpu, &var, seg);
3459 if (seg == VCPU_SREG_CS)
3461 ar = vmx_segment_access_rights(&var);
3463 if (var.base != (var.selector << 4))
3465 if (var.limit != 0xffff)
3473 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3475 struct kvm_segment cs;
3476 unsigned int cs_rpl;
3478 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3479 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3483 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3487 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3488 if (cs.dpl > cs_rpl)
3491 if (cs.dpl != cs_rpl)
3497 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3501 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3503 struct kvm_segment ss;
3504 unsigned int ss_rpl;
3506 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3507 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3511 if (ss.type != 3 && ss.type != 7)
3515 if (ss.dpl != ss_rpl) /* DPL != RPL */
3523 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3525 struct kvm_segment var;
3528 vmx_get_segment(vcpu, &var, seg);
3529 rpl = var.selector & SEGMENT_RPL_MASK;
3537 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3538 if (var.dpl < rpl) /* DPL < RPL */
3542 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3548 static bool tr_valid(struct kvm_vcpu *vcpu)
3550 struct kvm_segment tr;
3552 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3556 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3558 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3566 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3568 struct kvm_segment ldtr;
3570 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3574 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3584 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3586 struct kvm_segment cs, ss;
3588 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3589 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3591 return ((cs.selector & SEGMENT_RPL_MASK) ==
3592 (ss.selector & SEGMENT_RPL_MASK));
3596 * Check if guest state is valid. Returns true if valid, false if
3598 * We assume that registers are always usable
3600 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3602 /* real mode guest state checks */
3603 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3604 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3606 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3608 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3610 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3612 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3614 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3617 /* protected mode guest state checks */
3618 if (!cs_ss_rpl_check(vcpu))
3620 if (!code_segment_valid(vcpu))
3622 if (!stack_segment_valid(vcpu))
3624 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3626 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3628 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3630 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3632 if (!tr_valid(vcpu))
3634 if (!ldtr_valid(vcpu))
3638 * - Add checks on RIP
3639 * - Add checks on RFLAGS
3645 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3647 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3651 for (i = 0; i < 3; i++) {
3652 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3656 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3657 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3661 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3667 static int init_rmode_identity_map(struct kvm *kvm)
3669 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3674 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3675 mutex_lock(&kvm->slots_lock);
3677 if (likely(kvm_vmx->ept_identity_pagetable_done))
3680 if (!kvm_vmx->ept_identity_map_addr)
3681 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3683 uaddr = __x86_set_memory_region(kvm,
3684 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3685 kvm_vmx->ept_identity_map_addr,
3687 if (IS_ERR(uaddr)) {
3692 /* Set up identity-mapping pagetable for EPT in real mode */
3693 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3694 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3695 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3696 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3701 kvm_vmx->ept_identity_pagetable_done = true;
3704 mutex_unlock(&kvm->slots_lock);
3708 static void seg_setup(int seg)
3710 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3713 vmcs_write16(sf->selector, 0);
3714 vmcs_writel(sf->base, 0);
3715 vmcs_write32(sf->limit, 0xffff);
3717 if (seg == VCPU_SREG_CS)
3718 ar |= 0x08; /* code segment */
3720 vmcs_write32(sf->ar_bytes, ar);
3723 static int alloc_apic_access_page(struct kvm *kvm)
3729 mutex_lock(&kvm->slots_lock);
3730 if (kvm->arch.apic_access_page_done)
3732 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3733 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3739 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3740 if (is_error_page(page)) {
3746 * Do not pin the page in memory, so that memory hot-unplug
3747 * is able to migrate it.
3750 kvm->arch.apic_access_page_done = true;
3752 mutex_unlock(&kvm->slots_lock);
3756 int allocate_vpid(void)
3762 spin_lock(&vmx_vpid_lock);
3763 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3764 if (vpid < VMX_NR_VPIDS)
3765 __set_bit(vpid, vmx_vpid_bitmap);
3768 spin_unlock(&vmx_vpid_lock);
3772 void free_vpid(int vpid)
3774 if (!enable_vpid || vpid == 0)
3776 spin_lock(&vmx_vpid_lock);
3777 __clear_bit(vpid, vmx_vpid_bitmap);
3778 spin_unlock(&vmx_vpid_lock);
3781 static void vmx_clear_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3783 int f = sizeof(unsigned long);
3786 __clear_bit(msr, msr_bitmap + 0x000 / f);
3787 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3788 __clear_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3791 static void vmx_clear_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3793 int f = sizeof(unsigned long);
3796 __clear_bit(msr, msr_bitmap + 0x800 / f);
3797 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3798 __clear_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3801 static void vmx_set_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3803 int f = sizeof(unsigned long);
3806 __set_bit(msr, msr_bitmap + 0x000 / f);
3807 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3808 __set_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3811 static void vmx_set_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3813 int f = sizeof(unsigned long);
3816 __set_bit(msr, msr_bitmap + 0x800 / f);
3817 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3818 __set_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3821 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3823 struct vcpu_vmx *vmx = to_vmx(vcpu);
3824 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3826 if (!cpu_has_vmx_msr_bitmap())
3829 if (static_branch_unlikely(&enable_evmcs))
3830 evmcs_touch_msr_bitmap();
3833 * Mark the desired intercept state in shadow bitmap, this is needed
3834 * for resync when the MSR filters change.
3836 if (is_valid_passthrough_msr(msr)) {
3837 int idx = possible_passthrough_msr_slot(msr);
3839 if (idx != -ENOENT) {
3840 if (type & MSR_TYPE_R)
3841 clear_bit(idx, vmx->shadow_msr_intercept.read);
3842 if (type & MSR_TYPE_W)
3843 clear_bit(idx, vmx->shadow_msr_intercept.write);
3847 if ((type & MSR_TYPE_R) &&
3848 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3849 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3850 type &= ~MSR_TYPE_R;
3853 if ((type & MSR_TYPE_W) &&
3854 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3855 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3856 type &= ~MSR_TYPE_W;
3859 if (type & MSR_TYPE_R)
3860 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3862 if (type & MSR_TYPE_W)
3863 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3866 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3868 struct vcpu_vmx *vmx = to_vmx(vcpu);
3869 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3871 if (!cpu_has_vmx_msr_bitmap())
3874 if (static_branch_unlikely(&enable_evmcs))
3875 evmcs_touch_msr_bitmap();
3878 * Mark the desired intercept state in shadow bitmap, this is needed
3879 * for resync when the MSR filter changes.
3881 if (is_valid_passthrough_msr(msr)) {
3882 int idx = possible_passthrough_msr_slot(msr);
3884 if (idx != -ENOENT) {
3885 if (type & MSR_TYPE_R)
3886 set_bit(idx, vmx->shadow_msr_intercept.read);
3887 if (type & MSR_TYPE_W)
3888 set_bit(idx, vmx->shadow_msr_intercept.write);
3892 if (type & MSR_TYPE_R)
3893 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3895 if (type & MSR_TYPE_W)
3896 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3899 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3903 if (cpu_has_secondary_exec_ctrls() &&
3904 (secondary_exec_controls_get(to_vmx(vcpu)) &
3905 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3906 mode |= MSR_BITMAP_MODE_X2APIC;
3907 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3908 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3914 static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
3916 unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3917 unsigned long read_intercept;
3920 read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3922 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3923 unsigned int read_idx = msr / BITS_PER_LONG;
3924 unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3926 msr_bitmap[read_idx] = read_intercept;
3927 msr_bitmap[write_idx] = ~0ul;
3931 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu, u8 mode)
3933 if (!cpu_has_vmx_msr_bitmap())
3936 vmx_reset_x2apic_msrs(vcpu, mode);
3939 * TPR reads and writes can be virtualized even if virtual interrupt
3940 * delivery is not in use.
3942 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
3943 !(mode & MSR_BITMAP_MODE_X2APIC));
3945 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3946 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
3947 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3948 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3952 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3954 struct vcpu_vmx *vmx = to_vmx(vcpu);
3955 u8 mode = vmx_msr_bitmap_mode(vcpu);
3956 u8 changed = mode ^ vmx->msr_bitmap_mode;
3961 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3962 vmx_update_msr_bitmap_x2apic(vcpu, mode);
3964 vmx->msr_bitmap_mode = mode;
3967 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
3969 struct vcpu_vmx *vmx = to_vmx(vcpu);
3970 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3973 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
3974 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
3975 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
3976 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
3977 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3978 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3979 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3983 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3985 struct vcpu_vmx *vmx = to_vmx(vcpu);
3990 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3991 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3992 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3995 rvi = vmx_get_rvi();
3997 vapic_page = vmx->nested.virtual_apic_map.hva;
3998 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
4000 return ((rvi & 0xf0) > (vppr & 0xf0));
4003 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
4005 struct vcpu_vmx *vmx = to_vmx(vcpu);
4009 * Set intercept permissions for all potentially passed through MSRs
4010 * again. They will automatically get filtered through the MSR filter,
4011 * so we are back in sync after this.
4013 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
4014 u32 msr = vmx_possible_passthrough_msrs[i];
4015 bool read = test_bit(i, vmx->shadow_msr_intercept.read);
4016 bool write = test_bit(i, vmx->shadow_msr_intercept.write);
4018 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_R, read);
4019 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_W, write);
4022 pt_update_intercept_for_msr(vcpu);
4023 vmx_update_msr_bitmap_x2apic(vcpu, vmx_msr_bitmap_mode(vcpu));
4026 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
4030 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
4032 if (vcpu->mode == IN_GUEST_MODE) {
4034 * The vector of interrupt to be delivered to vcpu had
4035 * been set in PIR before this function.
4037 * Following cases will be reached in this block, and
4038 * we always send a notification event in all cases as
4041 * Case 1: vcpu keeps in non-root mode. Sending a
4042 * notification event posts the interrupt to vcpu.
4044 * Case 2: vcpu exits to root mode and is still
4045 * runnable. PIR will be synced to vIRR before the
4046 * next vcpu entry. Sending a notification event in
4047 * this case has no effect, as vcpu is not in root
4050 * Case 3: vcpu exits to root mode and is blocked.
4051 * vcpu_block() has already synced PIR to vIRR and
4052 * never blocks vcpu if vIRR is not cleared. Therefore,
4053 * a blocked vcpu here does not wait for any requested
4054 * interrupts in PIR, and sending a notification event
4055 * which has no effect is safe here.
4058 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
4065 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4068 struct vcpu_vmx *vmx = to_vmx(vcpu);
4070 if (is_guest_mode(vcpu) &&
4071 vector == vmx->nested.posted_intr_nv) {
4073 * If a posted intr is not recognized by hardware,
4074 * we will accomplish it in the next vmentry.
4076 vmx->nested.pi_pending = true;
4077 kvm_make_request(KVM_REQ_EVENT, vcpu);
4078 /* the PIR and ON have been set by L1. */
4079 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
4080 kvm_vcpu_kick(vcpu);
4086 * Send interrupt to vcpu via posted interrupt way.
4087 * 1. If target vcpu is running(non-root mode), send posted interrupt
4088 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4089 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4090 * interrupt from PIR in next vmentry.
4092 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4094 struct vcpu_vmx *vmx = to_vmx(vcpu);
4097 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4101 if (!vcpu->arch.apicv_active)
4104 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4107 /* If a previous notification has sent the IPI, nothing to do. */
4108 if (pi_test_and_set_on(&vmx->pi_desc))
4111 if (vcpu != kvm_get_running_vcpu() &&
4112 !kvm_vcpu_trigger_posted_interrupt(vcpu, false))
4113 kvm_vcpu_kick(vcpu);
4119 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4120 * will not change in the lifetime of the guest.
4121 * Note that host-state that does change is set elsewhere. E.g., host-state
4122 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4124 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4128 unsigned long cr0, cr3, cr4;
4131 WARN_ON(cr0 & X86_CR0_TS);
4132 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4135 * Save the most likely value for this task's CR3 in the VMCS.
4136 * We can't use __get_current_cr3_fast() because we're not atomic.
4139 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4140 vmx->loaded_vmcs->host_state.cr3 = cr3;
4142 /* Save the most likely value for this task's CR4 in the VMCS. */
4143 cr4 = cr4_read_shadow();
4144 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4145 vmx->loaded_vmcs->host_state.cr4 = cr4;
4147 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4148 #ifdef CONFIG_X86_64
4150 * Load null selectors, so we can avoid reloading them in
4151 * vmx_prepare_switch_to_host(), in case userspace uses
4152 * the null selectors too (the expected case).
4154 vmcs_write16(HOST_DS_SELECTOR, 0);
4155 vmcs_write16(HOST_ES_SELECTOR, 0);
4157 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4158 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4160 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4161 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4163 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4165 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4167 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4168 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4169 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4170 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4172 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4173 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4174 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4177 if (cpu_has_load_ia32_efer())
4178 vmcs_write64(HOST_IA32_EFER, host_efer);
4181 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4183 struct kvm_vcpu *vcpu = &vmx->vcpu;
4185 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4186 ~vcpu->arch.cr4_guest_rsvd_bits;
4188 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PGE;
4189 if (is_guest_mode(&vmx->vcpu))
4190 vcpu->arch.cr4_guest_owned_bits &=
4191 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4192 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4195 u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4197 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4199 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4200 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4203 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4205 if (!enable_preemption_timer)
4206 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4208 return pin_based_exec_ctrl;
4211 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4213 struct vcpu_vmx *vmx = to_vmx(vcpu);
4215 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4216 if (cpu_has_secondary_exec_ctrls()) {
4217 if (kvm_vcpu_apicv_active(vcpu))
4218 secondary_exec_controls_setbit(vmx,
4219 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4220 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4222 secondary_exec_controls_clearbit(vmx,
4223 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4224 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4227 if (cpu_has_vmx_msr_bitmap())
4228 vmx_update_msr_bitmap(vcpu);
4231 u32 vmx_exec_control(struct vcpu_vmx *vmx)
4233 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4235 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4236 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4238 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4239 exec_control &= ~CPU_BASED_TPR_SHADOW;
4240 #ifdef CONFIG_X86_64
4241 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4242 CPU_BASED_CR8_LOAD_EXITING;
4246 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4247 CPU_BASED_CR3_LOAD_EXITING |
4248 CPU_BASED_INVLPG_EXITING;
4249 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4250 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4251 CPU_BASED_MONITOR_EXITING);
4252 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4253 exec_control &= ~CPU_BASED_HLT_EXITING;
4254 return exec_control;
4258 * Adjust a single secondary execution control bit to intercept/allow an
4259 * instruction in the guest. This is usually done based on whether or not a
4260 * feature has been exposed to the guest in order to correctly emulate faults.
4263 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4264 u32 control, bool enabled, bool exiting)
4267 * If the control is for an opt-in feature, clear the control if the
4268 * feature is not exposed to the guest, i.e. not enabled. If the
4269 * control is opt-out, i.e. an exiting control, clear the control if
4270 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4271 * disabled for the associated instruction. Note, the caller is
4272 * responsible presetting exec_control to set all supported bits.
4274 if (enabled == exiting)
4275 *exec_control &= ~control;
4278 * Update the nested MSR settings so that a nested VMM can/can't set
4279 * controls for features that are/aren't exposed to the guest.
4283 vmx->nested.msrs.secondary_ctls_high |= control;
4285 vmx->nested.msrs.secondary_ctls_high &= ~control;
4290 * Wrapper macro for the common case of adjusting a secondary execution control
4291 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4292 * verifies that the control is actually supported by KVM and hardware.
4294 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4298 if (cpu_has_vmx_##name()) { \
4299 __enabled = guest_cpuid_has(&(vmx)->vcpu, \
4300 X86_FEATURE_##feat_name); \
4301 vmx_adjust_secondary_exec_control(vmx, exec_control, \
4302 SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4306 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4307 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4308 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4310 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4311 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4313 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
4315 struct kvm_vcpu *vcpu = &vmx->vcpu;
4317 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4319 if (vmx_pt_mode_is_system())
4320 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4321 if (!cpu_need_virtualize_apic_accesses(vcpu))
4322 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4324 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4326 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4327 enable_unrestricted_guest = 0;
4329 if (!enable_unrestricted_guest)
4330 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4331 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4332 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4333 if (!kvm_vcpu_apicv_active(vcpu))
4334 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4335 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4336 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4338 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4339 * in vmx_set_cr4. */
4340 exec_control &= ~SECONDARY_EXEC_DESC;
4342 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4344 We can NOT enable shadow_vmcs here because we don't have yet
4347 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4350 * PML is enabled/disabled when dirty logging of memsmlots changes, but
4351 * it needs to be set here when dirty logging is already active, e.g.
4352 * if this vCPU was created after dirty logging was enabled.
4354 if (!vcpu->kvm->arch.cpu_dirty_logging_count)
4355 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4357 if (cpu_has_vmx_xsaves()) {
4358 /* Exposing XSAVES only when XSAVE is exposed */
4359 bool xsaves_enabled =
4360 boot_cpu_has(X86_FEATURE_XSAVE) &&
4361 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4362 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4364 vcpu->arch.xsaves_enabled = xsaves_enabled;
4366 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4367 SECONDARY_EXEC_XSAVES,
4368 xsaves_enabled, false);
4371 vmx_adjust_sec_exec_feature(vmx, &exec_control, rdtscp, RDTSCP);
4372 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4374 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4375 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4377 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4378 ENABLE_USR_WAIT_PAUSE, false);
4380 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4381 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4383 vmx->secondary_exec_control = exec_control;
4386 #define VMX_XSS_EXIT_BITMAP 0
4389 * Noting that the initialization of Guest-state Area of VMCS is in
4392 static void init_vmcs(struct vcpu_vmx *vmx)
4395 nested_vmx_set_vmcs_shadowing_bitmap();
4397 if (cpu_has_vmx_msr_bitmap())
4398 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4400 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4403 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4405 exec_controls_set(vmx, vmx_exec_control(vmx));
4407 if (cpu_has_secondary_exec_ctrls()) {
4408 vmx_compute_secondary_exec_control(vmx);
4409 secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
4412 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4413 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4414 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4415 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4416 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4418 vmcs_write16(GUEST_INTR_STATUS, 0);
4420 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4421 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4424 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4425 vmcs_write32(PLE_GAP, ple_gap);
4426 vmx->ple_window = ple_window;
4427 vmx->ple_window_dirty = true;
4430 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4431 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4432 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4434 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4435 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4436 vmx_set_constant_host_state(vmx);
4437 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4438 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4440 if (cpu_has_vmx_vmfunc())
4441 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4443 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4444 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4445 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4446 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4447 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4449 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4450 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4452 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4454 /* 22.2.1, 20.8.1 */
4455 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4457 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4458 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4460 set_cr4_guest_host_mask(vmx);
4463 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4465 if (cpu_has_vmx_xsaves())
4466 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4469 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4470 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4473 vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4475 if (vmx_pt_mode_is_host_guest()) {
4476 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4477 /* Bit[6~0] are forced to 1, writes are ignored. */
4478 vmx->pt_desc.guest.output_mask = 0x7F;
4479 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4483 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4485 struct vcpu_vmx *vmx = to_vmx(vcpu);
4486 struct msr_data apic_base_msr;
4489 vmx->rmode.vm86_active = 0;
4492 vmx->msr_ia32_umwait_control = 0;
4494 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4495 vmx->hv_deadline_tsc = -1;
4496 kvm_set_cr8(vcpu, 0);
4499 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4500 MSR_IA32_APICBASE_ENABLE;
4501 if (kvm_vcpu_is_reset_bsp(vcpu))
4502 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4503 apic_base_msr.host_initiated = true;
4504 kvm_set_apic_base(vcpu, &apic_base_msr);
4507 vmx_segment_cache_clear(vmx);
4509 seg_setup(VCPU_SREG_CS);
4510 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4511 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4513 seg_setup(VCPU_SREG_DS);
4514 seg_setup(VCPU_SREG_ES);
4515 seg_setup(VCPU_SREG_FS);
4516 seg_setup(VCPU_SREG_GS);
4517 seg_setup(VCPU_SREG_SS);
4519 vmcs_write16(GUEST_TR_SELECTOR, 0);
4520 vmcs_writel(GUEST_TR_BASE, 0);
4521 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4522 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4524 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4525 vmcs_writel(GUEST_LDTR_BASE, 0);
4526 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4527 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4530 vmcs_write32(GUEST_SYSENTER_CS, 0);
4531 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4532 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4533 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4536 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4537 kvm_rip_write(vcpu, 0xfff0);
4539 vmcs_writel(GUEST_GDTR_BASE, 0);
4540 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4542 vmcs_writel(GUEST_IDTR_BASE, 0);
4543 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4545 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4546 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4547 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4548 if (kvm_mpx_supported())
4549 vmcs_write64(GUEST_BNDCFGS, 0);
4553 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4555 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4556 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4557 if (cpu_need_tpr_shadow(vcpu))
4558 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4559 __pa(vcpu->arch.apic->regs));
4560 vmcs_write32(TPR_THRESHOLD, 0);
4563 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4565 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4566 vmx->vcpu.arch.cr0 = cr0;
4567 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4568 vmx_set_cr4(vcpu, 0);
4569 vmx_set_efer(vcpu, 0);
4571 vmx_update_exception_bitmap(vcpu);
4573 vpid_sync_context(vmx->vpid);
4575 vmx_clear_hlt(vcpu);
4578 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4580 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4583 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4586 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4587 vmx_enable_irq_window(vcpu);
4591 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4594 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4596 struct vcpu_vmx *vmx = to_vmx(vcpu);
4598 int irq = vcpu->arch.interrupt.nr;
4600 trace_kvm_inj_virq(irq);
4602 ++vcpu->stat.irq_injections;
4603 if (vmx->rmode.vm86_active) {
4605 if (vcpu->arch.interrupt.soft)
4606 inc_eip = vcpu->arch.event_exit_inst_len;
4607 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4610 intr = irq | INTR_INFO_VALID_MASK;
4611 if (vcpu->arch.interrupt.soft) {
4612 intr |= INTR_TYPE_SOFT_INTR;
4613 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4614 vmx->vcpu.arch.event_exit_inst_len);
4616 intr |= INTR_TYPE_EXT_INTR;
4617 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4619 vmx_clear_hlt(vcpu);
4622 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4624 struct vcpu_vmx *vmx = to_vmx(vcpu);
4628 * Tracking the NMI-blocked state in software is built upon
4629 * finding the next open IRQ window. This, in turn, depends on
4630 * well-behaving guests: They have to keep IRQs disabled at
4631 * least as long as the NMI handler runs. Otherwise we may
4632 * cause NMI nesting, maybe breaking the guest. But as this is
4633 * highly unlikely, we can live with the residual risk.
4635 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4636 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4639 ++vcpu->stat.nmi_injections;
4640 vmx->loaded_vmcs->nmi_known_unmasked = false;
4642 if (vmx->rmode.vm86_active) {
4643 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4647 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4648 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4650 vmx_clear_hlt(vcpu);
4653 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4655 struct vcpu_vmx *vmx = to_vmx(vcpu);
4659 return vmx->loaded_vmcs->soft_vnmi_blocked;
4660 if (vmx->loaded_vmcs->nmi_known_unmasked)
4662 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4663 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4667 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4669 struct vcpu_vmx *vmx = to_vmx(vcpu);
4672 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4673 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4674 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4677 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4679 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4680 GUEST_INTR_STATE_NMI);
4682 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4683 GUEST_INTR_STATE_NMI);
4687 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4689 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4692 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4695 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4696 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4697 GUEST_INTR_STATE_NMI));
4700 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4702 if (to_vmx(vcpu)->nested.nested_run_pending)
4705 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4706 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4709 return !vmx_nmi_blocked(vcpu);
4712 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4714 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4717 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4718 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4719 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4722 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4724 if (to_vmx(vcpu)->nested.nested_run_pending)
4728 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4729 * e.g. if the IRQ arrived asynchronously after checking nested events.
4731 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4734 return !vmx_interrupt_blocked(vcpu);
4737 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4741 if (enable_unrestricted_guest)
4744 mutex_lock(&kvm->slots_lock);
4745 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4747 mutex_unlock(&kvm->slots_lock);
4750 return PTR_ERR(ret);
4752 to_kvm_vmx(kvm)->tss_addr = addr;
4754 return init_rmode_tss(kvm, ret);
4757 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4759 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4763 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4768 * Update instruction length as we may reinject the exception
4769 * from user space while in guest debugging mode.
4771 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4772 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4773 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4777 return !(vcpu->guest_debug &
4778 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4792 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4793 int vec, u32 err_code)
4796 * Instruction with address size override prefix opcode 0x67
4797 * Cause the #SS fault with 0 error code in VM86 mode.
4799 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4800 if (kvm_emulate_instruction(vcpu, 0)) {
4801 if (vcpu->arch.halt_request) {
4802 vcpu->arch.halt_request = 0;
4803 return kvm_vcpu_halt(vcpu);
4811 * Forward all other exceptions that are valid in real mode.
4812 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4813 * the required debugging infrastructure rework.
4815 kvm_queue_exception(vcpu, vec);
4819 static int handle_machine_check(struct kvm_vcpu *vcpu)
4821 /* handled by vmx_vcpu_run() */
4826 * If the host has split lock detection disabled, then #AC is
4827 * unconditionally injected into the guest, which is the pre split lock
4828 * detection behaviour.
4830 * If the host has split lock detection enabled then #AC is
4831 * only injected into the guest when:
4832 * - Guest CPL == 3 (user mode)
4833 * - Guest has #AC detection enabled in CR0
4834 * - Guest EFLAGS has AC bit set
4836 static inline bool guest_inject_ac(struct kvm_vcpu *vcpu)
4838 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4841 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4842 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4845 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4847 struct vcpu_vmx *vmx = to_vmx(vcpu);
4848 struct kvm_run *kvm_run = vcpu->run;
4849 u32 intr_info, ex_no, error_code;
4850 unsigned long cr2, rip, dr6;
4853 vect_info = vmx->idt_vectoring_info;
4854 intr_info = vmx_get_intr_info(vcpu);
4856 if (is_machine_check(intr_info) || is_nmi(intr_info))
4857 return 1; /* handled by handle_exception_nmi_irqoff() */
4859 if (is_invalid_opcode(intr_info))
4860 return handle_ud(vcpu);
4863 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4864 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4866 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4867 WARN_ON_ONCE(!enable_vmware_backdoor);
4870 * VMware backdoor emulation on #GP interception only handles
4871 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4872 * error code on #GP.
4875 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4878 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4882 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4883 * MMIO, it is better to report an internal error.
4884 * See the comments in vmx_handle_exit.
4886 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4887 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4888 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4889 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4890 vcpu->run->internal.ndata = 4;
4891 vcpu->run->internal.data[0] = vect_info;
4892 vcpu->run->internal.data[1] = intr_info;
4893 vcpu->run->internal.data[2] = error_code;
4894 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
4898 if (is_page_fault(intr_info)) {
4899 cr2 = vmx_get_exit_qual(vcpu);
4900 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
4902 * EPT will cause page fault only if we need to
4903 * detect illegal GPAs.
4905 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
4906 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
4909 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4912 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4914 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4915 return handle_rmode_exception(vcpu, ex_no, error_code);
4919 dr6 = vmx_get_exit_qual(vcpu);
4920 if (!(vcpu->guest_debug &
4921 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4922 if (is_icebp(intr_info))
4923 WARN_ON(!skip_emulated_instruction(vcpu));
4925 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
4928 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
4929 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4933 * Update instruction length as we may reinject #BP from
4934 * user space while in guest debugging mode. Reading it for
4935 * #DB as well causes no harm, it is not used in that case.
4937 vmx->vcpu.arch.event_exit_inst_len =
4938 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4939 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4940 rip = kvm_rip_read(vcpu);
4941 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4942 kvm_run->debug.arch.exception = ex_no;
4945 if (guest_inject_ac(vcpu)) {
4946 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4951 * Handle split lock. Depending on detection mode this will
4952 * either warn and disable split lock detection for this
4953 * task or force SIGBUS on it.
4955 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4959 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4960 kvm_run->ex.exception = ex_no;
4961 kvm_run->ex.error_code = error_code;
4967 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4969 ++vcpu->stat.irq_exits;
4973 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4975 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4976 vcpu->mmio_needed = 0;
4980 static int handle_io(struct kvm_vcpu *vcpu)
4982 unsigned long exit_qualification;
4983 int size, in, string;
4986 exit_qualification = vmx_get_exit_qual(vcpu);
4987 string = (exit_qualification & 16) != 0;
4989 ++vcpu->stat.io_exits;
4992 return kvm_emulate_instruction(vcpu, 0);
4994 port = exit_qualification >> 16;
4995 size = (exit_qualification & 7) + 1;
4996 in = (exit_qualification & 8) != 0;
4998 return kvm_fast_pio(vcpu, size, port, in);
5002 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5005 * Patch in the VMCALL instruction:
5007 hypercall[0] = 0x0f;
5008 hypercall[1] = 0x01;
5009 hypercall[2] = 0xc1;
5012 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5013 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5015 if (is_guest_mode(vcpu)) {
5016 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5017 unsigned long orig_val = val;
5020 * We get here when L2 changed cr0 in a way that did not change
5021 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5022 * but did change L0 shadowed bits. So we first calculate the
5023 * effective cr0 value that L1 would like to write into the
5024 * hardware. It consists of the L2-owned bits from the new
5025 * value combined with the L1-owned bits from L1's guest_cr0.
5027 val = (val & ~vmcs12->cr0_guest_host_mask) |
5028 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5030 if (!nested_guest_cr0_valid(vcpu, val))
5033 if (kvm_set_cr0(vcpu, val))
5035 vmcs_writel(CR0_READ_SHADOW, orig_val);
5038 if (to_vmx(vcpu)->nested.vmxon &&
5039 !nested_host_cr0_valid(vcpu, val))
5042 return kvm_set_cr0(vcpu, val);
5046 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5048 if (is_guest_mode(vcpu)) {
5049 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5050 unsigned long orig_val = val;
5052 /* analogously to handle_set_cr0 */
5053 val = (val & ~vmcs12->cr4_guest_host_mask) |
5054 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5055 if (kvm_set_cr4(vcpu, val))
5057 vmcs_writel(CR4_READ_SHADOW, orig_val);
5060 return kvm_set_cr4(vcpu, val);
5063 static int handle_desc(struct kvm_vcpu *vcpu)
5065 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
5066 return kvm_emulate_instruction(vcpu, 0);
5069 static int handle_cr(struct kvm_vcpu *vcpu)
5071 unsigned long exit_qualification, val;
5077 exit_qualification = vmx_get_exit_qual(vcpu);
5078 cr = exit_qualification & 15;
5079 reg = (exit_qualification >> 8) & 15;
5080 switch ((exit_qualification >> 4) & 3) {
5081 case 0: /* mov to cr */
5082 val = kvm_register_read(vcpu, reg);
5083 trace_kvm_cr_write(cr, val);
5086 err = handle_set_cr0(vcpu, val);
5087 return kvm_complete_insn_gp(vcpu, err);
5089 WARN_ON_ONCE(enable_unrestricted_guest);
5090 err = kvm_set_cr3(vcpu, val);
5091 return kvm_complete_insn_gp(vcpu, err);
5093 err = handle_set_cr4(vcpu, val);
5094 return kvm_complete_insn_gp(vcpu, err);
5096 u8 cr8_prev = kvm_get_cr8(vcpu);
5098 err = kvm_set_cr8(vcpu, cr8);
5099 ret = kvm_complete_insn_gp(vcpu, err);
5100 if (lapic_in_kernel(vcpu))
5102 if (cr8_prev <= cr8)
5105 * TODO: we might be squashing a
5106 * KVM_GUESTDBG_SINGLESTEP-triggered
5107 * KVM_EXIT_DEBUG here.
5109 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5115 WARN_ONCE(1, "Guest should always own CR0.TS");
5116 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5117 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5118 return kvm_skip_emulated_instruction(vcpu);
5119 case 1: /*mov from cr*/
5122 WARN_ON_ONCE(enable_unrestricted_guest);
5123 val = kvm_read_cr3(vcpu);
5124 kvm_register_write(vcpu, reg, val);
5125 trace_kvm_cr_read(cr, val);
5126 return kvm_skip_emulated_instruction(vcpu);
5128 val = kvm_get_cr8(vcpu);
5129 kvm_register_write(vcpu, reg, val);
5130 trace_kvm_cr_read(cr, val);
5131 return kvm_skip_emulated_instruction(vcpu);
5135 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5136 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5137 kvm_lmsw(vcpu, val);
5139 return kvm_skip_emulated_instruction(vcpu);
5143 vcpu->run->exit_reason = 0;
5144 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5145 (int)(exit_qualification >> 4) & 3, cr);
5149 static int handle_dr(struct kvm_vcpu *vcpu)
5151 unsigned long exit_qualification;
5155 exit_qualification = vmx_get_exit_qual(vcpu);
5156 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5158 /* First, if DR does not exist, trigger UD */
5159 if (!kvm_require_dr(vcpu, dr))
5162 if (kvm_x86_ops.get_cpl(vcpu) > 0)
5165 dr7 = vmcs_readl(GUEST_DR7);
5168 * As the vm-exit takes precedence over the debug trap, we
5169 * need to emulate the latter, either for the host or the
5170 * guest debugging itself.
5172 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5173 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5174 vcpu->run->debug.arch.dr7 = dr7;
5175 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5176 vcpu->run->debug.arch.exception = DB_VECTOR;
5177 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5180 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5185 if (vcpu->guest_debug == 0) {
5186 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5189 * No more DR vmexits; force a reload of the debug registers
5190 * and reenter on this instruction. The next vmexit will
5191 * retrieve the full state of the debug registers.
5193 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5197 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5198 if (exit_qualification & TYPE_MOV_FROM_DR) {
5201 kvm_get_dr(vcpu, dr, &val);
5202 kvm_register_write(vcpu, reg, val);
5205 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5209 return kvm_complete_insn_gp(vcpu, err);
5212 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5214 get_debugreg(vcpu->arch.db[0], 0);
5215 get_debugreg(vcpu->arch.db[1], 1);
5216 get_debugreg(vcpu->arch.db[2], 2);
5217 get_debugreg(vcpu->arch.db[3], 3);
5218 get_debugreg(vcpu->arch.dr6, 6);
5219 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5221 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5222 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5225 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5227 vmcs_writel(GUEST_DR7, val);
5230 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5232 kvm_apic_update_ppr(vcpu);
5236 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5238 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5240 kvm_make_request(KVM_REQ_EVENT, vcpu);
5242 ++vcpu->stat.irq_window_exits;
5246 static int handle_invlpg(struct kvm_vcpu *vcpu)
5248 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5250 kvm_mmu_invlpg(vcpu, exit_qualification);
5251 return kvm_skip_emulated_instruction(vcpu);
5254 static int handle_apic_access(struct kvm_vcpu *vcpu)
5256 if (likely(fasteoi)) {
5257 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5258 int access_type, offset;
5260 access_type = exit_qualification & APIC_ACCESS_TYPE;
5261 offset = exit_qualification & APIC_ACCESS_OFFSET;
5263 * Sane guest uses MOV to write EOI, with written value
5264 * not cared. So make a short-circuit here by avoiding
5265 * heavy instruction emulation.
5267 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5268 (offset == APIC_EOI)) {
5269 kvm_lapic_set_eoi(vcpu);
5270 return kvm_skip_emulated_instruction(vcpu);
5273 return kvm_emulate_instruction(vcpu, 0);
5276 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5278 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5279 int vector = exit_qualification & 0xff;
5281 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5282 kvm_apic_set_eoi_accelerated(vcpu, vector);
5286 static int handle_apic_write(struct kvm_vcpu *vcpu)
5288 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5289 u32 offset = exit_qualification & 0xfff;
5291 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5292 kvm_apic_write_nodecode(vcpu, offset);
5296 static int handle_task_switch(struct kvm_vcpu *vcpu)
5298 struct vcpu_vmx *vmx = to_vmx(vcpu);
5299 unsigned long exit_qualification;
5300 bool has_error_code = false;
5303 int reason, type, idt_v, idt_index;
5305 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5306 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5307 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5309 exit_qualification = vmx_get_exit_qual(vcpu);
5311 reason = (u32)exit_qualification >> 30;
5312 if (reason == TASK_SWITCH_GATE && idt_v) {
5314 case INTR_TYPE_NMI_INTR:
5315 vcpu->arch.nmi_injected = false;
5316 vmx_set_nmi_mask(vcpu, true);
5318 case INTR_TYPE_EXT_INTR:
5319 case INTR_TYPE_SOFT_INTR:
5320 kvm_clear_interrupt_queue(vcpu);
5322 case INTR_TYPE_HARD_EXCEPTION:
5323 if (vmx->idt_vectoring_info &
5324 VECTORING_INFO_DELIVER_CODE_MASK) {
5325 has_error_code = true;
5327 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5330 case INTR_TYPE_SOFT_EXCEPTION:
5331 kvm_clear_exception_queue(vcpu);
5337 tss_selector = exit_qualification;
5339 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5340 type != INTR_TYPE_EXT_INTR &&
5341 type != INTR_TYPE_NMI_INTR))
5342 WARN_ON(!skip_emulated_instruction(vcpu));
5345 * TODO: What about debug traps on tss switch?
5346 * Are we supposed to inject them and update dr6?
5348 return kvm_task_switch(vcpu, tss_selector,
5349 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5350 reason, has_error_code, error_code);
5353 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5355 unsigned long exit_qualification;
5359 exit_qualification = vmx_get_exit_qual(vcpu);
5362 * EPT violation happened while executing iret from NMI,
5363 * "blocked by NMI" bit has to be set before next VM entry.
5364 * There are errata that may cause this bit to not be set:
5367 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5369 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5370 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5372 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5373 trace_kvm_page_fault(gpa, exit_qualification);
5375 /* Is it a read fault? */
5376 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5377 ? PFERR_USER_MASK : 0;
5378 /* Is it a write fault? */
5379 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5380 ? PFERR_WRITE_MASK : 0;
5381 /* Is it a fetch fault? */
5382 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5383 ? PFERR_FETCH_MASK : 0;
5384 /* ept page table entry is present? */
5385 error_code |= (exit_qualification &
5386 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5387 EPT_VIOLATION_EXECUTABLE))
5388 ? PFERR_PRESENT_MASK : 0;
5390 error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
5391 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5393 vcpu->arch.exit_qualification = exit_qualification;
5396 * Check that the GPA doesn't exceed physical memory limits, as that is
5397 * a guest page fault. We have to emulate the instruction here, because
5398 * if the illegal address is that of a paging structure, then
5399 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5400 * would also use advanced VM-exit information for EPT violations to
5401 * reconstruct the page fault error code.
5403 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5404 return kvm_emulate_instruction(vcpu, 0);
5406 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5409 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5413 if (!vmx_can_emulate_instruction(vcpu, NULL, 0))
5417 * A nested guest cannot optimize MMIO vmexits, because we have an
5418 * nGPA here instead of the required GPA.
5420 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5421 if (!is_guest_mode(vcpu) &&
5422 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5423 trace_kvm_fast_mmio(gpa);
5424 return kvm_skip_emulated_instruction(vcpu);
5427 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5430 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5432 WARN_ON_ONCE(!enable_vnmi);
5433 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5434 ++vcpu->stat.nmi_window_exits;
5435 kvm_make_request(KVM_REQ_EVENT, vcpu);
5440 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5442 struct vcpu_vmx *vmx = to_vmx(vcpu);
5443 bool intr_window_requested;
5444 unsigned count = 130;
5446 intr_window_requested = exec_controls_get(vmx) &
5447 CPU_BASED_INTR_WINDOW_EXITING;
5449 while (vmx->emulation_required && count-- != 0) {
5450 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5451 return handle_interrupt_window(&vmx->vcpu);
5453 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5456 if (!kvm_emulate_instruction(vcpu, 0))
5459 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5460 vcpu->arch.exception.pending) {
5461 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5462 vcpu->run->internal.suberror =
5463 KVM_INTERNAL_ERROR_EMULATION;
5464 vcpu->run->internal.ndata = 0;
5468 if (vcpu->arch.halt_request) {
5469 vcpu->arch.halt_request = 0;
5470 return kvm_vcpu_halt(vcpu);
5474 * Note, return 1 and not 0, vcpu_run() will invoke
5475 * xfer_to_guest_mode() which will create a proper return
5478 if (__xfer_to_guest_mode_work_pending())
5485 static void grow_ple_window(struct kvm_vcpu *vcpu)
5487 struct vcpu_vmx *vmx = to_vmx(vcpu);
5488 unsigned int old = vmx->ple_window;
5490 vmx->ple_window = __grow_ple_window(old, ple_window,
5494 if (vmx->ple_window != old) {
5495 vmx->ple_window_dirty = true;
5496 trace_kvm_ple_window_update(vcpu->vcpu_id,
5497 vmx->ple_window, old);
5501 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5503 struct vcpu_vmx *vmx = to_vmx(vcpu);
5504 unsigned int old = vmx->ple_window;
5506 vmx->ple_window = __shrink_ple_window(old, ple_window,
5510 if (vmx->ple_window != old) {
5511 vmx->ple_window_dirty = true;
5512 trace_kvm_ple_window_update(vcpu->vcpu_id,
5513 vmx->ple_window, old);
5518 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5519 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5521 static int handle_pause(struct kvm_vcpu *vcpu)
5523 if (!kvm_pause_in_guest(vcpu->kvm))
5524 grow_ple_window(vcpu);
5527 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5528 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5529 * never set PAUSE_EXITING and just set PLE if supported,
5530 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5532 kvm_vcpu_on_spin(vcpu, true);
5533 return kvm_skip_emulated_instruction(vcpu);
5536 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5541 static int handle_invpcid(struct kvm_vcpu *vcpu)
5543 u32 vmx_instruction_info;
5551 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5552 kvm_queue_exception(vcpu, UD_VECTOR);
5556 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5557 type = kvm_register_read(vcpu, (vmx_instruction_info >> 28) & 0xf);
5560 kvm_inject_gp(vcpu, 0);
5564 /* According to the Intel instruction reference, the memory operand
5565 * is read even if it isn't needed (e.g., for type==all)
5567 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5568 vmx_instruction_info, false,
5569 sizeof(operand), &gva))
5572 return kvm_handle_invpcid(vcpu, type, gva);
5575 static int handle_pml_full(struct kvm_vcpu *vcpu)
5577 unsigned long exit_qualification;
5579 trace_kvm_pml_full(vcpu->vcpu_id);
5581 exit_qualification = vmx_get_exit_qual(vcpu);
5584 * PML buffer FULL happened while executing iret from NMI,
5585 * "blocked by NMI" bit has to be set before next VM entry.
5587 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5589 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5590 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5591 GUEST_INTR_STATE_NMI);
5594 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5595 * here.., and there's no userspace involvement needed for PML.
5600 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5602 struct vcpu_vmx *vmx = to_vmx(vcpu);
5604 if (!vmx->req_immediate_exit &&
5605 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5606 kvm_lapic_expired_hv_timer(vcpu);
5607 return EXIT_FASTPATH_REENTER_GUEST;
5610 return EXIT_FASTPATH_NONE;
5613 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5615 handle_fastpath_preemption_timer(vcpu);
5620 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5621 * are overwritten by nested_vmx_setup() when nested=1.
5623 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5625 kvm_queue_exception(vcpu, UD_VECTOR);
5629 #ifndef CONFIG_X86_SGX_KVM
5630 static int handle_encls(struct kvm_vcpu *vcpu)
5633 * SGX virtualization is disabled. There is no software enable bit for
5634 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
5635 * the guest from executing ENCLS (when SGX is supported by hardware).
5637 kvm_queue_exception(vcpu, UD_VECTOR);
5640 #endif /* CONFIG_X86_SGX_KVM */
5642 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
5644 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
5645 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
5650 * The exit handlers return 1 if the exit was handled fully and guest execution
5651 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5652 * to be done to userspace and return 0.
5654 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5655 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5656 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5657 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5658 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5659 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5660 [EXIT_REASON_CR_ACCESS] = handle_cr,
5661 [EXIT_REASON_DR_ACCESS] = handle_dr,
5662 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5663 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5664 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5665 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5666 [EXIT_REASON_HLT] = kvm_emulate_halt,
5667 [EXIT_REASON_INVD] = kvm_emulate_invd,
5668 [EXIT_REASON_INVLPG] = handle_invlpg,
5669 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
5670 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
5671 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5672 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5673 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5674 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5675 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5676 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5677 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5678 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5679 [EXIT_REASON_VMON] = handle_vmx_instruction,
5680 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5681 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5682 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5683 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5684 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
5685 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
5686 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5687 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5688 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5689 [EXIT_REASON_LDTR_TR] = handle_desc,
5690 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5691 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5692 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5693 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
5694 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5695 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
5696 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5697 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5698 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
5699 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
5700 [EXIT_REASON_PML_FULL] = handle_pml_full,
5701 [EXIT_REASON_INVPCID] = handle_invpcid,
5702 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5703 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5704 [EXIT_REASON_ENCLS] = handle_encls,
5705 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
5708 static const int kvm_vmx_max_exit_handlers =
5709 ARRAY_SIZE(kvm_vmx_exit_handlers);
5711 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2,
5712 u32 *intr_info, u32 *error_code)
5714 struct vcpu_vmx *vmx = to_vmx(vcpu);
5716 *info1 = vmx_get_exit_qual(vcpu);
5717 if (!(vmx->exit_reason.failed_vmentry)) {
5718 *info2 = vmx->idt_vectoring_info;
5719 *intr_info = vmx_get_intr_info(vcpu);
5720 if (is_exception_with_error_code(*intr_info))
5721 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5731 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5734 __free_page(vmx->pml_pg);
5739 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5741 struct vcpu_vmx *vmx = to_vmx(vcpu);
5745 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5747 /* Do nothing if PML buffer is empty */
5748 if (pml_idx == (PML_ENTITY_NUM - 1))
5751 /* PML index always points to next available PML buffer entity */
5752 if (pml_idx >= PML_ENTITY_NUM)
5757 pml_buf = page_address(vmx->pml_pg);
5758 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5761 gpa = pml_buf[pml_idx];
5762 WARN_ON(gpa & (PAGE_SIZE - 1));
5763 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5766 /* reset PML index */
5767 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5770 static void vmx_dump_sel(char *name, uint32_t sel)
5772 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5773 name, vmcs_read16(sel),
5774 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5775 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5776 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5779 static void vmx_dump_dtsel(char *name, uint32_t limit)
5781 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5782 name, vmcs_read32(limit),
5783 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5786 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
5789 struct vmx_msr_entry *e;
5791 pr_err("MSR %s:\n", name);
5792 for (i = 0, e = m->val; i < m->nr; ++i, ++e)
5793 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
5796 void dump_vmcs(struct kvm_vcpu *vcpu)
5798 struct vcpu_vmx *vmx = to_vmx(vcpu);
5799 u32 vmentry_ctl, vmexit_ctl;
5800 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5804 if (!dump_invalid_vmcs) {
5805 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5809 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5810 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5811 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5812 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5813 cr4 = vmcs_readl(GUEST_CR4);
5814 secondary_exec_control = 0;
5815 if (cpu_has_secondary_exec_ctrls())
5816 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5818 pr_err("*** Guest State ***\n");
5819 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5820 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5821 vmcs_readl(CR0_GUEST_HOST_MASK));
5822 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5823 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5824 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5825 if (cpu_has_vmx_ept()) {
5826 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5827 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5828 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5829 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5831 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5832 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5833 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5834 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5835 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5836 vmcs_readl(GUEST_SYSENTER_ESP),
5837 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5838 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5839 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5840 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5841 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5842 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5843 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5844 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5845 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5846 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5847 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5848 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
5849 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
5850 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
5851 else if (efer_slot >= 0)
5852 pr_err("EFER= 0x%016llx (autoload)\n",
5853 vmx->msr_autoload.guest.val[efer_slot].value);
5854 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
5855 pr_err("EFER= 0x%016llx (effective)\n",
5856 vcpu->arch.efer | (EFER_LMA | EFER_LME));
5858 pr_err("EFER= 0x%016llx (effective)\n",
5859 vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
5860 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
5861 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
5862 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5863 vmcs_read64(GUEST_IA32_DEBUGCTL),
5864 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5865 if (cpu_has_load_perf_global_ctrl() &&
5866 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5867 pr_err("PerfGlobCtl = 0x%016llx\n",
5868 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5869 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5870 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5871 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5872 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5873 vmcs_read32(GUEST_ACTIVITY_STATE));
5874 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5875 pr_err("InterruptStatus = %04x\n",
5876 vmcs_read16(GUEST_INTR_STATUS));
5877 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
5878 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
5879 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
5880 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
5882 pr_err("*** Host State ***\n");
5883 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5884 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5885 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5886 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5887 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5888 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5889 vmcs_read16(HOST_TR_SELECTOR));
5890 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5891 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5892 vmcs_readl(HOST_TR_BASE));
5893 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5894 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5895 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5896 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5897 vmcs_readl(HOST_CR4));
5898 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5899 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5900 vmcs_read32(HOST_IA32_SYSENTER_CS),
5901 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5902 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
5903 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
5904 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
5905 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
5906 if (cpu_has_load_perf_global_ctrl() &&
5907 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5908 pr_err("PerfGlobCtl = 0x%016llx\n",
5909 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5910 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
5911 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
5913 pr_err("*** Control State ***\n");
5914 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5915 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5916 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5917 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5918 vmcs_read32(EXCEPTION_BITMAP),
5919 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5920 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5921 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5922 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5923 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5924 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5925 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5926 vmcs_read32(VM_EXIT_INTR_INFO),
5927 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5928 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5929 pr_err(" reason=%08x qualification=%016lx\n",
5930 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5931 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5932 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5933 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5934 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5935 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5936 pr_err("TSC Multiplier = 0x%016llx\n",
5937 vmcs_read64(TSC_MULTIPLIER));
5938 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5939 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5940 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5941 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5943 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5944 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5945 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5946 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5948 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5949 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5950 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5951 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5952 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5953 pr_err("PLE Gap=%08x Window=%08x\n",
5954 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5955 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5956 pr_err("Virtual processor ID = 0x%04x\n",
5957 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5961 * The guest has exited. See if we can fix it or if we need userspace
5964 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
5966 struct vcpu_vmx *vmx = to_vmx(vcpu);
5967 union vmx_exit_reason exit_reason = vmx->exit_reason;
5968 u32 vectoring_info = vmx->idt_vectoring_info;
5969 u16 exit_handler_index;
5972 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5973 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5974 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5975 * mode as if vcpus is in root mode, the PML buffer must has been
5976 * flushed already. Note, PML is never enabled in hardware while
5979 if (enable_pml && !is_guest_mode(vcpu))
5980 vmx_flush_pml_buffer(vcpu);
5983 * We should never reach this point with a pending nested VM-Enter, and
5984 * more specifically emulation of L2 due to invalid guest state (see
5985 * below) should never happen as that means we incorrectly allowed a
5986 * nested VM-Enter with an invalid vmcs12.
5988 WARN_ON_ONCE(vmx->nested.nested_run_pending);
5990 /* If guest state is invalid, start emulating */
5991 if (vmx->emulation_required)
5992 return handle_invalid_guest_state(vcpu);
5994 if (is_guest_mode(vcpu)) {
5996 * PML is never enabled when running L2, bail immediately if a
5997 * PML full exit occurs as something is horribly wrong.
5999 if (exit_reason.basic == EXIT_REASON_PML_FULL)
6000 goto unexpected_vmexit;
6003 * The host physical addresses of some pages of guest memory
6004 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6005 * Page). The CPU may write to these pages via their host
6006 * physical address while L2 is running, bypassing any
6007 * address-translation-based dirty tracking (e.g. EPT write
6010 * Mark them dirty on every exit from L2 to prevent them from
6011 * getting out of sync with dirty tracking.
6013 nested_mark_vmcs12_pages_dirty(vcpu);
6015 if (nested_vmx_reflect_vmexit(vcpu))
6019 if (exit_reason.failed_vmentry) {
6021 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6022 vcpu->run->fail_entry.hardware_entry_failure_reason
6024 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6028 if (unlikely(vmx->fail)) {
6030 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6031 vcpu->run->fail_entry.hardware_entry_failure_reason
6032 = vmcs_read32(VM_INSTRUCTION_ERROR);
6033 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6039 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6040 * delivery event since it indicates guest is accessing MMIO.
6041 * The vm-exit can be triggered again after return to guest that
6042 * will cause infinite loop.
6044 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6045 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6046 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6047 exit_reason.basic != EXIT_REASON_PML_FULL &&
6048 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6049 exit_reason.basic != EXIT_REASON_TASK_SWITCH)) {
6052 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6053 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6054 vcpu->run->internal.data[0] = vectoring_info;
6055 vcpu->run->internal.data[1] = exit_reason.full;
6056 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6057 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6058 vcpu->run->internal.data[ndata++] =
6059 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6061 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6062 vcpu->run->internal.ndata = ndata;
6066 if (unlikely(!enable_vnmi &&
6067 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6068 if (!vmx_interrupt_blocked(vcpu)) {
6069 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6070 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6071 vcpu->arch.nmi_pending) {
6073 * This CPU don't support us in finding the end of an
6074 * NMI-blocked window if the guest runs with IRQs
6075 * disabled. So we pull the trigger after 1 s of
6076 * futile waiting, but inform the user about this.
6078 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6079 "state on VCPU %d after 1 s timeout\n",
6080 __func__, vcpu->vcpu_id);
6081 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6085 if (exit_fastpath != EXIT_FASTPATH_NONE)
6088 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6089 goto unexpected_vmexit;
6090 #ifdef CONFIG_RETPOLINE
6091 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6092 return kvm_emulate_wrmsr(vcpu);
6093 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6094 return handle_preemption_timer(vcpu);
6095 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6096 return handle_interrupt_window(vcpu);
6097 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6098 return handle_external_interrupt(vcpu);
6099 else if (exit_reason.basic == EXIT_REASON_HLT)
6100 return kvm_emulate_halt(vcpu);
6101 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6102 return handle_ept_misconfig(vcpu);
6105 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6106 kvm_vmx_max_exit_handlers);
6107 if (!kvm_vmx_exit_handlers[exit_handler_index])
6108 goto unexpected_vmexit;
6110 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6113 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6116 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6117 vcpu->run->internal.suberror =
6118 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6119 vcpu->run->internal.ndata = 2;
6120 vcpu->run->internal.data[0] = exit_reason.full;
6121 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6125 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6127 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6130 * Even when current exit reason is handled by KVM internally, we
6131 * still need to exit to user space when bus lock detected to inform
6132 * that there is a bus lock in guest.
6134 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6136 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6138 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6145 * Software based L1D cache flush which is used when microcode providing
6146 * the cache control MSR is not loaded.
6148 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6149 * flush it is required to read in 64 KiB because the replacement algorithm
6150 * is not exactly LRU. This could be sized at runtime via topology
6151 * information but as all relevant affected CPUs have 32KiB L1D cache size
6152 * there is no point in doing so.
6154 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6156 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6159 * This code is only executed when the the flush mode is 'cond' or
6162 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6166 * Clear the per-vcpu flush bit, it gets set again
6167 * either from vcpu_run() or from one of the unsafe
6170 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6171 vcpu->arch.l1tf_flush_l1d = false;
6174 * Clear the per-cpu flush bit, it gets set again from
6175 * the interrupt handlers.
6177 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6178 kvm_clear_cpu_l1tf_flush_l1d();
6184 vcpu->stat.l1d_flush++;
6186 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6187 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6192 /* First ensure the pages are in the TLB */
6193 "xorl %%eax, %%eax\n"
6194 ".Lpopulate_tlb:\n\t"
6195 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6196 "addl $4096, %%eax\n\t"
6197 "cmpl %%eax, %[size]\n\t"
6198 "jne .Lpopulate_tlb\n\t"
6199 "xorl %%eax, %%eax\n\t"
6201 /* Now fill the cache */
6202 "xorl %%eax, %%eax\n"
6204 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6205 "addl $64, %%eax\n\t"
6206 "cmpl %%eax, %[size]\n\t"
6207 "jne .Lfill_cache\n\t"
6209 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6211 : "eax", "ebx", "ecx", "edx");
6214 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6216 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6219 if (is_guest_mode(vcpu) &&
6220 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6223 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6224 if (is_guest_mode(vcpu))
6225 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6227 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6230 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6232 struct vcpu_vmx *vmx = to_vmx(vcpu);
6233 u32 sec_exec_control;
6235 if (!lapic_in_kernel(vcpu))
6238 if (!flexpriority_enabled &&
6239 !cpu_has_vmx_virtualize_x2apic_mode())
6242 /* Postpone execution until vmcs01 is the current VMCS. */
6243 if (is_guest_mode(vcpu)) {
6244 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6248 sec_exec_control = secondary_exec_controls_get(vmx);
6249 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6250 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6252 switch (kvm_get_apic_mode(vcpu)) {
6253 case LAPIC_MODE_INVALID:
6254 WARN_ONCE(true, "Invalid local APIC state");
6255 case LAPIC_MODE_DISABLED:
6257 case LAPIC_MODE_XAPIC:
6258 if (flexpriority_enabled) {
6260 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6261 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6264 * Flush the TLB, reloading the APIC access page will
6265 * only do so if its physical address has changed, but
6266 * the guest may have inserted a non-APIC mapping into
6267 * the TLB while the APIC access page was disabled.
6269 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6272 case LAPIC_MODE_X2APIC:
6273 if (cpu_has_vmx_virtualize_x2apic_mode())
6275 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6278 secondary_exec_controls_set(vmx, sec_exec_control);
6280 vmx_update_msr_bitmap(vcpu);
6283 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6287 /* Defer reload until vmcs01 is the current VMCS. */
6288 if (is_guest_mode(vcpu)) {
6289 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6293 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6294 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6297 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6298 if (is_error_page(page))
6301 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6302 vmx_flush_tlb_current(vcpu);
6305 * Do not pin apic access page in memory, the MMU notifier
6306 * will call us again if it is migrated or swapped out.
6311 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6319 status = vmcs_read16(GUEST_INTR_STATUS);
6321 if (max_isr != old) {
6323 status |= max_isr << 8;
6324 vmcs_write16(GUEST_INTR_STATUS, status);
6328 static void vmx_set_rvi(int vector)
6336 status = vmcs_read16(GUEST_INTR_STATUS);
6337 old = (u8)status & 0xff;
6338 if ((u8)vector != old) {
6340 status |= (u8)vector;
6341 vmcs_write16(GUEST_INTR_STATUS, status);
6345 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6348 * When running L2, updating RVI is only relevant when
6349 * vmcs12 virtual-interrupt-delivery enabled.
6350 * However, it can be enabled only when L1 also
6351 * intercepts external-interrupts and in that case
6352 * we should not update vmcs02 RVI but instead intercept
6353 * interrupt. Therefore, do nothing when running L2.
6355 if (!is_guest_mode(vcpu))
6356 vmx_set_rvi(max_irr);
6359 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6361 struct vcpu_vmx *vmx = to_vmx(vcpu);
6363 bool max_irr_updated;
6365 WARN_ON(!vcpu->arch.apicv_active);
6366 if (pi_test_on(&vmx->pi_desc)) {
6367 pi_clear_on(&vmx->pi_desc);
6369 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6370 * But on x86 this is just a compiler barrier anyway.
6372 smp_mb__after_atomic();
6374 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6377 * If we are running L2 and L1 has a new pending interrupt
6378 * which can be injected, we should re-evaluate
6379 * what should be done with this new L1 interrupt.
6380 * If L1 intercepts external-interrupts, we should
6381 * exit from L2 to L1. Otherwise, interrupt should be
6382 * delivered directly to L2.
6384 if (is_guest_mode(vcpu) && max_irr_updated) {
6385 if (nested_exit_on_intr(vcpu))
6386 kvm_vcpu_exiting_guest_mode(vcpu);
6388 kvm_make_request(KVM_REQ_EVENT, vcpu);
6391 max_irr = kvm_lapic_find_highest_irr(vcpu);
6393 vmx_hwapic_irr_update(vcpu, max_irr);
6397 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6399 if (!kvm_vcpu_apicv_active(vcpu))
6402 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6403 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6404 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6405 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6408 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6410 struct vcpu_vmx *vmx = to_vmx(vcpu);
6412 pi_clear_on(&vmx->pi_desc);
6413 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6416 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6418 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu, u32 intr_info)
6420 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6421 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6423 kvm_before_interrupt(vcpu);
6424 vmx_do_interrupt_nmi_irqoff(gate_offset(desc));
6425 kvm_after_interrupt(vcpu);
6428 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6430 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6432 /* if exit due to PF check for async PF */
6433 if (is_page_fault(intr_info))
6434 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6435 /* Handle machine checks before interrupts are enabled */
6436 else if (is_machine_check(intr_info))
6437 kvm_machine_check();
6438 /* We need to handle NMIs before interrupts are enabled */
6439 else if (is_nmi(intr_info))
6440 handle_interrupt_nmi_irqoff(&vmx->vcpu, intr_info);
6443 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6445 u32 intr_info = vmx_get_intr_info(vcpu);
6447 if (WARN_ONCE(!is_external_intr(intr_info),
6448 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6451 handle_interrupt_nmi_irqoff(vcpu, intr_info);
6454 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6456 struct vcpu_vmx *vmx = to_vmx(vcpu);
6458 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6459 handle_external_interrupt_irqoff(vcpu);
6460 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
6461 handle_exception_nmi_irqoff(vmx);
6465 * The kvm parameter can be NULL (module initialization, or invocation before
6466 * VM creation). Be sure to check the kvm parameter before using it.
6468 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
6471 case MSR_IA32_SMBASE:
6473 * We cannot do SMM unless we can run the guest in big
6476 return enable_unrestricted_guest || emulate_invalid_guest_state;
6477 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6479 case MSR_AMD64_VIRT_SPEC_CTRL:
6480 /* This is AMD only. */
6487 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6492 bool idtv_info_valid;
6494 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6497 if (vmx->loaded_vmcs->nmi_known_unmasked)
6500 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6501 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6502 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6504 * SDM 3: 27.7.1.2 (September 2008)
6505 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6506 * a guest IRET fault.
6507 * SDM 3: 23.2.2 (September 2008)
6508 * Bit 12 is undefined in any of the following cases:
6509 * If the VM exit sets the valid bit in the IDT-vectoring
6510 * information field.
6511 * If the VM exit is due to a double fault.
6513 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6514 vector != DF_VECTOR && !idtv_info_valid)
6515 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6516 GUEST_INTR_STATE_NMI);
6518 vmx->loaded_vmcs->nmi_known_unmasked =
6519 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6520 & GUEST_INTR_STATE_NMI);
6521 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6522 vmx->loaded_vmcs->vnmi_blocked_time +=
6523 ktime_to_ns(ktime_sub(ktime_get(),
6524 vmx->loaded_vmcs->entry_time));
6527 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6528 u32 idt_vectoring_info,
6529 int instr_len_field,
6530 int error_code_field)
6534 bool idtv_info_valid;
6536 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6538 vcpu->arch.nmi_injected = false;
6539 kvm_clear_exception_queue(vcpu);
6540 kvm_clear_interrupt_queue(vcpu);
6542 if (!idtv_info_valid)
6545 kvm_make_request(KVM_REQ_EVENT, vcpu);
6547 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6548 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6551 case INTR_TYPE_NMI_INTR:
6552 vcpu->arch.nmi_injected = true;
6554 * SDM 3: 27.7.1.2 (September 2008)
6555 * Clear bit "block by NMI" before VM entry if a NMI
6558 vmx_set_nmi_mask(vcpu, false);
6560 case INTR_TYPE_SOFT_EXCEPTION:
6561 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6563 case INTR_TYPE_HARD_EXCEPTION:
6564 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6565 u32 err = vmcs_read32(error_code_field);
6566 kvm_requeue_exception_e(vcpu, vector, err);
6568 kvm_requeue_exception(vcpu, vector);
6570 case INTR_TYPE_SOFT_INTR:
6571 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6573 case INTR_TYPE_EXT_INTR:
6574 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6581 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6583 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6584 VM_EXIT_INSTRUCTION_LEN,
6585 IDT_VECTORING_ERROR_CODE);
6588 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6590 __vmx_complete_interrupts(vcpu,
6591 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6592 VM_ENTRY_INSTRUCTION_LEN,
6593 VM_ENTRY_EXCEPTION_ERROR_CODE);
6595 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6598 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6601 struct perf_guest_switch_msr *msrs;
6603 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
6604 msrs = perf_guest_get_msrs(&nr_msrs);
6608 for (i = 0; i < nr_msrs; i++)
6609 if (msrs[i].host == msrs[i].guest)
6610 clear_atomic_switch_msr(vmx, msrs[i].msr);
6612 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6613 msrs[i].host, false);
6616 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6618 struct vcpu_vmx *vmx = to_vmx(vcpu);
6622 if (vmx->req_immediate_exit) {
6623 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6624 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6625 } else if (vmx->hv_deadline_tsc != -1) {
6627 if (vmx->hv_deadline_tsc > tscl)
6628 /* set_hv_timer ensures the delta fits in 32-bits */
6629 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6630 cpu_preemption_timer_multi);
6634 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6635 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6636 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6637 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6638 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6642 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6644 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6645 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6646 vmcs_writel(HOST_RSP, host_rsp);
6650 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6652 switch (to_vmx(vcpu)->exit_reason.basic) {
6653 case EXIT_REASON_MSR_WRITE:
6654 return handle_fastpath_set_msr_irqoff(vcpu);
6655 case EXIT_REASON_PREEMPTION_TIMER:
6656 return handle_fastpath_preemption_timer(vcpu);
6658 return EXIT_FASTPATH_NONE;
6662 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6663 struct vcpu_vmx *vmx)
6666 * VMENTER enables interrupts (host state), but the kernel state is
6667 * interrupts disabled when this is invoked. Also tell RCU about
6668 * it. This is the same logic as for exit_to_user_mode().
6670 * This ensures that e.g. latency analysis on the host observes
6671 * guest mode as interrupt enabled.
6673 * guest_enter_irqoff() informs context tracking about the
6674 * transition to guest mode and if enabled adjusts RCU state
6677 instrumentation_begin();
6678 trace_hardirqs_on_prepare();
6679 lockdep_hardirqs_on_prepare(CALLER_ADDR0);
6680 instrumentation_end();
6682 guest_enter_irqoff();
6683 lockdep_hardirqs_on(CALLER_ADDR0);
6685 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6686 if (static_branch_unlikely(&vmx_l1d_should_flush))
6687 vmx_l1d_flush(vcpu);
6688 else if (static_branch_unlikely(&mds_user_clear))
6689 mds_clear_cpu_buffers();
6691 if (vcpu->arch.cr2 != native_read_cr2())
6692 native_write_cr2(vcpu->arch.cr2);
6694 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6695 vmx->loaded_vmcs->launched);
6697 vcpu->arch.cr2 = native_read_cr2();
6700 * VMEXIT disables interrupts (host state), but tracing and lockdep
6701 * have them in state 'on' as recorded before entering guest mode.
6702 * Same as enter_from_user_mode().
6704 * guest_exit_irqoff() restores host context and reinstates RCU if
6705 * enabled and required.
6707 * This needs to be done before the below as native_read_msr()
6708 * contains a tracepoint and x86_spec_ctrl_restore_host() calls
6709 * into world and some more.
6711 lockdep_hardirqs_off(CALLER_ADDR0);
6712 guest_exit_irqoff();
6714 instrumentation_begin();
6715 trace_hardirqs_off_finish();
6716 instrumentation_end();
6719 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6721 struct vcpu_vmx *vmx = to_vmx(vcpu);
6722 unsigned long cr3, cr4;
6724 /* Record the guest's net vcpu time for enforced NMI injections. */
6725 if (unlikely(!enable_vnmi &&
6726 vmx->loaded_vmcs->soft_vnmi_blocked))
6727 vmx->loaded_vmcs->entry_time = ktime_get();
6729 /* Don't enter VMX if guest state is invalid, let the exit handler
6730 start emulation until we arrive back to a valid state */
6731 if (vmx->emulation_required)
6732 return EXIT_FASTPATH_NONE;
6734 trace_kvm_entry(vcpu);
6736 if (vmx->ple_window_dirty) {
6737 vmx->ple_window_dirty = false;
6738 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6742 * We did this in prepare_switch_to_guest, because it needs to
6743 * be within srcu_read_lock.
6745 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6747 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6748 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6749 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6750 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6752 cr3 = __get_current_cr3_fast();
6753 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6754 vmcs_writel(HOST_CR3, cr3);
6755 vmx->loaded_vmcs->host_state.cr3 = cr3;
6758 cr4 = cr4_read_shadow();
6759 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6760 vmcs_writel(HOST_CR4, cr4);
6761 vmx->loaded_vmcs->host_state.cr4 = cr4;
6764 /* When single-stepping over STI and MOV SS, we must clear the
6765 * corresponding interruptibility bits in the guest state. Otherwise
6766 * vmentry fails as it then expects bit 14 (BS) in pending debug
6767 * exceptions being set, but that's not correct for the guest debugging
6769 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6770 vmx_set_interrupt_shadow(vcpu, 0);
6772 kvm_load_guest_xsave_state(vcpu);
6774 pt_guest_enter(vmx);
6776 atomic_switch_perf_msrs(vmx);
6777 if (intel_pmu_lbr_is_enabled(vcpu))
6778 vmx_passthrough_lbr_msrs(vcpu);
6780 if (enable_preemption_timer)
6781 vmx_update_hv_timer(vcpu);
6783 kvm_wait_lapic_expire(vcpu);
6786 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6787 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6788 * is no need to worry about the conditional branch over the wrmsr
6789 * being speculatively taken.
6791 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6793 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6794 vmx_vcpu_enter_exit(vcpu, vmx);
6797 * We do not use IBRS in the kernel. If this vCPU has used the
6798 * SPEC_CTRL MSR it may have left it on; save the value and
6799 * turn it off. This is much more efficient than blindly adding
6800 * it to the atomic save/restore list. Especially as the former
6801 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6803 * For non-nested case:
6804 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6808 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6811 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6812 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6814 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6816 /* All fields are clean at this point */
6817 if (static_branch_unlikely(&enable_evmcs)) {
6818 current_evmcs->hv_clean_fields |=
6819 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6821 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
6824 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6825 if (vmx->host_debugctlmsr)
6826 update_debugctlmsr(vmx->host_debugctlmsr);
6828 #ifndef CONFIG_X86_64
6830 * The sysexit path does not restore ds/es, so we must set them to
6831 * a reasonable value ourselves.
6833 * We can't defer this to vmx_prepare_switch_to_host() since that
6834 * function may be executed in interrupt context, which saves and
6835 * restore segments around it, nullifying its effect.
6837 loadsegment(ds, __USER_DS);
6838 loadsegment(es, __USER_DS);
6841 vmx_register_cache_reset(vcpu);
6845 kvm_load_host_xsave_state(vcpu);
6847 vmx->nested.nested_run_pending = 0;
6848 vmx->idt_vectoring_info = 0;
6850 if (unlikely(vmx->fail)) {
6851 vmx->exit_reason.full = 0xdead;
6852 return EXIT_FASTPATH_NONE;
6855 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
6856 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
6857 kvm_machine_check();
6859 if (likely(!vmx->exit_reason.failed_vmentry))
6860 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6862 trace_kvm_exit(vmx->exit_reason.full, vcpu, KVM_ISA_VMX);
6864 if (unlikely(vmx->exit_reason.failed_vmentry))
6865 return EXIT_FASTPATH_NONE;
6867 vmx->loaded_vmcs->launched = 1;
6869 vmx_recover_nmi_blocking(vmx);
6870 vmx_complete_interrupts(vmx);
6872 if (is_guest_mode(vcpu))
6873 return EXIT_FASTPATH_NONE;
6875 return vmx_exit_handlers_fastpath(vcpu);
6878 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6880 struct vcpu_vmx *vmx = to_vmx(vcpu);
6883 vmx_destroy_pml_buffer(vmx);
6884 free_vpid(vmx->vpid);
6885 nested_vmx_free_vcpu(vcpu);
6886 free_loaded_vmcs(vmx->loaded_vmcs);
6889 static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
6891 struct vcpu_vmx *vmx;
6894 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6899 vmx->vpid = allocate_vpid();
6902 * If PML is turned on, failure on enabling PML just results in failure
6903 * of creating the vcpu, therefore we can simplify PML logic (by
6904 * avoiding dealing with cases, such as enabling PML partially on vcpus
6905 * for the guest), etc.
6908 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6913 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
6915 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i) {
6916 u32 index = vmx_uret_msrs_list[i];
6917 u32 data_low, data_high;
6918 int j = vmx->nr_uret_msrs;
6920 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6922 if (wrmsr_safe(index, data_low, data_high) < 0)
6925 vmx->guest_uret_msrs[j].slot = i;
6926 vmx->guest_uret_msrs[j].data = 0;
6928 case MSR_IA32_TSX_CTRL:
6930 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID
6931 * interception. Keep the host value unchanged to avoid
6932 * changing CPUID bits under the host kernel's feet.
6934 * hle=0, rtm=0, tsx_ctrl=1 can be found with some
6935 * combinations of new kernel and old userspace. If
6936 * those guests run on a tsx=off host, do allow guests
6937 * to use TSX_CTRL, but do not change the value on the
6938 * host so that TSX remains always disabled.
6940 if (boot_cpu_has(X86_FEATURE_RTM))
6941 vmx->guest_uret_msrs[j].mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6943 vmx->guest_uret_msrs[j].mask = 0;
6946 vmx->guest_uret_msrs[j].mask = -1ull;
6949 ++vmx->nr_uret_msrs;
6952 err = alloc_loaded_vmcs(&vmx->vmcs01);
6956 /* The MSR bitmap starts with all ones */
6957 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6958 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6960 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
6961 #ifdef CONFIG_X86_64
6962 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
6963 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
6964 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6966 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6967 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6968 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6969 if (kvm_cstate_in_guest(vcpu->kvm)) {
6970 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
6971 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6972 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6973 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6975 vmx->msr_bitmap_mode = 0;
6977 vmx->loaded_vmcs = &vmx->vmcs01;
6979 vmx_vcpu_load(vcpu, cpu);
6984 if (cpu_need_virtualize_apic_accesses(vcpu)) {
6985 err = alloc_apic_access_page(vcpu->kvm);
6990 if (enable_ept && !enable_unrestricted_guest) {
6991 err = init_rmode_identity_map(vcpu->kvm);
6997 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
6999 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
7001 vcpu_setup_sgx_lepubkeyhash(vcpu);
7003 vmx->nested.posted_intr_nv = -1;
7004 vmx->nested.current_vmptr = -1ull;
7006 vcpu->arch.microcode_version = 0x100000000ULL;
7007 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
7010 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
7011 * or POSTED_INTR_WAKEUP_VECTOR.
7013 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
7014 vmx->pi_desc.sn = 1;
7016 #if IS_ENABLED(CONFIG_HYPERV)
7017 vmx->hv_root_ept = INVALID_PAGE;
7022 free_loaded_vmcs(vmx->loaded_vmcs);
7024 vmx_destroy_pml_buffer(vmx);
7026 free_vpid(vmx->vpid);
7030 #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"
7031 #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"
7033 static int vmx_vm_init(struct kvm *kvm)
7035 #if IS_ENABLED(CONFIG_HYPERV)
7036 spin_lock_init(&to_kvm_vmx(kvm)->hv_root_ept_lock);
7040 kvm->arch.pause_in_guest = true;
7042 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7043 switch (l1tf_mitigation) {
7044 case L1TF_MITIGATION_OFF:
7045 case L1TF_MITIGATION_FLUSH_NOWARN:
7046 /* 'I explicitly don't care' is set */
7048 case L1TF_MITIGATION_FLUSH:
7049 case L1TF_MITIGATION_FLUSH_NOSMT:
7050 case L1TF_MITIGATION_FULL:
7052 * Warn upon starting the first VM in a potentially
7053 * insecure environment.
7055 if (sched_smt_active())
7056 pr_warn_once(L1TF_MSG_SMT);
7057 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7058 pr_warn_once(L1TF_MSG_L1D);
7060 case L1TF_MITIGATION_FULL_FORCE:
7061 /* Flush is enforced */
7065 kvm_apicv_init(kvm, enable_apicv);
7069 static int __init vmx_check_processor_compat(void)
7071 struct vmcs_config vmcs_conf;
7072 struct vmx_capability vmx_cap;
7074 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7075 !this_cpu_has(X86_FEATURE_VMX)) {
7076 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7080 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7083 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
7084 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7085 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7086 smp_processor_id());
7092 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7097 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7098 * memory aliases with conflicting memory types and sometimes MCEs.
7099 * We have to be careful as to what are honored and when.
7101 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7102 * UC. The effective memory type is UC or WC depending on guest PAT.
7103 * This was historically the source of MCEs and we want to be
7106 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7107 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7108 * EPT memory type is set to WB. The effective memory type is forced
7111 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7112 * EPT memory type is used to emulate guest CD/MTRR.
7116 cache = MTRR_TYPE_UNCACHABLE;
7120 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7121 ipat = VMX_EPT_IPAT_BIT;
7122 cache = MTRR_TYPE_WRBACK;
7126 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7127 ipat = VMX_EPT_IPAT_BIT;
7128 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7129 cache = MTRR_TYPE_WRBACK;
7131 cache = MTRR_TYPE_UNCACHABLE;
7135 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
7138 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7141 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
7144 * These bits in the secondary execution controls field
7145 * are dynamic, the others are mostly based on the hypervisor
7146 * architecture and the guest's CPUID. Do not touch the
7150 SECONDARY_EXEC_SHADOW_VMCS |
7151 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7152 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7153 SECONDARY_EXEC_DESC;
7155 u32 new_ctl = vmx->secondary_exec_control;
7156 u32 cur_ctl = secondary_exec_controls_get(vmx);
7158 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7162 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7163 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7165 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7167 struct vcpu_vmx *vmx = to_vmx(vcpu);
7168 struct kvm_cpuid_entry2 *entry;
7170 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7171 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7173 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7174 if (entry && (entry->_reg & (_cpuid_mask))) \
7175 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7178 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7179 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7180 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7181 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7182 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7183 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7184 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7185 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7186 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7187 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7188 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7189 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7190 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7191 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7192 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7194 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7195 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7196 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7197 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7198 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7199 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7200 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7202 #undef cr4_fixed1_update
7205 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7207 struct vcpu_vmx *vmx = to_vmx(vcpu);
7209 if (kvm_mpx_supported()) {
7210 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7213 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7214 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7216 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7217 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7222 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7224 struct vcpu_vmx *vmx = to_vmx(vcpu);
7225 struct kvm_cpuid_entry2 *best = NULL;
7228 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7229 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7232 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7233 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7234 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7235 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7238 /* Get the number of configurable Address Ranges for filtering */
7239 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7240 PT_CAP_num_address_ranges);
7242 /* Initialize and clear the no dependency bits */
7243 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7244 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7247 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7248 * will inject an #GP
7250 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7251 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7254 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7255 * PSBFreq can be set
7257 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7258 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7259 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7262 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7263 * MTCFreq can be set
7265 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7266 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7267 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7269 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7270 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7271 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7274 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7275 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7276 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7278 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7279 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7280 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7282 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7283 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7284 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7286 /* unmask address range configure area */
7287 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7288 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7291 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7293 struct vcpu_vmx *vmx = to_vmx(vcpu);
7295 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7296 vcpu->arch.xsaves_enabled = false;
7298 if (cpu_has_secondary_exec_ctrls()) {
7299 vmx_compute_secondary_exec_control(vmx);
7300 vmcs_set_secondary_exec_control(vmx);
7303 if (nested_vmx_allowed(vcpu))
7304 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7305 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7306 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7308 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7309 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7310 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7312 if (nested_vmx_allowed(vcpu)) {
7313 nested_vmx_cr_fixed1_bits_update(vcpu);
7314 nested_vmx_entry_exit_ctls_update(vcpu);
7317 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7318 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7319 update_intel_pt_cfg(vcpu);
7321 if (boot_cpu_has(X86_FEATURE_RTM)) {
7322 struct vmx_uret_msr *msr;
7323 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7325 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7326 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7330 set_cr4_guest_host_mask(vmx);
7332 vmx_write_encls_bitmap(vcpu, NULL);
7333 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7334 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7336 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7338 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7339 vmx->msr_ia32_feature_control_valid_bits |=
7340 FEAT_CTL_SGX_LC_ENABLED;
7342 vmx->msr_ia32_feature_control_valid_bits &=
7343 ~FEAT_CTL_SGX_LC_ENABLED;
7345 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7346 vmx_update_exception_bitmap(vcpu);
7349 static __init void vmx_set_cpu_caps(void)
7355 kvm_cpu_cap_set(X86_FEATURE_VMX);
7358 if (kvm_mpx_supported())
7359 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7360 if (!cpu_has_vmx_invpcid())
7361 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7362 if (vmx_pt_mode_is_host_guest())
7363 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7366 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7367 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7368 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7369 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7372 if (vmx_umip_emulated())
7373 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7377 if (!cpu_has_vmx_xsaves())
7378 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7380 /* CPUID 0x80000001 */
7381 if (!cpu_has_vmx_rdtscp())
7382 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7384 if (cpu_has_vmx_waitpkg())
7385 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7388 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7390 to_vmx(vcpu)->req_immediate_exit = true;
7393 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7394 struct x86_instruction_info *info)
7396 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7397 unsigned short port;
7401 if (info->intercept == x86_intercept_in ||
7402 info->intercept == x86_intercept_ins) {
7403 port = info->src_val;
7404 size = info->dst_bytes;
7406 port = info->dst_val;
7407 size = info->src_bytes;
7411 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7412 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7415 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7417 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7418 intercept = nested_cpu_has(vmcs12,
7419 CPU_BASED_UNCOND_IO_EXITING);
7421 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7423 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7424 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7427 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7428 struct x86_instruction_info *info,
7429 enum x86_intercept_stage stage,
7430 struct x86_exception *exception)
7432 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7434 switch (info->intercept) {
7436 * RDPID causes #UD if disabled through secondary execution controls.
7437 * Because it is marked as EmulateOnUD, we need to intercept it here.
7439 case x86_intercept_rdtscp:
7440 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7441 exception->vector = UD_VECTOR;
7442 exception->error_code_valid = false;
7443 return X86EMUL_PROPAGATE_FAULT;
7447 case x86_intercept_in:
7448 case x86_intercept_ins:
7449 case x86_intercept_out:
7450 case x86_intercept_outs:
7451 return vmx_check_intercept_io(vcpu, info);
7453 case x86_intercept_lgdt:
7454 case x86_intercept_lidt:
7455 case x86_intercept_lldt:
7456 case x86_intercept_ltr:
7457 case x86_intercept_sgdt:
7458 case x86_intercept_sidt:
7459 case x86_intercept_sldt:
7460 case x86_intercept_str:
7461 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7462 return X86EMUL_CONTINUE;
7464 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7467 /* TODO: check more intercepts... */
7472 return X86EMUL_UNHANDLEABLE;
7475 #ifdef CONFIG_X86_64
7476 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7477 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7478 u64 divisor, u64 *result)
7480 u64 low = a << shift, high = a >> (64 - shift);
7482 /* To avoid the overflow on divq */
7483 if (high >= divisor)
7486 /* Low hold the result, high hold rem which is discarded */
7487 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7488 "rm" (divisor), "0" (low), "1" (high));
7494 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7497 struct vcpu_vmx *vmx;
7498 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7499 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7503 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7504 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7505 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7506 ktimer->timer_advance_ns);
7508 if (delta_tsc > lapic_timer_advance_cycles)
7509 delta_tsc -= lapic_timer_advance_cycles;
7513 /* Convert to host delta tsc if tsc scaling is enabled */
7514 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7515 delta_tsc && u64_shl_div_u64(delta_tsc,
7516 kvm_tsc_scaling_ratio_frac_bits,
7517 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7521 * If the delta tsc can't fit in the 32 bit after the multi shift,
7522 * we can't use the preemption timer.
7523 * It's possible that it fits on later vmentries, but checking
7524 * on every vmentry is costly so we just use an hrtimer.
7526 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7529 vmx->hv_deadline_tsc = tscl + delta_tsc;
7530 *expired = !delta_tsc;
7534 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7536 to_vmx(vcpu)->hv_deadline_tsc = -1;
7540 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7542 if (!kvm_pause_in_guest(vcpu->kvm))
7543 shrink_ple_window(vcpu);
7546 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
7548 struct vcpu_vmx *vmx = to_vmx(vcpu);
7550 if (is_guest_mode(vcpu)) {
7551 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
7556 * Note, cpu_dirty_logging_count can be changed concurrent with this
7557 * code, but in that case another update request will be made and so
7558 * the guest will never run with a stale PML value.
7560 if (vcpu->kvm->arch.cpu_dirty_logging_count)
7561 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7563 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7566 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7568 if (pi_pre_block(vcpu))
7571 if (kvm_lapic_hv_timer_in_use(vcpu))
7572 kvm_lapic_switch_to_sw_timer(vcpu);
7577 static void vmx_post_block(struct kvm_vcpu *vcpu)
7579 if (kvm_x86_ops.set_hv_timer)
7580 kvm_lapic_switch_to_hv_timer(vcpu);
7582 pi_post_block(vcpu);
7585 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7587 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7588 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7589 FEAT_CTL_LMCE_ENABLED;
7591 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7592 ~FEAT_CTL_LMCE_ENABLED;
7595 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7597 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7598 if (to_vmx(vcpu)->nested.nested_run_pending)
7600 return !is_smm(vcpu);
7603 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7605 struct vcpu_vmx *vmx = to_vmx(vcpu);
7607 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7608 if (vmx->nested.smm.guest_mode)
7609 nested_vmx_vmexit(vcpu, -1, 0, 0);
7611 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7612 vmx->nested.vmxon = false;
7613 vmx_clear_hlt(vcpu);
7617 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7619 struct vcpu_vmx *vmx = to_vmx(vcpu);
7622 if (vmx->nested.smm.vmxon) {
7623 vmx->nested.vmxon = true;
7624 vmx->nested.smm.vmxon = false;
7627 if (vmx->nested.smm.guest_mode) {
7628 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7632 vmx->nested.smm.guest_mode = false;
7637 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
7639 /* RSM will cause a vmexit anyway. */
7642 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7644 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
7647 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7649 if (is_guest_mode(vcpu)) {
7650 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7652 if (hrtimer_try_to_cancel(timer) == 1)
7653 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7657 static void hardware_unsetup(void)
7660 nested_vmx_hardware_unsetup();
7665 static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7667 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7668 BIT(APICV_INHIBIT_REASON_HYPERV);
7670 return supported & BIT(bit);
7673 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7674 .hardware_unsetup = hardware_unsetup,
7676 .hardware_enable = hardware_enable,
7677 .hardware_disable = hardware_disable,
7678 .cpu_has_accelerated_tpr = report_flexpriority,
7679 .has_emulated_msr = vmx_has_emulated_msr,
7681 .vm_size = sizeof(struct kvm_vmx),
7682 .vm_init = vmx_vm_init,
7684 .vcpu_create = vmx_create_vcpu,
7685 .vcpu_free = vmx_free_vcpu,
7686 .vcpu_reset = vmx_vcpu_reset,
7688 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7689 .vcpu_load = vmx_vcpu_load,
7690 .vcpu_put = vmx_vcpu_put,
7692 .update_exception_bitmap = vmx_update_exception_bitmap,
7693 .get_msr_feature = vmx_get_msr_feature,
7694 .get_msr = vmx_get_msr,
7695 .set_msr = vmx_set_msr,
7696 .get_segment_base = vmx_get_segment_base,
7697 .get_segment = vmx_get_segment,
7698 .set_segment = vmx_set_segment,
7699 .get_cpl = vmx_get_cpl,
7700 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7701 .set_cr0 = vmx_set_cr0,
7702 .is_valid_cr4 = vmx_is_valid_cr4,
7703 .set_cr4 = vmx_set_cr4,
7704 .set_efer = vmx_set_efer,
7705 .get_idt = vmx_get_idt,
7706 .set_idt = vmx_set_idt,
7707 .get_gdt = vmx_get_gdt,
7708 .set_gdt = vmx_set_gdt,
7709 .set_dr7 = vmx_set_dr7,
7710 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7711 .cache_reg = vmx_cache_reg,
7712 .get_rflags = vmx_get_rflags,
7713 .set_rflags = vmx_set_rflags,
7715 .tlb_flush_all = vmx_flush_tlb_all,
7716 .tlb_flush_current = vmx_flush_tlb_current,
7717 .tlb_flush_gva = vmx_flush_tlb_gva,
7718 .tlb_flush_guest = vmx_flush_tlb_guest,
7720 .run = vmx_vcpu_run,
7721 .handle_exit = vmx_handle_exit,
7722 .skip_emulated_instruction = vmx_skip_emulated_instruction,
7723 .update_emulated_instruction = vmx_update_emulated_instruction,
7724 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7725 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7726 .patch_hypercall = vmx_patch_hypercall,
7727 .set_irq = vmx_inject_irq,
7728 .set_nmi = vmx_inject_nmi,
7729 .queue_exception = vmx_queue_exception,
7730 .cancel_injection = vmx_cancel_injection,
7731 .interrupt_allowed = vmx_interrupt_allowed,
7732 .nmi_allowed = vmx_nmi_allowed,
7733 .get_nmi_mask = vmx_get_nmi_mask,
7734 .set_nmi_mask = vmx_set_nmi_mask,
7735 .enable_nmi_window = vmx_enable_nmi_window,
7736 .enable_irq_window = vmx_enable_irq_window,
7737 .update_cr8_intercept = vmx_update_cr8_intercept,
7738 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7739 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7740 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7741 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7742 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7743 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7744 .hwapic_irr_update = vmx_hwapic_irr_update,
7745 .hwapic_isr_update = vmx_hwapic_isr_update,
7746 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7747 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7748 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7749 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
7751 .set_tss_addr = vmx_set_tss_addr,
7752 .set_identity_map_addr = vmx_set_identity_map_addr,
7753 .get_mt_mask = vmx_get_mt_mask,
7755 .get_exit_info = vmx_get_exit_info,
7757 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
7759 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7761 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7763 .load_mmu_pgd = vmx_load_mmu_pgd,
7765 .check_intercept = vmx_check_intercept,
7766 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7768 .request_immediate_exit = vmx_request_immediate_exit,
7770 .sched_in = vmx_sched_in,
7772 .cpu_dirty_log_size = PML_ENTITY_NUM,
7773 .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
7775 .pre_block = vmx_pre_block,
7776 .post_block = vmx_post_block,
7778 .pmu_ops = &intel_pmu_ops,
7779 .nested_ops = &vmx_nested_ops,
7781 .update_pi_irte = pi_update_irte,
7783 #ifdef CONFIG_X86_64
7784 .set_hv_timer = vmx_set_hv_timer,
7785 .cancel_hv_timer = vmx_cancel_hv_timer,
7788 .setup_mce = vmx_setup_mce,
7790 .smi_allowed = vmx_smi_allowed,
7791 .pre_enter_smm = vmx_pre_enter_smm,
7792 .pre_leave_smm = vmx_pre_leave_smm,
7793 .enable_smi_window = vmx_enable_smi_window,
7795 .can_emulate_instruction = vmx_can_emulate_instruction,
7796 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7797 .migrate_timers = vmx_migrate_timers,
7799 .msr_filter_changed = vmx_msr_filter_changed,
7800 .complete_emulated_msr = kvm_complete_insn_gp,
7802 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
7805 static __init int hardware_setup(void)
7807 unsigned long host_bndcfgs;
7809 int r, i, ept_lpage_level;
7812 host_idt_base = dt.address;
7814 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
7815 kvm_define_user_return_msr(i, vmx_uret_msrs_list[i]);
7817 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7820 if (boot_cpu_has(X86_FEATURE_NX))
7821 kvm_enable_efer_bits(EFER_NX);
7823 if (boot_cpu_has(X86_FEATURE_MPX)) {
7824 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7825 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7828 if (!cpu_has_vmx_mpx())
7829 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
7830 XFEATURE_MASK_BNDCSR);
7832 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7833 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7836 if (!cpu_has_vmx_ept() ||
7837 !cpu_has_vmx_ept_4levels() ||
7838 !cpu_has_vmx_ept_mt_wb() ||
7839 !cpu_has_vmx_invept_global())
7842 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7843 enable_ept_ad_bits = 0;
7845 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7846 enable_unrestricted_guest = 0;
7848 if (!cpu_has_vmx_flexpriority())
7849 flexpriority_enabled = 0;
7851 if (!cpu_has_virtual_nmis())
7855 * set_apic_access_page_addr() is used to reload apic access
7856 * page upon invalidation. No need to do anything if not
7857 * using the APIC_ACCESS_ADDR VMCS field.
7859 if (!flexpriority_enabled)
7860 vmx_x86_ops.set_apic_access_page_addr = NULL;
7862 if (!cpu_has_vmx_tpr_shadow())
7863 vmx_x86_ops.update_cr8_intercept = NULL;
7865 #if IS_ENABLED(CONFIG_HYPERV)
7866 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7868 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
7869 vmx_x86_ops.tlb_remote_flush_with_range =
7870 hv_remote_flush_tlb_with_range;
7874 if (!cpu_has_vmx_ple()) {
7877 ple_window_grow = 0;
7879 ple_window_shrink = 0;
7882 if (!cpu_has_vmx_apicv()) {
7884 vmx_x86_ops.sync_pir_to_irr = NULL;
7887 if (cpu_has_vmx_tsc_scaling()) {
7888 kvm_has_tsc_control = true;
7889 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7890 kvm_tsc_scaling_ratio_frac_bits = 48;
7893 kvm_has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
7895 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7898 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
7899 cpu_has_vmx_ept_execute_only());
7902 ept_lpage_level = 0;
7903 else if (cpu_has_vmx_ept_1g_page())
7904 ept_lpage_level = PG_LEVEL_1G;
7905 else if (cpu_has_vmx_ept_2m_page())
7906 ept_lpage_level = PG_LEVEL_2M;
7908 ept_lpage_level = PG_LEVEL_4K;
7909 kvm_configure_mmu(enable_ept, vmx_get_max_tdp_level(), ept_lpage_level);
7912 * Only enable PML when hardware supports PML feature, and both EPT
7913 * and EPT A/D bit features are enabled -- PML depends on them to work.
7915 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7919 vmx_x86_ops.cpu_dirty_log_size = 0;
7921 if (!cpu_has_vmx_preemption_timer())
7922 enable_preemption_timer = false;
7924 if (enable_preemption_timer) {
7925 u64 use_timer_freq = 5000ULL * 1000 * 1000;
7928 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7929 cpu_preemption_timer_multi =
7930 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7933 use_timer_freq = (u64)tsc_khz * 1000;
7934 use_timer_freq >>= cpu_preemption_timer_multi;
7937 * KVM "disables" the preemption timer by setting it to its max
7938 * value. Don't use the timer if it might cause spurious exits
7939 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
7941 if (use_timer_freq > 0xffffffffu / 10)
7942 enable_preemption_timer = false;
7945 if (!enable_preemption_timer) {
7946 vmx_x86_ops.set_hv_timer = NULL;
7947 vmx_x86_ops.cancel_hv_timer = NULL;
7948 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
7951 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
7953 kvm_mce_cap_supported |= MCG_LMCE_P;
7955 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7957 if (!enable_ept || !cpu_has_vmx_intel_pt())
7958 pt_mode = PT_MODE_SYSTEM;
7960 setup_default_sgx_lepubkeyhash();
7963 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7964 vmx_capability.ept);
7966 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7973 r = alloc_kvm_area();
7975 nested_vmx_hardware_unsetup();
7979 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
7980 .cpu_has_kvm_support = cpu_has_kvm_support,
7981 .disabled_by_bios = vmx_disabled_by_bios,
7982 .check_processor_compatibility = vmx_check_processor_compat,
7983 .hardware_setup = hardware_setup,
7985 .runtime_ops = &vmx_x86_ops,
7988 static void vmx_cleanup_l1d_flush(void)
7990 if (vmx_l1d_flush_pages) {
7991 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7992 vmx_l1d_flush_pages = NULL;
7994 /* Restore state so sysfs ignores VMX */
7995 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
7998 static void vmx_exit(void)
8000 #ifdef CONFIG_KEXEC_CORE
8001 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8007 #if IS_ENABLED(CONFIG_HYPERV)
8008 if (static_branch_unlikely(&enable_evmcs)) {
8010 struct hv_vp_assist_page *vp_ap;
8012 * Reset everything to support using non-enlightened VMCS
8013 * access later (e.g. when we reload the module with
8014 * enlightened_vmcs=0)
8016 for_each_online_cpu(cpu) {
8017 vp_ap = hv_get_vp_assist_page(cpu);
8022 vp_ap->nested_control.features.directhypercall = 0;
8023 vp_ap->current_nested_vmcs = 0;
8024 vp_ap->enlighten_vmentry = 0;
8027 static_branch_disable(&enable_evmcs);
8030 vmx_cleanup_l1d_flush();
8032 module_exit(vmx_exit);
8034 static int __init vmx_init(void)
8038 #if IS_ENABLED(CONFIG_HYPERV)
8040 * Enlightened VMCS usage should be recommended and the host needs
8041 * to support eVMCS v1 or above. We can also disable eVMCS support
8042 * with module parameter.
8044 if (enlightened_vmcs &&
8045 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8046 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8047 KVM_EVMCS_VERSION) {
8050 /* Check that we have assist pages on all online CPUs */
8051 for_each_online_cpu(cpu) {
8052 if (!hv_get_vp_assist_page(cpu)) {
8053 enlightened_vmcs = false;
8058 if (enlightened_vmcs) {
8059 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8060 static_branch_enable(&enable_evmcs);
8063 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8064 vmx_x86_ops.enable_direct_tlbflush
8065 = hv_enable_direct_tlbflush;
8068 enlightened_vmcs = false;
8072 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8073 __alignof__(struct vcpu_vmx), THIS_MODULE);
8078 * Must be called after kvm_init() so enable_ept is properly set
8079 * up. Hand the parameter mitigation value in which was stored in
8080 * the pre module init parser. If no parameter was given, it will
8081 * contain 'auto' which will be turned into the default 'cond'
8084 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8090 for_each_possible_cpu(cpu) {
8091 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8096 #ifdef CONFIG_KEXEC_CORE
8097 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8098 crash_vmclear_local_loaded_vmcss);
8100 vmx_check_vmcs12_offsets();
8103 * Shadow paging doesn't have a (further) performance penalty
8104 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8108 allow_smaller_maxphyaddr = true;
8112 module_init(vmx_init);