1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <linux/highmem.h>
17 #include <linux/hrtimer.h>
18 #include <linux/kernel.h>
19 #include <linux/kvm_host.h>
20 #include <linux/module.h>
21 #include <linux/moduleparam.h>
22 #include <linux/mod_devicetable.h>
24 #include <linux/objtool.h>
25 #include <linux/sched.h>
26 #include <linux/sched/smt.h>
27 #include <linux/slab.h>
28 #include <linux/tboot.h>
29 #include <linux/trace_events.h>
30 #include <linux/entry-kvm.h>
35 #include <asm/cpu_device_id.h>
36 #include <asm/debugreg.h>
38 #include <asm/fpu/internal.h>
39 #include <asm/idtentry.h>
41 #include <asm/irq_remapping.h>
42 #include <asm/kexec.h>
43 #include <asm/perf_event.h>
44 #include <asm/mmu_context.h>
45 #include <asm/mshyperv.h>
46 #include <asm/mwait.h>
47 #include <asm/spec-ctrl.h>
48 #include <asm/virtext.h>
51 #include "capabilities.h"
56 #include "kvm_cache_regs.h"
68 MODULE_AUTHOR("Qumranet");
69 MODULE_LICENSE("GPL");
72 static const struct x86_cpu_id vmx_cpu_id[] = {
73 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
76 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
79 bool __read_mostly enable_vpid = 1;
80 module_param_named(vpid, enable_vpid, bool, 0444);
82 static bool __read_mostly enable_vnmi = 1;
83 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
85 bool __read_mostly flexpriority_enabled = 1;
86 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
88 bool __read_mostly enable_ept = 1;
89 module_param_named(ept, enable_ept, bool, S_IRUGO);
91 bool __read_mostly enable_unrestricted_guest = 1;
92 module_param_named(unrestricted_guest,
93 enable_unrestricted_guest, bool, S_IRUGO);
95 bool __read_mostly enable_ept_ad_bits = 1;
96 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
98 static bool __read_mostly emulate_invalid_guest_state = true;
99 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
101 static bool __read_mostly fasteoi = 1;
102 module_param(fasteoi, bool, S_IRUGO);
104 bool __read_mostly enable_apicv = 1;
105 module_param(enable_apicv, bool, S_IRUGO);
108 * If nested=1, nested virtualization is supported, i.e., guests may use
109 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
110 * use VMX instructions.
112 static bool __read_mostly nested = 1;
113 module_param(nested, bool, S_IRUGO);
115 bool __read_mostly enable_pml = 1;
116 module_param_named(pml, enable_pml, bool, S_IRUGO);
118 static bool __read_mostly dump_invalid_vmcs = 0;
119 module_param(dump_invalid_vmcs, bool, 0644);
121 #define MSR_BITMAP_MODE_X2APIC 1
122 #define MSR_BITMAP_MODE_X2APIC_APICV 2
124 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
126 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
127 static int __read_mostly cpu_preemption_timer_multi;
128 static bool __read_mostly enable_preemption_timer = 1;
130 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
133 extern bool __read_mostly allow_smaller_maxphyaddr;
134 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
136 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
137 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
138 #define KVM_VM_CR0_ALWAYS_ON \
139 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
140 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
142 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
143 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
144 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
146 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
148 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
149 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
150 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
151 RTIT_STATUS_BYTECNT))
154 * List of MSRs that can be directly passed to the guest.
155 * In addition to these x2apic and PT MSRs are handled specially.
157 static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
166 MSR_IA32_SYSENTER_CS,
167 MSR_IA32_SYSENTER_ESP,
168 MSR_IA32_SYSENTER_EIP,
170 MSR_CORE_C3_RESIDENCY,
171 MSR_CORE_C6_RESIDENCY,
172 MSR_CORE_C7_RESIDENCY,
176 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
177 * ple_gap: upper bound on the amount of time between two successive
178 * executions of PAUSE in a loop. Also indicate if ple enabled.
179 * According to test, this time is usually smaller than 128 cycles.
180 * ple_window: upper bound on the amount of time a guest is allowed to execute
181 * in a PAUSE loop. Tests indicate that most spinlocks are held for
182 * less than 2^12 cycles
183 * Time is measured based on a counter that runs at the same rate as the TSC,
184 * refer SDM volume 3b section 21.6.13 & 22.1.3.
186 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
187 module_param(ple_gap, uint, 0444);
189 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
190 module_param(ple_window, uint, 0444);
192 /* Default doubles per-vcpu window every exit. */
193 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
194 module_param(ple_window_grow, uint, 0444);
196 /* Default resets per-vcpu window every exit to ple_window. */
197 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
198 module_param(ple_window_shrink, uint, 0444);
200 /* Default is to compute the maximum so we can never overflow. */
201 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
202 module_param(ple_window_max, uint, 0444);
204 /* Default is SYSTEM mode, 1 for host-guest mode */
205 int __read_mostly pt_mode = PT_MODE_SYSTEM;
206 module_param(pt_mode, int, S_IRUGO);
208 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
209 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
210 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
212 /* Storage for pre module init parameter parsing */
213 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
215 static const struct {
218 } vmentry_l1d_param[] = {
219 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
220 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
221 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
222 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
223 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
224 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
227 #define L1D_CACHE_ORDER 4
228 static void *vmx_l1d_flush_pages;
230 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
235 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
236 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
241 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
245 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
248 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
249 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
250 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
255 /* If set to auto use the default l1tf mitigation method */
256 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
257 switch (l1tf_mitigation) {
258 case L1TF_MITIGATION_OFF:
259 l1tf = VMENTER_L1D_FLUSH_NEVER;
261 case L1TF_MITIGATION_FLUSH_NOWARN:
262 case L1TF_MITIGATION_FLUSH:
263 case L1TF_MITIGATION_FLUSH_NOSMT:
264 l1tf = VMENTER_L1D_FLUSH_COND;
266 case L1TF_MITIGATION_FULL:
267 case L1TF_MITIGATION_FULL_FORCE:
268 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
271 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
272 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
275 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
276 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
278 * This allocation for vmx_l1d_flush_pages is not tied to a VM
279 * lifetime and so should not be charged to a memcg.
281 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
284 vmx_l1d_flush_pages = page_address(page);
287 * Initialize each page with a different pattern in
288 * order to protect against KSM in the nested
289 * virtualization case.
291 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
292 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
297 l1tf_vmx_mitigation = l1tf;
299 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
300 static_branch_enable(&vmx_l1d_should_flush);
302 static_branch_disable(&vmx_l1d_should_flush);
304 if (l1tf == VMENTER_L1D_FLUSH_COND)
305 static_branch_enable(&vmx_l1d_flush_cond);
307 static_branch_disable(&vmx_l1d_flush_cond);
311 static int vmentry_l1d_flush_parse(const char *s)
316 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
317 if (vmentry_l1d_param[i].for_parse &&
318 sysfs_streq(s, vmentry_l1d_param[i].option))
325 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
329 l1tf = vmentry_l1d_flush_parse(s);
333 if (!boot_cpu_has(X86_BUG_L1TF))
337 * Has vmx_init() run already? If not then this is the pre init
338 * parameter parsing. In that case just store the value and let
339 * vmx_init() do the proper setup after enable_ept has been
342 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
343 vmentry_l1d_flush_param = l1tf;
347 mutex_lock(&vmx_l1d_flush_mutex);
348 ret = vmx_setup_l1d_flush(l1tf);
349 mutex_unlock(&vmx_l1d_flush_mutex);
353 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
355 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
356 return sprintf(s, "???\n");
358 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
361 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
362 .set = vmentry_l1d_flush_set,
363 .get = vmentry_l1d_flush_get,
365 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
367 static u32 vmx_segment_access_rights(struct kvm_segment *var);
369 void vmx_vmexit(void);
371 #define vmx_insn_failed(fmt...) \
374 pr_warn_ratelimited(fmt); \
377 asmlinkage void vmread_error(unsigned long field, bool fault)
380 kvm_spurious_fault();
382 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
385 noinline void vmwrite_error(unsigned long field, unsigned long value)
387 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
388 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
391 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
393 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
396 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
398 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
401 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
403 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
407 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
409 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
413 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
414 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
416 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
417 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
419 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
421 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
422 static DEFINE_SPINLOCK(vmx_vpid_lock);
424 struct vmcs_config vmcs_config;
425 struct vmx_capability vmx_capability;
427 #define VMX_SEGMENT_FIELD(seg) \
428 [VCPU_SREG_##seg] = { \
429 .selector = GUEST_##seg##_SELECTOR, \
430 .base = GUEST_##seg##_BASE, \
431 .limit = GUEST_##seg##_LIMIT, \
432 .ar_bytes = GUEST_##seg##_AR_BYTES, \
435 static const struct kvm_vmx_segment_field {
440 } kvm_vmx_segment_fields[] = {
441 VMX_SEGMENT_FIELD(CS),
442 VMX_SEGMENT_FIELD(DS),
443 VMX_SEGMENT_FIELD(ES),
444 VMX_SEGMENT_FIELD(FS),
445 VMX_SEGMENT_FIELD(GS),
446 VMX_SEGMENT_FIELD(SS),
447 VMX_SEGMENT_FIELD(TR),
448 VMX_SEGMENT_FIELD(LDTR),
451 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
453 vmx->segment_cache.bitmask = 0;
456 static unsigned long host_idt_base;
458 #if IS_ENABLED(CONFIG_HYPERV)
459 static bool __read_mostly enlightened_vmcs = true;
460 module_param(enlightened_vmcs, bool, 0444);
462 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
465 struct kvm_tlb_range *range = data;
467 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
471 static inline int hv_remote_flush_root_ept(hpa_t root_ept,
472 struct kvm_tlb_range *range)
475 return hyperv_flush_guest_mapping_range(root_ept,
476 kvm_fill_hv_flush_list_func, (void *)range);
478 return hyperv_flush_guest_mapping(root_ept);
481 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
482 struct kvm_tlb_range *range)
484 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
485 struct kvm_vcpu *vcpu;
486 int ret = 0, i, nr_unique_valid_roots;
489 spin_lock(&kvm_vmx->hv_root_ept_lock);
491 if (!VALID_PAGE(kvm_vmx->hv_root_ept)) {
492 nr_unique_valid_roots = 0;
495 * Flush all valid roots, and see if all vCPUs have converged
496 * on a common root, in which case future flushes can skip the
497 * loop and flush the common root.
499 kvm_for_each_vcpu(i, vcpu, kvm) {
500 root = to_vmx(vcpu)->hv_root_ept;
501 if (!VALID_PAGE(root) || root == kvm_vmx->hv_root_ept)
505 * Set the tracked root to the first valid root. Keep
506 * this root for the entirety of the loop even if more
507 * roots are encountered as a low effort optimization
508 * to avoid flushing the same (first) root again.
510 if (++nr_unique_valid_roots == 1)
511 kvm_vmx->hv_root_ept = root;
514 ret = hv_remote_flush_root_ept(root, range);
517 * Stop processing roots if a failure occurred and
518 * multiple valid roots have already been detected.
520 if (ret && nr_unique_valid_roots > 1)
525 * The optimized flush of a single root can't be used if there
526 * are multiple valid roots (obviously).
528 if (nr_unique_valid_roots > 1)
529 kvm_vmx->hv_root_ept = INVALID_PAGE;
531 ret = hv_remote_flush_root_ept(kvm_vmx->hv_root_ept, range);
534 spin_unlock(&kvm_vmx->hv_root_ept_lock);
537 static int hv_remote_flush_tlb(struct kvm *kvm)
539 return hv_remote_flush_tlb_with_range(kvm, NULL);
542 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
544 struct hv_enlightened_vmcs *evmcs;
545 struct hv_partition_assist_pg **p_hv_pa_pg =
546 &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
548 * Synthetic VM-Exit is not enabled in current code and so All
549 * evmcs in singe VM shares same assist page.
552 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
557 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
559 evmcs->partition_assist_page =
561 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
562 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
567 #endif /* IS_ENABLED(CONFIG_HYPERV) */
569 static void hv_track_root_ept(struct kvm_vcpu *vcpu, hpa_t root_ept)
571 #if IS_ENABLED(CONFIG_HYPERV)
572 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
574 if (kvm_x86_ops.tlb_remote_flush == hv_remote_flush_tlb) {
575 spin_lock(&kvm_vmx->hv_root_ept_lock);
576 to_vmx(vcpu)->hv_root_ept = root_ept;
577 if (root_ept != kvm_vmx->hv_root_ept)
578 kvm_vmx->hv_root_ept = INVALID_PAGE;
579 spin_unlock(&kvm_vmx->hv_root_ept_lock);
585 * Comment's format: document - errata name - stepping - processor name.
587 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
589 static u32 vmx_preemption_cpu_tfms[] = {
590 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
592 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
593 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
594 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
596 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
598 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
599 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
601 * 320767.pdf - AAP86 - B1 -
602 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
605 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
607 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
609 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
611 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
612 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
613 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
615 /* Xeon E3-1220 V2 */
619 static inline bool cpu_has_broken_vmx_preemption_timer(void)
621 u32 eax = cpuid_eax(0x00000001), i;
623 /* Clear the reserved bits */
624 eax &= ~(0x3U << 14 | 0xfU << 28);
625 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
626 if (eax == vmx_preemption_cpu_tfms[i])
632 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
634 return flexpriority_enabled && lapic_in_kernel(vcpu);
637 static inline bool report_flexpriority(void)
639 return flexpriority_enabled;
642 static int possible_passthrough_msr_slot(u32 msr)
646 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
647 if (vmx_possible_passthrough_msrs[i] == msr)
653 static bool is_valid_passthrough_msr(u32 msr)
658 case 0x800 ... 0x8ff:
659 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
661 case MSR_IA32_RTIT_STATUS:
662 case MSR_IA32_RTIT_OUTPUT_BASE:
663 case MSR_IA32_RTIT_OUTPUT_MASK:
664 case MSR_IA32_RTIT_CR3_MATCH:
665 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
666 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
669 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
670 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
671 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
672 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
673 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
674 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
678 r = possible_passthrough_msr_slot(msr) != -ENOENT;
680 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
685 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
689 i = kvm_find_user_return_msr(msr);
691 return &vmx->guest_uret_msrs[i];
695 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
696 struct vmx_uret_msr *msr, u64 data)
698 unsigned int slot = msr - vmx->guest_uret_msrs;
701 u64 old_msr_data = msr->data;
703 if (msr->load_into_hardware) {
705 ret = kvm_set_user_return_msr(slot, msr->data, msr->mask);
708 msr->data = old_msr_data;
713 #ifdef CONFIG_KEXEC_CORE
714 static void crash_vmclear_local_loaded_vmcss(void)
716 int cpu = raw_smp_processor_id();
717 struct loaded_vmcs *v;
719 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
720 loaded_vmcss_on_cpu_link)
723 #endif /* CONFIG_KEXEC_CORE */
725 static void __loaded_vmcs_clear(void *arg)
727 struct loaded_vmcs *loaded_vmcs = arg;
728 int cpu = raw_smp_processor_id();
730 if (loaded_vmcs->cpu != cpu)
731 return; /* vcpu migration can race with cpu offline */
732 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
733 per_cpu(current_vmcs, cpu) = NULL;
735 vmcs_clear(loaded_vmcs->vmcs);
736 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
737 vmcs_clear(loaded_vmcs->shadow_vmcs);
739 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
742 * Ensure all writes to loaded_vmcs, including deleting it from its
743 * current percpu list, complete before setting loaded_vmcs->vcpu to
744 * -1, otherwise a different cpu can see vcpu == -1 first and add
745 * loaded_vmcs to its percpu list before it's deleted from this cpu's
746 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
750 loaded_vmcs->cpu = -1;
751 loaded_vmcs->launched = 0;
754 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
756 int cpu = loaded_vmcs->cpu;
759 smp_call_function_single(cpu,
760 __loaded_vmcs_clear, loaded_vmcs, 1);
763 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
767 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
769 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
770 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
771 vmx->segment_cache.bitmask = 0;
773 ret = vmx->segment_cache.bitmask & mask;
774 vmx->segment_cache.bitmask |= mask;
778 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
780 u16 *p = &vmx->segment_cache.seg[seg].selector;
782 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
783 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
787 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
789 ulong *p = &vmx->segment_cache.seg[seg].base;
791 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
792 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
796 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
798 u32 *p = &vmx->segment_cache.seg[seg].limit;
800 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
801 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
805 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
807 u32 *p = &vmx->segment_cache.seg[seg].ar;
809 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
810 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
814 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
818 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
819 (1u << DB_VECTOR) | (1u << AC_VECTOR);
821 * Guest access to VMware backdoor ports could legitimately
822 * trigger #GP because of TSS I/O permission bitmap.
823 * We intercept those #GP and allow access to them anyway
826 if (enable_vmware_backdoor)
827 eb |= (1u << GP_VECTOR);
828 if ((vcpu->guest_debug &
829 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
830 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
831 eb |= 1u << BP_VECTOR;
832 if (to_vmx(vcpu)->rmode.vm86_active)
834 if (!vmx_need_pf_intercept(vcpu))
835 eb &= ~(1u << PF_VECTOR);
837 /* When we are running a nested L2 guest and L1 specified for it a
838 * certain exception bitmap, we must trap the same exceptions and pass
839 * them to L1. When running L2, we will only handle the exceptions
840 * specified above if L1 did not want them.
842 if (is_guest_mode(vcpu))
843 eb |= get_vmcs12(vcpu)->exception_bitmap;
846 * If EPT is enabled, #PF is only trapped if MAXPHYADDR is mismatched
847 * between guest and host. In that case we only care about present
848 * faults. For vmcs02, however, PFEC_MASK and PFEC_MATCH are set in
849 * prepare_vmcs02_rare.
851 bool selective_pf_trap = enable_ept && (eb & (1u << PF_VECTOR));
852 int mask = selective_pf_trap ? PFERR_PRESENT_MASK : 0;
853 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
854 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, mask);
857 vmcs_write32(EXCEPTION_BITMAP, eb);
861 * Check if MSR is intercepted for currently loaded MSR bitmap.
863 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
865 unsigned long *msr_bitmap;
866 int f = sizeof(unsigned long);
868 if (!cpu_has_vmx_msr_bitmap())
871 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
874 return !!test_bit(msr, msr_bitmap + 0x800 / f);
875 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
877 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
883 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
884 unsigned long entry, unsigned long exit)
886 vm_entry_controls_clearbit(vmx, entry);
887 vm_exit_controls_clearbit(vmx, exit);
890 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
894 for (i = 0; i < m->nr; ++i) {
895 if (m->val[i].index == msr)
901 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
904 struct msr_autoload *m = &vmx->msr_autoload;
908 if (cpu_has_load_ia32_efer()) {
909 clear_atomic_switch_msr_special(vmx,
910 VM_ENTRY_LOAD_IA32_EFER,
911 VM_EXIT_LOAD_IA32_EFER);
915 case MSR_CORE_PERF_GLOBAL_CTRL:
916 if (cpu_has_load_perf_global_ctrl()) {
917 clear_atomic_switch_msr_special(vmx,
918 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
919 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
924 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
928 m->guest.val[i] = m->guest.val[m->guest.nr];
929 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
932 i = vmx_find_loadstore_msr_slot(&m->host, msr);
937 m->host.val[i] = m->host.val[m->host.nr];
938 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
941 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
942 unsigned long entry, unsigned long exit,
943 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
944 u64 guest_val, u64 host_val)
946 vmcs_write64(guest_val_vmcs, guest_val);
947 if (host_val_vmcs != HOST_IA32_EFER)
948 vmcs_write64(host_val_vmcs, host_val);
949 vm_entry_controls_setbit(vmx, entry);
950 vm_exit_controls_setbit(vmx, exit);
953 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
954 u64 guest_val, u64 host_val, bool entry_only)
957 struct msr_autoload *m = &vmx->msr_autoload;
961 if (cpu_has_load_ia32_efer()) {
962 add_atomic_switch_msr_special(vmx,
963 VM_ENTRY_LOAD_IA32_EFER,
964 VM_EXIT_LOAD_IA32_EFER,
967 guest_val, host_val);
971 case MSR_CORE_PERF_GLOBAL_CTRL:
972 if (cpu_has_load_perf_global_ctrl()) {
973 add_atomic_switch_msr_special(vmx,
974 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
975 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
976 GUEST_IA32_PERF_GLOBAL_CTRL,
977 HOST_IA32_PERF_GLOBAL_CTRL,
978 guest_val, host_val);
982 case MSR_IA32_PEBS_ENABLE:
983 /* PEBS needs a quiescent period after being disabled (to write
984 * a record). Disabling PEBS through VMX MSR swapping doesn't
985 * provide that period, so a CPU could write host's record into
988 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
991 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
993 j = vmx_find_loadstore_msr_slot(&m->host, msr);
995 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
996 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
997 printk_once(KERN_WARNING "Not enough msr switch entries. "
998 "Can't add msr %x\n", msr);
1003 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1005 m->guest.val[i].index = msr;
1006 m->guest.val[i].value = guest_val;
1013 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1015 m->host.val[j].index = msr;
1016 m->host.val[j].value = host_val;
1019 static bool update_transition_efer(struct vcpu_vmx *vmx)
1021 u64 guest_efer = vmx->vcpu.arch.efer;
1022 u64 ignore_bits = 0;
1025 /* Shadow paging assumes NX to be available. */
1027 guest_efer |= EFER_NX;
1030 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1032 ignore_bits |= EFER_SCE;
1033 #ifdef CONFIG_X86_64
1034 ignore_bits |= EFER_LMA | EFER_LME;
1035 /* SCE is meaningful only in long mode on Intel */
1036 if (guest_efer & EFER_LMA)
1037 ignore_bits &= ~(u64)EFER_SCE;
1041 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1042 * On CPUs that support "load IA32_EFER", always switch EFER
1043 * atomically, since it's faster than switching it manually.
1045 if (cpu_has_load_ia32_efer() ||
1046 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1047 if (!(guest_efer & EFER_LMA))
1048 guest_efer &= ~EFER_LME;
1049 if (guest_efer != host_efer)
1050 add_atomic_switch_msr(vmx, MSR_EFER,
1051 guest_efer, host_efer, false);
1053 clear_atomic_switch_msr(vmx, MSR_EFER);
1057 i = kvm_find_user_return_msr(MSR_EFER);
1061 clear_atomic_switch_msr(vmx, MSR_EFER);
1063 guest_efer &= ~ignore_bits;
1064 guest_efer |= host_efer & ignore_bits;
1066 vmx->guest_uret_msrs[i].data = guest_efer;
1067 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1072 #ifdef CONFIG_X86_32
1074 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1075 * VMCS rather than the segment table. KVM uses this helper to figure
1076 * out the current bases to poke them into the VMCS before entry.
1078 static unsigned long segment_base(u16 selector)
1080 struct desc_struct *table;
1083 if (!(selector & ~SEGMENT_RPL_MASK))
1086 table = get_current_gdt_ro();
1088 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1089 u16 ldt_selector = kvm_read_ldt();
1091 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1094 table = (struct desc_struct *)segment_base(ldt_selector);
1096 v = get_desc_base(&table[selector >> 3]);
1101 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1103 return vmx_pt_mode_is_host_guest() &&
1104 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1107 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1109 /* The base must be 128-byte aligned and a legal physical address. */
1110 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1113 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1117 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1118 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1119 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1120 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1121 for (i = 0; i < addr_range; i++) {
1122 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1123 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1127 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1131 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1132 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1133 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1134 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1135 for (i = 0; i < addr_range; i++) {
1136 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1137 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1141 static void pt_guest_enter(struct vcpu_vmx *vmx)
1143 if (vmx_pt_mode_is_system())
1147 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1148 * Save host state before VM entry.
1150 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1151 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1152 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1153 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1154 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1158 static void pt_guest_exit(struct vcpu_vmx *vmx)
1160 if (vmx_pt_mode_is_system())
1163 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1164 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1165 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1168 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1169 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1172 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1173 unsigned long fs_base, unsigned long gs_base)
1175 if (unlikely(fs_sel != host->fs_sel)) {
1177 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1179 vmcs_write16(HOST_FS_SELECTOR, 0);
1180 host->fs_sel = fs_sel;
1182 if (unlikely(gs_sel != host->gs_sel)) {
1184 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1186 vmcs_write16(HOST_GS_SELECTOR, 0);
1187 host->gs_sel = gs_sel;
1189 if (unlikely(fs_base != host->fs_base)) {
1190 vmcs_writel(HOST_FS_BASE, fs_base);
1191 host->fs_base = fs_base;
1193 if (unlikely(gs_base != host->gs_base)) {
1194 vmcs_writel(HOST_GS_BASE, gs_base);
1195 host->gs_base = gs_base;
1199 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1201 struct vcpu_vmx *vmx = to_vmx(vcpu);
1202 struct vmcs_host_state *host_state;
1203 #ifdef CONFIG_X86_64
1204 int cpu = raw_smp_processor_id();
1206 unsigned long fs_base, gs_base;
1210 vmx->req_immediate_exit = false;
1213 * Note that guest MSRs to be saved/restored can also be changed
1214 * when guest state is loaded. This happens when guest transitions
1215 * to/from long-mode by setting MSR_EFER.LMA.
1217 if (!vmx->guest_uret_msrs_loaded) {
1218 vmx->guest_uret_msrs_loaded = true;
1219 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
1220 if (!vmx->guest_uret_msrs[i].load_into_hardware)
1223 kvm_set_user_return_msr(i,
1224 vmx->guest_uret_msrs[i].data,
1225 vmx->guest_uret_msrs[i].mask);
1229 if (vmx->nested.need_vmcs12_to_shadow_sync)
1230 nested_sync_vmcs12_to_shadow(vcpu);
1232 if (vmx->guest_state_loaded)
1235 host_state = &vmx->loaded_vmcs->host_state;
1238 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1239 * allow segment selectors with cpl > 0 or ti == 1.
1241 host_state->ldt_sel = kvm_read_ldt();
1243 #ifdef CONFIG_X86_64
1244 savesegment(ds, host_state->ds_sel);
1245 savesegment(es, host_state->es_sel);
1247 gs_base = cpu_kernelmode_gs_base(cpu);
1248 if (likely(is_64bit_mm(current->mm))) {
1249 current_save_fsgs();
1250 fs_sel = current->thread.fsindex;
1251 gs_sel = current->thread.gsindex;
1252 fs_base = current->thread.fsbase;
1253 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1255 savesegment(fs, fs_sel);
1256 savesegment(gs, gs_sel);
1257 fs_base = read_msr(MSR_FS_BASE);
1258 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1261 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1263 savesegment(fs, fs_sel);
1264 savesegment(gs, gs_sel);
1265 fs_base = segment_base(fs_sel);
1266 gs_base = segment_base(gs_sel);
1269 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1270 vmx->guest_state_loaded = true;
1273 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1275 struct vmcs_host_state *host_state;
1277 if (!vmx->guest_state_loaded)
1280 host_state = &vmx->loaded_vmcs->host_state;
1282 ++vmx->vcpu.stat.host_state_reload;
1284 #ifdef CONFIG_X86_64
1285 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1287 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1288 kvm_load_ldt(host_state->ldt_sel);
1289 #ifdef CONFIG_X86_64
1290 load_gs_index(host_state->gs_sel);
1292 loadsegment(gs, host_state->gs_sel);
1295 if (host_state->fs_sel & 7)
1296 loadsegment(fs, host_state->fs_sel);
1297 #ifdef CONFIG_X86_64
1298 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1299 loadsegment(ds, host_state->ds_sel);
1300 loadsegment(es, host_state->es_sel);
1303 invalidate_tss_limit();
1304 #ifdef CONFIG_X86_64
1305 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1307 load_fixmap_gdt(raw_smp_processor_id());
1308 vmx->guest_state_loaded = false;
1309 vmx->guest_uret_msrs_loaded = false;
1312 #ifdef CONFIG_X86_64
1313 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1316 if (vmx->guest_state_loaded)
1317 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1319 return vmx->msr_guest_kernel_gs_base;
1322 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1325 if (vmx->guest_state_loaded)
1326 wrmsrl(MSR_KERNEL_GS_BASE, data);
1328 vmx->msr_guest_kernel_gs_base = data;
1332 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1333 struct loaded_vmcs *buddy)
1335 struct vcpu_vmx *vmx = to_vmx(vcpu);
1336 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1339 if (!already_loaded) {
1340 loaded_vmcs_clear(vmx->loaded_vmcs);
1341 local_irq_disable();
1344 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1345 * this cpu's percpu list, otherwise it may not yet be deleted
1346 * from its previous cpu's percpu list. Pairs with the
1347 * smb_wmb() in __loaded_vmcs_clear().
1351 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1352 &per_cpu(loaded_vmcss_on_cpu, cpu));
1356 prev = per_cpu(current_vmcs, cpu);
1357 if (prev != vmx->loaded_vmcs->vmcs) {
1358 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1359 vmcs_load(vmx->loaded_vmcs->vmcs);
1362 * No indirect branch prediction barrier needed when switching
1363 * the active VMCS within a guest, e.g. on nested VM-Enter.
1364 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1366 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1367 indirect_branch_prediction_barrier();
1370 if (!already_loaded) {
1371 void *gdt = get_current_gdt_ro();
1372 unsigned long sysenter_esp;
1375 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1376 * TLB entries from its previous association with the vCPU.
1378 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1381 * Linux uses per-cpu TSS and GDT, so set these when switching
1382 * processors. See 22.2.4.
1384 vmcs_writel(HOST_TR_BASE,
1385 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1386 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1388 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1389 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1391 vmx->loaded_vmcs->cpu = cpu;
1394 /* Setup TSC multiplier */
1395 if (kvm_has_tsc_control &&
1396 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1397 decache_tsc_multiplier(vmx);
1401 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1402 * vcpu mutex is already taken.
1404 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1406 struct vcpu_vmx *vmx = to_vmx(vcpu);
1408 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1410 vmx_vcpu_pi_load(vcpu, cpu);
1412 vmx->host_debugctlmsr = get_debugctlmsr();
1415 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1417 vmx_vcpu_pi_put(vcpu);
1419 vmx_prepare_switch_to_host(to_vmx(vcpu));
1422 static bool emulation_required(struct kvm_vcpu *vcpu)
1424 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1427 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1429 struct vcpu_vmx *vmx = to_vmx(vcpu);
1430 unsigned long rflags, save_rflags;
1432 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1433 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1434 rflags = vmcs_readl(GUEST_RFLAGS);
1435 if (vmx->rmode.vm86_active) {
1436 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1437 save_rflags = vmx->rmode.save_rflags;
1438 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1440 vmx->rflags = rflags;
1445 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1447 struct vcpu_vmx *vmx = to_vmx(vcpu);
1448 unsigned long old_rflags;
1450 if (is_unrestricted_guest(vcpu)) {
1451 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1452 vmx->rflags = rflags;
1453 vmcs_writel(GUEST_RFLAGS, rflags);
1457 old_rflags = vmx_get_rflags(vcpu);
1458 vmx->rflags = rflags;
1459 if (vmx->rmode.vm86_active) {
1460 vmx->rmode.save_rflags = rflags;
1461 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1463 vmcs_writel(GUEST_RFLAGS, rflags);
1465 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1466 vmx->emulation_required = emulation_required(vcpu);
1469 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1471 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1474 if (interruptibility & GUEST_INTR_STATE_STI)
1475 ret |= KVM_X86_SHADOW_INT_STI;
1476 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1477 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1482 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1484 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1485 u32 interruptibility = interruptibility_old;
1487 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1489 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1490 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1491 else if (mask & KVM_X86_SHADOW_INT_STI)
1492 interruptibility |= GUEST_INTR_STATE_STI;
1494 if ((interruptibility != interruptibility_old))
1495 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1498 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1500 struct vcpu_vmx *vmx = to_vmx(vcpu);
1501 unsigned long value;
1504 * Any MSR write that attempts to change bits marked reserved will
1507 if (data & vmx->pt_desc.ctl_bitmask)
1511 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1512 * result in a #GP unless the same write also clears TraceEn.
1514 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1515 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1519 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1520 * and FabricEn would cause #GP, if
1521 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1523 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1524 !(data & RTIT_CTL_FABRIC_EN) &&
1525 !intel_pt_validate_cap(vmx->pt_desc.caps,
1526 PT_CAP_single_range_output))
1530 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1531 * utilize encodings marked reserved will cause a #GP fault.
1533 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1534 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1535 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1536 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1538 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1539 PT_CAP_cycle_thresholds);
1540 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1541 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1542 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1544 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1545 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1546 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1547 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1551 * If ADDRx_CFG is reserved or the encodings is >2 will
1552 * cause a #GP fault.
1554 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1555 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1557 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1558 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1560 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1561 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1563 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1564 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1570 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
1573 * Emulation of instructions in SGX enclaves is impossible as RIP does
1574 * not point tthe failing instruction, and even if it did, the code
1575 * stream is inaccessible. Inject #UD instead of exiting to userspace
1576 * so that guest userspace can't DoS the guest simply by triggering
1577 * emulation (enclaves are CPL3 only).
1579 if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1580 kvm_queue_exception(vcpu, UD_VECTOR);
1586 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1588 union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1589 unsigned long rip, orig_rip;
1593 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1594 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1595 * set when EPT misconfig occurs. In practice, real hardware updates
1596 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1597 * (namely Hyper-V) don't set it due to it being undefined behavior,
1598 * i.e. we end up advancing IP with some random value.
1600 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1601 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1602 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1605 * Emulating an enclave's instructions isn't supported as KVM
1606 * cannot access the enclave's memory or its true RIP, e.g. the
1607 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1608 * the RIP that actually triggered the VM-Exit. But, because
1609 * most instructions that cause VM-Exit will #UD in an enclave,
1610 * most instruction-based VM-Exits simply do not occur.
1612 * There are a few exceptions, notably the debug instructions
1613 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1614 * and generate #DB/#BP as expected, which KVM might intercept.
1615 * But again, the CPU does the dirty work and saves an instr
1616 * length of zero so VMMs don't shoot themselves in the foot.
1617 * WARN if KVM tries to skip a non-zero length instruction on
1618 * a VM-Exit from an enclave.
1623 WARN(exit_reason.enclave_mode,
1624 "KVM: skipping instruction after SGX enclave VM-Exit");
1626 orig_rip = kvm_rip_read(vcpu);
1627 rip = orig_rip + instr_len;
1628 #ifdef CONFIG_X86_64
1630 * We need to mask out the high 32 bits of RIP if not in 64-bit
1631 * mode, but just finding out that we are in 64-bit mode is
1632 * quite expensive. Only do it if there was a carry.
1634 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1637 kvm_rip_write(vcpu, rip);
1639 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1644 /* skipping an emulated instruction also counts */
1645 vmx_set_interrupt_shadow(vcpu, 0);
1651 * Recognizes a pending MTF VM-exit and records the nested state for later
1654 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1656 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1657 struct vcpu_vmx *vmx = to_vmx(vcpu);
1659 if (!is_guest_mode(vcpu))
1663 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1664 * T-bit traps. As instruction emulation is completed (i.e. at the
1665 * instruction boundary), any #DB exception pending delivery must be a
1666 * debug-trap. Record the pending MTF state to be delivered in
1667 * vmx_check_nested_events().
1669 if (nested_cpu_has_mtf(vmcs12) &&
1670 (!vcpu->arch.exception.pending ||
1671 vcpu->arch.exception.nr == DB_VECTOR))
1672 vmx->nested.mtf_pending = true;
1674 vmx->nested.mtf_pending = false;
1677 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1679 vmx_update_emulated_instruction(vcpu);
1680 return skip_emulated_instruction(vcpu);
1683 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1686 * Ensure that we clear the HLT state in the VMCS. We don't need to
1687 * explicitly skip the instruction because if the HLT state is set,
1688 * then the instruction is already executing and RIP has already been
1691 if (kvm_hlt_in_guest(vcpu->kvm) &&
1692 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1693 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1696 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1698 struct vcpu_vmx *vmx = to_vmx(vcpu);
1699 unsigned nr = vcpu->arch.exception.nr;
1700 bool has_error_code = vcpu->arch.exception.has_error_code;
1701 u32 error_code = vcpu->arch.exception.error_code;
1702 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1704 kvm_deliver_exception_payload(vcpu);
1706 if (has_error_code) {
1707 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1708 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1711 if (vmx->rmode.vm86_active) {
1713 if (kvm_exception_is_soft(nr))
1714 inc_eip = vcpu->arch.event_exit_inst_len;
1715 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1719 WARN_ON_ONCE(vmx->emulation_required);
1721 if (kvm_exception_is_soft(nr)) {
1722 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1723 vmx->vcpu.arch.event_exit_inst_len);
1724 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1726 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1728 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1730 vmx_clear_hlt(vcpu);
1733 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
1734 bool load_into_hardware)
1736 struct vmx_uret_msr *uret_msr;
1738 uret_msr = vmx_find_uret_msr(vmx, msr);
1742 uret_msr->load_into_hardware = load_into_hardware;
1746 * Set up the vmcs to automatically save and restore system
1747 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1748 * mode, as fiddling with msrs is very expensive.
1750 static void setup_msrs(struct vcpu_vmx *vmx)
1752 #ifdef CONFIG_X86_64
1753 bool load_syscall_msrs;
1756 * The SYSCALL MSRs are only needed on long mode guests, and only
1757 * when EFER.SCE is set.
1759 load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
1760 (vmx->vcpu.arch.efer & EFER_SCE);
1762 vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
1763 vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
1764 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
1766 vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
1768 vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
1769 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
1770 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
1773 * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
1774 * kernel and old userspace. If those guests run on a tsx=off host, do
1775 * allow guests to use TSX_CTRL, but don't change the value in hardware
1776 * so that TSX remains always disabled.
1778 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
1780 if (cpu_has_vmx_msr_bitmap())
1781 vmx_update_msr_bitmap(&vmx->vcpu);
1784 * The set of MSRs to load may have changed, reload MSRs before the
1787 vmx->guest_uret_msrs_loaded = false;
1790 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1792 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1793 u64 g_tsc_offset = 0;
1796 * We're here if L1 chose not to trap WRMSR to TSC. According
1797 * to the spec, this should set L1's TSC; The offset that L1
1798 * set for L2 remains unchanged, and still needs to be added
1799 * to the newly set TSC to get L2's TSC.
1801 if (is_guest_mode(vcpu) &&
1802 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
1803 g_tsc_offset = vmcs12->tsc_offset;
1805 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1806 vcpu->arch.tsc_offset - g_tsc_offset,
1808 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1809 return offset + g_tsc_offset;
1813 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1814 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1815 * all guests if the "nested" module option is off, and can also be disabled
1816 * for a single guest by disabling its VMX cpuid bit.
1818 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1820 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1823 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1826 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1828 return !(val & ~valid_bits);
1831 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1833 switch (msr->index) {
1834 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1837 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1838 case MSR_IA32_PERF_CAPABILITIES:
1839 msr->data = vmx_get_perf_capabilities();
1842 return KVM_MSR_RET_INVALID;
1847 * Reads an msr value (of 'msr_index') into 'pdata'.
1848 * Returns 0 on success, non-0 otherwise.
1849 * Assumes vcpu_load() was already called.
1851 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1853 struct vcpu_vmx *vmx = to_vmx(vcpu);
1854 struct vmx_uret_msr *msr;
1857 switch (msr_info->index) {
1858 #ifdef CONFIG_X86_64
1860 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1863 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1865 case MSR_KERNEL_GS_BASE:
1866 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1870 return kvm_get_msr_common(vcpu, msr_info);
1871 case MSR_IA32_TSX_CTRL:
1872 if (!msr_info->host_initiated &&
1873 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1876 case MSR_IA32_UMWAIT_CONTROL:
1877 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1880 msr_info->data = vmx->msr_ia32_umwait_control;
1882 case MSR_IA32_SPEC_CTRL:
1883 if (!msr_info->host_initiated &&
1884 !guest_has_spec_ctrl_msr(vcpu))
1887 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1889 case MSR_IA32_SYSENTER_CS:
1890 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1892 case MSR_IA32_SYSENTER_EIP:
1893 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1895 case MSR_IA32_SYSENTER_ESP:
1896 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1898 case MSR_IA32_BNDCFGS:
1899 if (!kvm_mpx_supported() ||
1900 (!msr_info->host_initiated &&
1901 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1903 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1905 case MSR_IA32_MCG_EXT_CTL:
1906 if (!msr_info->host_initiated &&
1907 !(vmx->msr_ia32_feature_control &
1908 FEAT_CTL_LMCE_ENABLED))
1910 msr_info->data = vcpu->arch.mcg_ext_ctl;
1912 case MSR_IA32_FEAT_CTL:
1913 msr_info->data = vmx->msr_ia32_feature_control;
1915 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
1916 if (!msr_info->host_initiated &&
1917 !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
1919 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
1920 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
1922 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1923 if (!nested_vmx_allowed(vcpu))
1925 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1929 * Enlightened VMCS v1 doesn't have certain fields, but buggy
1930 * Hyper-V versions are still trying to use corresponding
1931 * features when they are exposed. Filter out the essential
1934 if (!msr_info->host_initiated &&
1935 vmx->nested.enlightened_vmcs_enabled)
1936 nested_evmcs_filter_control_msr(msr_info->index,
1939 case MSR_IA32_RTIT_CTL:
1940 if (!vmx_pt_mode_is_host_guest())
1942 msr_info->data = vmx->pt_desc.guest.ctl;
1944 case MSR_IA32_RTIT_STATUS:
1945 if (!vmx_pt_mode_is_host_guest())
1947 msr_info->data = vmx->pt_desc.guest.status;
1949 case MSR_IA32_RTIT_CR3_MATCH:
1950 if (!vmx_pt_mode_is_host_guest() ||
1951 !intel_pt_validate_cap(vmx->pt_desc.caps,
1952 PT_CAP_cr3_filtering))
1954 msr_info->data = vmx->pt_desc.guest.cr3_match;
1956 case MSR_IA32_RTIT_OUTPUT_BASE:
1957 if (!vmx_pt_mode_is_host_guest() ||
1958 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1959 PT_CAP_topa_output) &&
1960 !intel_pt_validate_cap(vmx->pt_desc.caps,
1961 PT_CAP_single_range_output)))
1963 msr_info->data = vmx->pt_desc.guest.output_base;
1965 case MSR_IA32_RTIT_OUTPUT_MASK:
1966 if (!vmx_pt_mode_is_host_guest() ||
1967 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1968 PT_CAP_topa_output) &&
1969 !intel_pt_validate_cap(vmx->pt_desc.caps,
1970 PT_CAP_single_range_output)))
1972 msr_info->data = vmx->pt_desc.guest.output_mask;
1974 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1975 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1976 if (!vmx_pt_mode_is_host_guest() ||
1977 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1978 PT_CAP_num_address_ranges)))
1981 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1983 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1985 case MSR_IA32_DEBUGCTLMSR:
1986 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
1990 msr = vmx_find_uret_msr(vmx, msr_info->index);
1992 msr_info->data = msr->data;
1995 return kvm_get_msr_common(vcpu, msr_info);
2001 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
2004 #ifdef CONFIG_X86_64
2005 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
2008 return (unsigned long)data;
2011 static u64 vcpu_supported_debugctl(struct kvm_vcpu *vcpu)
2013 u64 debugctl = vmx_supported_debugctl();
2015 if (!intel_pmu_lbr_is_enabled(vcpu))
2016 debugctl &= ~DEBUGCTLMSR_LBR_MASK;
2018 if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
2019 debugctl &= ~DEBUGCTLMSR_BUS_LOCK_DETECT;
2025 * Writes msr value into the appropriate "register".
2026 * Returns 0 on success, non-0 otherwise.
2027 * Assumes vcpu_load() was already called.
2029 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2031 struct vcpu_vmx *vmx = to_vmx(vcpu);
2032 struct vmx_uret_msr *msr;
2034 u32 msr_index = msr_info->index;
2035 u64 data = msr_info->data;
2038 switch (msr_index) {
2040 ret = kvm_set_msr_common(vcpu, msr_info);
2042 #ifdef CONFIG_X86_64
2044 vmx_segment_cache_clear(vmx);
2045 vmcs_writel(GUEST_FS_BASE, data);
2048 vmx_segment_cache_clear(vmx);
2049 vmcs_writel(GUEST_GS_BASE, data);
2051 case MSR_KERNEL_GS_BASE:
2052 vmx_write_guest_kernel_gs_base(vmx, data);
2055 case MSR_IA32_SYSENTER_CS:
2056 if (is_guest_mode(vcpu))
2057 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2058 vmcs_write32(GUEST_SYSENTER_CS, data);
2060 case MSR_IA32_SYSENTER_EIP:
2061 if (is_guest_mode(vcpu)) {
2062 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2063 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2065 vmcs_writel(GUEST_SYSENTER_EIP, data);
2067 case MSR_IA32_SYSENTER_ESP:
2068 if (is_guest_mode(vcpu)) {
2069 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2070 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2072 vmcs_writel(GUEST_SYSENTER_ESP, data);
2074 case MSR_IA32_DEBUGCTLMSR: {
2075 u64 invalid = data & ~vcpu_supported_debugctl(vcpu);
2076 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2077 if (report_ignored_msrs)
2078 vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
2080 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2081 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2087 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2088 VM_EXIT_SAVE_DEBUG_CONTROLS)
2089 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2091 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2092 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2093 (data & DEBUGCTLMSR_LBR))
2094 intel_pmu_create_guest_lbr_event(vcpu);
2097 case MSR_IA32_BNDCFGS:
2098 if (!kvm_mpx_supported() ||
2099 (!msr_info->host_initiated &&
2100 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2102 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2103 (data & MSR_IA32_BNDCFGS_RSVD))
2105 vmcs_write64(GUEST_BNDCFGS, data);
2107 case MSR_IA32_UMWAIT_CONTROL:
2108 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2111 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2112 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2115 vmx->msr_ia32_umwait_control = data;
2117 case MSR_IA32_SPEC_CTRL:
2118 if (!msr_info->host_initiated &&
2119 !guest_has_spec_ctrl_msr(vcpu))
2122 if (kvm_spec_ctrl_test_value(data))
2125 vmx->spec_ctrl = data;
2131 * When it's written (to non-zero) for the first time, pass
2135 * The handling of the MSR bitmap for L2 guests is done in
2136 * nested_vmx_prepare_msr_bitmap. We should not touch the
2137 * vmcs02.msr_bitmap here since it gets completely overwritten
2138 * in the merging. We update the vmcs01 here for L1 as well
2139 * since it will end up touching the MSR anyway now.
2141 vmx_disable_intercept_for_msr(vcpu,
2145 case MSR_IA32_TSX_CTRL:
2146 if (!msr_info->host_initiated &&
2147 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2149 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2152 case MSR_IA32_PRED_CMD:
2153 if (!msr_info->host_initiated &&
2154 !guest_has_pred_cmd_msr(vcpu))
2157 if (data & ~PRED_CMD_IBPB)
2159 if (!boot_cpu_has(X86_FEATURE_IBPB))
2164 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2168 * When it's written (to non-zero) for the first time, pass
2172 * The handling of the MSR bitmap for L2 guests is done in
2173 * nested_vmx_prepare_msr_bitmap. We should not touch the
2174 * vmcs02.msr_bitmap here since it gets completely overwritten
2177 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
2179 case MSR_IA32_CR_PAT:
2180 if (!kvm_pat_valid(data))
2183 if (is_guest_mode(vcpu) &&
2184 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2185 get_vmcs12(vcpu)->guest_ia32_pat = data;
2187 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2188 vmcs_write64(GUEST_IA32_PAT, data);
2189 vcpu->arch.pat = data;
2192 ret = kvm_set_msr_common(vcpu, msr_info);
2194 case MSR_IA32_TSC_ADJUST:
2195 ret = kvm_set_msr_common(vcpu, msr_info);
2197 case MSR_IA32_MCG_EXT_CTL:
2198 if ((!msr_info->host_initiated &&
2199 !(to_vmx(vcpu)->msr_ia32_feature_control &
2200 FEAT_CTL_LMCE_ENABLED)) ||
2201 (data & ~MCG_EXT_CTL_LMCE_EN))
2203 vcpu->arch.mcg_ext_ctl = data;
2205 case MSR_IA32_FEAT_CTL:
2206 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2207 (to_vmx(vcpu)->msr_ia32_feature_control &
2208 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2210 vmx->msr_ia32_feature_control = data;
2211 if (msr_info->host_initiated && data == 0)
2212 vmx_leave_nested(vcpu);
2214 /* SGX may be enabled/disabled by guest's firmware */
2215 vmx_write_encls_bitmap(vcpu, NULL);
2217 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2219 * On real hardware, the LE hash MSRs are writable before
2220 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2221 * at which point SGX related bits in IA32_FEATURE_CONTROL
2224 * KVM does not emulate SGX activation for simplicity, so
2225 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2226 * is unlocked. This is technically not architectural
2227 * behavior, but it's close enough.
2229 if (!msr_info->host_initiated &&
2230 (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2231 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2232 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2234 vmx->msr_ia32_sgxlepubkeyhash
2235 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2237 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2238 if (!msr_info->host_initiated)
2239 return 1; /* they are read-only */
2240 if (!nested_vmx_allowed(vcpu))
2242 return vmx_set_vmx_msr(vcpu, msr_index, data);
2243 case MSR_IA32_RTIT_CTL:
2244 if (!vmx_pt_mode_is_host_guest() ||
2245 vmx_rtit_ctl_check(vcpu, data) ||
2248 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2249 vmx->pt_desc.guest.ctl = data;
2250 pt_update_intercept_for_msr(vcpu);
2252 case MSR_IA32_RTIT_STATUS:
2253 if (!pt_can_write_msr(vmx))
2255 if (data & MSR_IA32_RTIT_STATUS_MASK)
2257 vmx->pt_desc.guest.status = data;
2259 case MSR_IA32_RTIT_CR3_MATCH:
2260 if (!pt_can_write_msr(vmx))
2262 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2263 PT_CAP_cr3_filtering))
2265 vmx->pt_desc.guest.cr3_match = data;
2267 case MSR_IA32_RTIT_OUTPUT_BASE:
2268 if (!pt_can_write_msr(vmx))
2270 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2271 PT_CAP_topa_output) &&
2272 !intel_pt_validate_cap(vmx->pt_desc.caps,
2273 PT_CAP_single_range_output))
2275 if (!pt_output_base_valid(vcpu, data))
2277 vmx->pt_desc.guest.output_base = data;
2279 case MSR_IA32_RTIT_OUTPUT_MASK:
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 vmx->pt_desc.guest.output_mask = data;
2289 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2290 if (!pt_can_write_msr(vmx))
2292 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2293 if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2294 PT_CAP_num_address_ranges))
2296 if (is_noncanonical_address(data, vcpu))
2299 vmx->pt_desc.guest.addr_b[index / 2] = data;
2301 vmx->pt_desc.guest.addr_a[index / 2] = data;
2303 case MSR_IA32_PERF_CAPABILITIES:
2304 if (data && !vcpu_to_pmu(vcpu)->version)
2306 if (data & PMU_CAP_LBR_FMT) {
2307 if ((data & PMU_CAP_LBR_FMT) !=
2308 (vmx_get_perf_capabilities() & PMU_CAP_LBR_FMT))
2310 if (!intel_pmu_lbr_is_compatible(vcpu))
2313 ret = kvm_set_msr_common(vcpu, msr_info);
2318 msr = vmx_find_uret_msr(vmx, msr_index);
2320 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2322 ret = kvm_set_msr_common(vcpu, msr_info);
2328 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2330 unsigned long guest_owned_bits;
2332 kvm_register_mark_available(vcpu, reg);
2336 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2339 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2341 case VCPU_EXREG_PDPTR:
2343 ept_save_pdptrs(vcpu);
2345 case VCPU_EXREG_CR0:
2346 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2348 vcpu->arch.cr0 &= ~guest_owned_bits;
2349 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2351 case VCPU_EXREG_CR3:
2352 if (is_unrestricted_guest(vcpu) ||
2353 (enable_ept && is_paging(vcpu)))
2354 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2356 case VCPU_EXREG_CR4:
2357 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2359 vcpu->arch.cr4 &= ~guest_owned_bits;
2360 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2368 static __init int cpu_has_kvm_support(void)
2370 return cpu_has_vmx();
2373 static __init int vmx_disabled_by_bios(void)
2375 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2376 !boot_cpu_has(X86_FEATURE_VMX);
2379 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2383 cr4_set_bits(X86_CR4_VMXE);
2385 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2386 _ASM_EXTABLE(1b, %l[fault])
2387 : : [vmxon_pointer] "m"(vmxon_pointer)
2392 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2393 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2394 cr4_clear_bits(X86_CR4_VMXE);
2399 static int hardware_enable(void)
2401 int cpu = raw_smp_processor_id();
2402 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2405 if (cr4_read_shadow() & X86_CR4_VMXE)
2409 * This can happen if we hot-added a CPU but failed to allocate
2410 * VP assist page for it.
2412 if (static_branch_unlikely(&enable_evmcs) &&
2413 !hv_get_vp_assist_page(cpu))
2416 intel_pt_handle_vmx(1);
2418 r = kvm_cpu_vmxon(phys_addr);
2420 intel_pt_handle_vmx(0);
2430 static void vmclear_local_loaded_vmcss(void)
2432 int cpu = raw_smp_processor_id();
2433 struct loaded_vmcs *v, *n;
2435 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2436 loaded_vmcss_on_cpu_link)
2437 __loaded_vmcs_clear(v);
2440 static void hardware_disable(void)
2442 vmclear_local_loaded_vmcss();
2445 kvm_spurious_fault();
2447 intel_pt_handle_vmx(0);
2451 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2452 * directly instead of going through cpu_has(), to ensure KVM is trapping
2453 * ENCLS whenever it's supported in hardware. It does not matter whether
2454 * the host OS supports or has enabled SGX.
2456 static bool cpu_has_sgx(void)
2458 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2461 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2462 u32 msr, u32 *result)
2464 u32 vmx_msr_low, vmx_msr_high;
2465 u32 ctl = ctl_min | ctl_opt;
2467 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2469 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2470 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2472 /* Ensure minimum (required) set of control bits are supported. */
2480 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2481 struct vmx_capability *vmx_cap)
2483 u32 vmx_msr_low, vmx_msr_high;
2484 u32 min, opt, min2, opt2;
2485 u32 _pin_based_exec_control = 0;
2486 u32 _cpu_based_exec_control = 0;
2487 u32 _cpu_based_2nd_exec_control = 0;
2488 u32 _vmexit_control = 0;
2489 u32 _vmentry_control = 0;
2491 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2492 min = CPU_BASED_HLT_EXITING |
2493 #ifdef CONFIG_X86_64
2494 CPU_BASED_CR8_LOAD_EXITING |
2495 CPU_BASED_CR8_STORE_EXITING |
2497 CPU_BASED_CR3_LOAD_EXITING |
2498 CPU_BASED_CR3_STORE_EXITING |
2499 CPU_BASED_UNCOND_IO_EXITING |
2500 CPU_BASED_MOV_DR_EXITING |
2501 CPU_BASED_USE_TSC_OFFSETTING |
2502 CPU_BASED_MWAIT_EXITING |
2503 CPU_BASED_MONITOR_EXITING |
2504 CPU_BASED_INVLPG_EXITING |
2505 CPU_BASED_RDPMC_EXITING;
2507 opt = CPU_BASED_TPR_SHADOW |
2508 CPU_BASED_USE_MSR_BITMAPS |
2509 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2510 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2511 &_cpu_based_exec_control) < 0)
2513 #ifdef CONFIG_X86_64
2514 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2515 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2516 ~CPU_BASED_CR8_STORE_EXITING;
2518 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2520 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2521 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2522 SECONDARY_EXEC_WBINVD_EXITING |
2523 SECONDARY_EXEC_ENABLE_VPID |
2524 SECONDARY_EXEC_ENABLE_EPT |
2525 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2526 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2527 SECONDARY_EXEC_DESC |
2528 SECONDARY_EXEC_ENABLE_RDTSCP |
2529 SECONDARY_EXEC_ENABLE_INVPCID |
2530 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2531 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2532 SECONDARY_EXEC_SHADOW_VMCS |
2533 SECONDARY_EXEC_XSAVES |
2534 SECONDARY_EXEC_RDSEED_EXITING |
2535 SECONDARY_EXEC_RDRAND_EXITING |
2536 SECONDARY_EXEC_ENABLE_PML |
2537 SECONDARY_EXEC_TSC_SCALING |
2538 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2539 SECONDARY_EXEC_PT_USE_GPA |
2540 SECONDARY_EXEC_PT_CONCEAL_VMX |
2541 SECONDARY_EXEC_ENABLE_VMFUNC |
2542 SECONDARY_EXEC_BUS_LOCK_DETECTION;
2544 opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2545 if (adjust_vmx_controls(min2, opt2,
2546 MSR_IA32_VMX_PROCBASED_CTLS2,
2547 &_cpu_based_2nd_exec_control) < 0)
2550 #ifndef CONFIG_X86_64
2551 if (!(_cpu_based_2nd_exec_control &
2552 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2553 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2556 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2557 _cpu_based_2nd_exec_control &= ~(
2558 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2559 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2560 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2562 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2563 &vmx_cap->ept, &vmx_cap->vpid);
2565 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2566 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2568 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2569 CPU_BASED_CR3_STORE_EXITING |
2570 CPU_BASED_INVLPG_EXITING);
2571 } else if (vmx_cap->ept) {
2573 pr_warn_once("EPT CAP should not exist if not support "
2574 "1-setting enable EPT VM-execution control\n");
2576 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2579 pr_warn_once("VPID CAP should not exist if not support "
2580 "1-setting enable VPID VM-execution control\n");
2583 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2584 #ifdef CONFIG_X86_64
2585 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2587 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2588 VM_EXIT_LOAD_IA32_PAT |
2589 VM_EXIT_LOAD_IA32_EFER |
2590 VM_EXIT_CLEAR_BNDCFGS |
2591 VM_EXIT_PT_CONCEAL_PIP |
2592 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2593 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2594 &_vmexit_control) < 0)
2597 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2598 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2599 PIN_BASED_VMX_PREEMPTION_TIMER;
2600 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2601 &_pin_based_exec_control) < 0)
2604 if (cpu_has_broken_vmx_preemption_timer())
2605 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2606 if (!(_cpu_based_2nd_exec_control &
2607 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2608 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2610 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2611 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2612 VM_ENTRY_LOAD_IA32_PAT |
2613 VM_ENTRY_LOAD_IA32_EFER |
2614 VM_ENTRY_LOAD_BNDCFGS |
2615 VM_ENTRY_PT_CONCEAL_PIP |
2616 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2617 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2618 &_vmentry_control) < 0)
2622 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2623 * can't be used due to an errata where VM Exit may incorrectly clear
2624 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2625 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2627 if (boot_cpu_data.x86 == 0x6) {
2628 switch (boot_cpu_data.x86_model) {
2629 case 26: /* AAK155 */
2630 case 30: /* AAP115 */
2631 case 37: /* AAT100 */
2632 case 44: /* BC86,AAY89,BD102 */
2634 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2635 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2636 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2637 "does not work properly. Using workaround\n");
2645 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2647 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2648 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2651 #ifdef CONFIG_X86_64
2652 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2653 if (vmx_msr_high & (1u<<16))
2657 /* Require Write-Back (WB) memory type for VMCS accesses. */
2658 if (((vmx_msr_high >> 18) & 15) != 6)
2661 vmcs_conf->size = vmx_msr_high & 0x1fff;
2662 vmcs_conf->order = get_order(vmcs_conf->size);
2663 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2665 vmcs_conf->revision_id = vmx_msr_low;
2667 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2668 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2669 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2670 vmcs_conf->vmexit_ctrl = _vmexit_control;
2671 vmcs_conf->vmentry_ctrl = _vmentry_control;
2673 #if IS_ENABLED(CONFIG_HYPERV)
2674 if (enlightened_vmcs)
2675 evmcs_sanitize_exec_ctrls(vmcs_conf);
2681 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2683 int node = cpu_to_node(cpu);
2687 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2690 vmcs = page_address(pages);
2691 memset(vmcs, 0, vmcs_config.size);
2693 /* KVM supports Enlightened VMCS v1 only */
2694 if (static_branch_unlikely(&enable_evmcs))
2695 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2697 vmcs->hdr.revision_id = vmcs_config.revision_id;
2700 vmcs->hdr.shadow_vmcs = 1;
2704 void free_vmcs(struct vmcs *vmcs)
2706 free_pages((unsigned long)vmcs, vmcs_config.order);
2710 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2712 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2714 if (!loaded_vmcs->vmcs)
2716 loaded_vmcs_clear(loaded_vmcs);
2717 free_vmcs(loaded_vmcs->vmcs);
2718 loaded_vmcs->vmcs = NULL;
2719 if (loaded_vmcs->msr_bitmap)
2720 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2721 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2724 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2726 loaded_vmcs->vmcs = alloc_vmcs(false);
2727 if (!loaded_vmcs->vmcs)
2730 vmcs_clear(loaded_vmcs->vmcs);
2732 loaded_vmcs->shadow_vmcs = NULL;
2733 loaded_vmcs->hv_timer_soft_disabled = false;
2734 loaded_vmcs->cpu = -1;
2735 loaded_vmcs->launched = 0;
2737 if (cpu_has_vmx_msr_bitmap()) {
2738 loaded_vmcs->msr_bitmap = (unsigned long *)
2739 __get_free_page(GFP_KERNEL_ACCOUNT);
2740 if (!loaded_vmcs->msr_bitmap)
2742 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2744 if (IS_ENABLED(CONFIG_HYPERV) &&
2745 static_branch_unlikely(&enable_evmcs) &&
2746 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2747 struct hv_enlightened_vmcs *evmcs =
2748 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2750 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2754 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2755 memset(&loaded_vmcs->controls_shadow, 0,
2756 sizeof(struct vmcs_controls_shadow));
2761 free_loaded_vmcs(loaded_vmcs);
2765 static void free_kvm_area(void)
2769 for_each_possible_cpu(cpu) {
2770 free_vmcs(per_cpu(vmxarea, cpu));
2771 per_cpu(vmxarea, cpu) = NULL;
2775 static __init int alloc_kvm_area(void)
2779 for_each_possible_cpu(cpu) {
2782 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2789 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2790 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2791 * revision_id reported by MSR_IA32_VMX_BASIC.
2793 * However, even though not explicitly documented by
2794 * TLFS, VMXArea passed as VMXON argument should
2795 * still be marked with revision_id reported by
2798 if (static_branch_unlikely(&enable_evmcs))
2799 vmcs->hdr.revision_id = vmcs_config.revision_id;
2801 per_cpu(vmxarea, cpu) = vmcs;
2806 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2807 struct kvm_segment *save)
2809 if (!emulate_invalid_guest_state) {
2811 * CS and SS RPL should be equal during guest entry according
2812 * to VMX spec, but in reality it is not always so. Since vcpu
2813 * is in the middle of the transition from real mode to
2814 * protected mode it is safe to assume that RPL 0 is a good
2817 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2818 save->selector &= ~SEGMENT_RPL_MASK;
2819 save->dpl = save->selector & SEGMENT_RPL_MASK;
2822 vmx_set_segment(vcpu, save, seg);
2825 static void enter_pmode(struct kvm_vcpu *vcpu)
2827 unsigned long flags;
2828 struct vcpu_vmx *vmx = to_vmx(vcpu);
2831 * Update real mode segment cache. It may be not up-to-date if segment
2832 * register was written while vcpu was in a guest mode.
2834 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2835 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2836 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2837 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2838 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2839 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2841 vmx->rmode.vm86_active = 0;
2843 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2845 flags = vmcs_readl(GUEST_RFLAGS);
2846 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2847 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2848 vmcs_writel(GUEST_RFLAGS, flags);
2850 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2851 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2853 vmx_update_exception_bitmap(vcpu);
2855 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2856 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2857 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2858 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2859 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2860 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2863 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2865 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2866 struct kvm_segment var = *save;
2869 if (seg == VCPU_SREG_CS)
2872 if (!emulate_invalid_guest_state) {
2873 var.selector = var.base >> 4;
2874 var.base = var.base & 0xffff0;
2884 if (save->base & 0xf)
2885 printk_once(KERN_WARNING "kvm: segment base is not "
2886 "paragraph aligned when entering "
2887 "protected mode (seg=%d)", seg);
2890 vmcs_write16(sf->selector, var.selector);
2891 vmcs_writel(sf->base, var.base);
2892 vmcs_write32(sf->limit, var.limit);
2893 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2896 static void enter_rmode(struct kvm_vcpu *vcpu)
2898 unsigned long flags;
2899 struct vcpu_vmx *vmx = to_vmx(vcpu);
2900 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2902 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2903 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2904 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2905 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2906 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2907 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2908 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2910 vmx->rmode.vm86_active = 1;
2913 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2914 * vcpu. Warn the user that an update is overdue.
2916 if (!kvm_vmx->tss_addr)
2917 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2918 "called before entering vcpu\n");
2920 vmx_segment_cache_clear(vmx);
2922 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2923 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2924 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2926 flags = vmcs_readl(GUEST_RFLAGS);
2927 vmx->rmode.save_rflags = flags;
2929 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2931 vmcs_writel(GUEST_RFLAGS, flags);
2932 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2933 vmx_update_exception_bitmap(vcpu);
2935 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2936 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2937 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2938 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2939 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2940 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2942 kvm_mmu_reset_context(vcpu);
2945 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2947 struct vcpu_vmx *vmx = to_vmx(vcpu);
2948 struct vmx_uret_msr *msr = vmx_find_uret_msr(vmx, MSR_EFER);
2950 /* Nothing to do if hardware doesn't support EFER. */
2954 vcpu->arch.efer = efer;
2955 if (efer & EFER_LMA) {
2956 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2959 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2961 msr->data = efer & ~EFER_LME;
2967 #ifdef CONFIG_X86_64
2969 static void enter_lmode(struct kvm_vcpu *vcpu)
2973 vmx_segment_cache_clear(to_vmx(vcpu));
2975 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2976 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2977 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2979 vmcs_write32(GUEST_TR_AR_BYTES,
2980 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2981 | VMX_AR_TYPE_BUSY_64_TSS);
2983 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2986 static void exit_lmode(struct kvm_vcpu *vcpu)
2988 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2989 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2994 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
2996 struct vcpu_vmx *vmx = to_vmx(vcpu);
2999 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
3000 * the CPU is not required to invalidate guest-physical mappings on
3001 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
3002 * associated with the root EPT structure and not any particular VPID
3003 * (INVVPID also isn't required to invalidate guest-physical mappings).
3007 } else if (enable_vpid) {
3008 if (cpu_has_vmx_invvpid_global()) {
3009 vpid_sync_vcpu_global();
3011 vpid_sync_vcpu_single(vmx->vpid);
3012 vpid_sync_vcpu_single(vmx->nested.vpid02);
3017 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
3019 struct kvm_mmu *mmu = vcpu->arch.mmu;
3020 u64 root_hpa = mmu->root_hpa;
3022 /* No flush required if the current context is invalid. */
3023 if (!VALID_PAGE(root_hpa))
3027 ept_sync_context(construct_eptp(vcpu, root_hpa,
3028 mmu->shadow_root_level));
3029 else if (!is_guest_mode(vcpu))
3030 vpid_sync_context(to_vmx(vcpu)->vpid);
3032 vpid_sync_context(nested_get_vpid02(vcpu));
3035 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3038 * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
3039 * vmx_flush_tlb_guest() for an explanation of why this is ok.
3041 vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
3044 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3047 * vpid_sync_context() is a nop if vmx->vpid==0, e.g. if enable_vpid==0
3048 * or a vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit
3049 * are required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3050 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3051 * i.e. no explicit INVVPID is necessary.
3053 vpid_sync_context(to_vmx(vcpu)->vpid);
3056 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3058 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3060 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3063 if (is_pae_paging(vcpu)) {
3064 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3065 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3066 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3067 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3071 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3073 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3075 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3078 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3079 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3080 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3081 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3083 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
3086 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3088 struct kvm_vcpu *vcpu)
3090 struct vcpu_vmx *vmx = to_vmx(vcpu);
3092 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3093 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3094 if (!(cr0 & X86_CR0_PG)) {
3095 /* From paging/starting to nonpaging */
3096 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3097 CPU_BASED_CR3_STORE_EXITING);
3098 vcpu->arch.cr0 = cr0;
3099 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3100 } else if (!is_paging(vcpu)) {
3101 /* From nonpaging to paging */
3102 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3103 CPU_BASED_CR3_STORE_EXITING);
3104 vcpu->arch.cr0 = cr0;
3105 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3108 if (!(cr0 & X86_CR0_WP))
3109 *hw_cr0 &= ~X86_CR0_WP;
3112 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3114 struct vcpu_vmx *vmx = to_vmx(vcpu);
3115 unsigned long hw_cr0;
3117 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3118 if (is_unrestricted_guest(vcpu))
3119 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3121 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3123 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3126 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3130 #ifdef CONFIG_X86_64
3131 if (vcpu->arch.efer & EFER_LME) {
3132 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3134 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3139 if (enable_ept && !is_unrestricted_guest(vcpu))
3140 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3142 vmcs_writel(CR0_READ_SHADOW, cr0);
3143 vmcs_writel(GUEST_CR0, hw_cr0);
3144 vcpu->arch.cr0 = cr0;
3145 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3147 /* depends on vcpu->arch.cr0 to be set to a new value */
3148 vmx->emulation_required = emulation_required(vcpu);
3151 static int vmx_get_max_tdp_level(void)
3153 if (cpu_has_vmx_ept_5levels())
3158 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3160 u64 eptp = VMX_EPTP_MT_WB;
3162 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3164 if (enable_ept_ad_bits &&
3165 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3166 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3172 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3175 struct kvm *kvm = vcpu->kvm;
3176 bool update_guest_cr3 = true;
3177 unsigned long guest_cr3;
3181 eptp = construct_eptp(vcpu, root_hpa, root_level);
3182 vmcs_write64(EPT_POINTER, eptp);
3184 hv_track_root_ept(vcpu, root_hpa);
3186 if (!enable_unrestricted_guest && !is_paging(vcpu))
3187 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3188 else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3189 guest_cr3 = vcpu->arch.cr3;
3190 else /* vmcs01.GUEST_CR3 is already up-to-date. */
3191 update_guest_cr3 = false;
3192 vmx_ept_load_pdptrs(vcpu);
3194 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3197 if (update_guest_cr3)
3198 vmcs_writel(GUEST_CR3, guest_cr3);
3201 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3204 * We operate under the default treatment of SMM, so VMX cannot be
3205 * enabled under SMM. Note, whether or not VMXE is allowed at all is
3206 * handled by kvm_is_valid_cr4().
3208 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3211 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3217 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3219 unsigned long old_cr4 = vcpu->arch.cr4;
3220 struct vcpu_vmx *vmx = to_vmx(vcpu);
3222 * Pass through host's Machine Check Enable value to hw_cr4, which
3223 * is in force while we are in guest mode. Do not let guests control
3224 * this bit, even if host CR4.MCE == 0.
3226 unsigned long hw_cr4;
3228 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3229 if (is_unrestricted_guest(vcpu))
3230 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3231 else if (vmx->rmode.vm86_active)
3232 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3234 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3236 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3237 if (cr4 & X86_CR4_UMIP) {
3238 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3239 hw_cr4 &= ~X86_CR4_UMIP;
3240 } else if (!is_guest_mode(vcpu) ||
3241 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3242 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3246 vcpu->arch.cr4 = cr4;
3247 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3249 if (!is_unrestricted_guest(vcpu)) {
3251 if (!is_paging(vcpu)) {
3252 hw_cr4 &= ~X86_CR4_PAE;
3253 hw_cr4 |= X86_CR4_PSE;
3254 } else if (!(cr4 & X86_CR4_PAE)) {
3255 hw_cr4 &= ~X86_CR4_PAE;
3260 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3261 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3262 * to be manually disabled when guest switches to non-paging
3265 * If !enable_unrestricted_guest, the CPU is always running
3266 * with CR0.PG=1 and CR4 needs to be modified.
3267 * If enable_unrestricted_guest, the CPU automatically
3268 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3270 if (!is_paging(vcpu))
3271 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3274 vmcs_writel(CR4_READ_SHADOW, cr4);
3275 vmcs_writel(GUEST_CR4, hw_cr4);
3277 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3278 kvm_update_cpuid_runtime(vcpu);
3281 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3283 struct vcpu_vmx *vmx = to_vmx(vcpu);
3286 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3287 *var = vmx->rmode.segs[seg];
3288 if (seg == VCPU_SREG_TR
3289 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3291 var->base = vmx_read_guest_seg_base(vmx, seg);
3292 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3295 var->base = vmx_read_guest_seg_base(vmx, seg);
3296 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3297 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3298 ar = vmx_read_guest_seg_ar(vmx, seg);
3299 var->unusable = (ar >> 16) & 1;
3300 var->type = ar & 15;
3301 var->s = (ar >> 4) & 1;
3302 var->dpl = (ar >> 5) & 3;
3304 * Some userspaces do not preserve unusable property. Since usable
3305 * segment has to be present according to VMX spec we can use present
3306 * property to amend userspace bug by making unusable segment always
3307 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3308 * segment as unusable.
3310 var->present = !var->unusable;
3311 var->avl = (ar >> 12) & 1;
3312 var->l = (ar >> 13) & 1;
3313 var->db = (ar >> 14) & 1;
3314 var->g = (ar >> 15) & 1;
3317 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3319 struct kvm_segment s;
3321 if (to_vmx(vcpu)->rmode.vm86_active) {
3322 vmx_get_segment(vcpu, &s, seg);
3325 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3328 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3330 struct vcpu_vmx *vmx = to_vmx(vcpu);
3332 if (unlikely(vmx->rmode.vm86_active))
3335 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3336 return VMX_AR_DPL(ar);
3340 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3344 if (var->unusable || !var->present)
3347 ar = var->type & 15;
3348 ar |= (var->s & 1) << 4;
3349 ar |= (var->dpl & 3) << 5;
3350 ar |= (var->present & 1) << 7;
3351 ar |= (var->avl & 1) << 12;
3352 ar |= (var->l & 1) << 13;
3353 ar |= (var->db & 1) << 14;
3354 ar |= (var->g & 1) << 15;
3360 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3362 struct vcpu_vmx *vmx = to_vmx(vcpu);
3363 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3365 vmx_segment_cache_clear(vmx);
3367 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3368 vmx->rmode.segs[seg] = *var;
3369 if (seg == VCPU_SREG_TR)
3370 vmcs_write16(sf->selector, var->selector);
3372 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3376 vmcs_writel(sf->base, var->base);
3377 vmcs_write32(sf->limit, var->limit);
3378 vmcs_write16(sf->selector, var->selector);
3381 * Fix the "Accessed" bit in AR field of segment registers for older
3383 * IA32 arch specifies that at the time of processor reset the
3384 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3385 * is setting it to 0 in the userland code. This causes invalid guest
3386 * state vmexit when "unrestricted guest" mode is turned on.
3387 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3388 * tree. Newer qemu binaries with that qemu fix would not need this
3391 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3392 var->type |= 0x1; /* Accessed */
3394 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3397 vmx->emulation_required = emulation_required(vcpu);
3400 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3402 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3404 *db = (ar >> 14) & 1;
3405 *l = (ar >> 13) & 1;
3408 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3410 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3411 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3414 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3416 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3417 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3420 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3422 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3423 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3426 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3428 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3429 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3432 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3434 struct kvm_segment var;
3437 vmx_get_segment(vcpu, &var, seg);
3439 if (seg == VCPU_SREG_CS)
3441 ar = vmx_segment_access_rights(&var);
3443 if (var.base != (var.selector << 4))
3445 if (var.limit != 0xffff)
3453 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3455 struct kvm_segment cs;
3456 unsigned int cs_rpl;
3458 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3459 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3463 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3467 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3468 if (cs.dpl > cs_rpl)
3471 if (cs.dpl != cs_rpl)
3477 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3481 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3483 struct kvm_segment ss;
3484 unsigned int ss_rpl;
3486 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3487 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3491 if (ss.type != 3 && ss.type != 7)
3495 if (ss.dpl != ss_rpl) /* DPL != RPL */
3503 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3505 struct kvm_segment var;
3508 vmx_get_segment(vcpu, &var, seg);
3509 rpl = var.selector & SEGMENT_RPL_MASK;
3517 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3518 if (var.dpl < rpl) /* DPL < RPL */
3522 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3528 static bool tr_valid(struct kvm_vcpu *vcpu)
3530 struct kvm_segment tr;
3532 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3536 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3538 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3546 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3548 struct kvm_segment ldtr;
3550 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3554 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3564 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3566 struct kvm_segment cs, ss;
3568 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3569 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3571 return ((cs.selector & SEGMENT_RPL_MASK) ==
3572 (ss.selector & SEGMENT_RPL_MASK));
3576 * Check if guest state is valid. Returns true if valid, false if
3578 * We assume that registers are always usable
3580 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3582 /* real mode guest state checks */
3583 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3584 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3586 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3588 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3590 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3592 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3594 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3597 /* protected mode guest state checks */
3598 if (!cs_ss_rpl_check(vcpu))
3600 if (!code_segment_valid(vcpu))
3602 if (!stack_segment_valid(vcpu))
3604 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3606 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3608 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3610 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3612 if (!tr_valid(vcpu))
3614 if (!ldtr_valid(vcpu))
3618 * - Add checks on RIP
3619 * - Add checks on RFLAGS
3625 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3627 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3631 for (i = 0; i < 3; i++) {
3632 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3636 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3637 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3641 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3647 static int init_rmode_identity_map(struct kvm *kvm)
3649 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3654 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3655 mutex_lock(&kvm->slots_lock);
3657 if (likely(kvm_vmx->ept_identity_pagetable_done))
3660 if (!kvm_vmx->ept_identity_map_addr)
3661 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3663 uaddr = __x86_set_memory_region(kvm,
3664 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3665 kvm_vmx->ept_identity_map_addr,
3667 if (IS_ERR(uaddr)) {
3672 /* Set up identity-mapping pagetable for EPT in real mode */
3673 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3674 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3675 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3676 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3681 kvm_vmx->ept_identity_pagetable_done = true;
3684 mutex_unlock(&kvm->slots_lock);
3688 static void seg_setup(int seg)
3690 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3693 vmcs_write16(sf->selector, 0);
3694 vmcs_writel(sf->base, 0);
3695 vmcs_write32(sf->limit, 0xffff);
3697 if (seg == VCPU_SREG_CS)
3698 ar |= 0x08; /* code segment */
3700 vmcs_write32(sf->ar_bytes, ar);
3703 static int alloc_apic_access_page(struct kvm *kvm)
3709 mutex_lock(&kvm->slots_lock);
3710 if (kvm->arch.apic_access_page_done)
3712 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3713 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3719 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3720 if (is_error_page(page)) {
3726 * Do not pin the page in memory, so that memory hot-unplug
3727 * is able to migrate it.
3730 kvm->arch.apic_access_page_done = true;
3732 mutex_unlock(&kvm->slots_lock);
3736 int allocate_vpid(void)
3742 spin_lock(&vmx_vpid_lock);
3743 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3744 if (vpid < VMX_NR_VPIDS)
3745 __set_bit(vpid, vmx_vpid_bitmap);
3748 spin_unlock(&vmx_vpid_lock);
3752 void free_vpid(int vpid)
3754 if (!enable_vpid || vpid == 0)
3756 spin_lock(&vmx_vpid_lock);
3757 __clear_bit(vpid, vmx_vpid_bitmap);
3758 spin_unlock(&vmx_vpid_lock);
3761 static void vmx_clear_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3763 int f = sizeof(unsigned long);
3766 __clear_bit(msr, msr_bitmap + 0x000 / f);
3767 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3768 __clear_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3771 static void vmx_clear_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3773 int f = sizeof(unsigned long);
3776 __clear_bit(msr, msr_bitmap + 0x800 / f);
3777 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3778 __clear_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3781 static void vmx_set_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3783 int f = sizeof(unsigned long);
3786 __set_bit(msr, msr_bitmap + 0x000 / f);
3787 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3788 __set_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3791 static void vmx_set_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3793 int f = sizeof(unsigned long);
3796 __set_bit(msr, msr_bitmap + 0x800 / f);
3797 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3798 __set_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3801 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3803 struct vcpu_vmx *vmx = to_vmx(vcpu);
3804 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3806 if (!cpu_has_vmx_msr_bitmap())
3809 if (static_branch_unlikely(&enable_evmcs))
3810 evmcs_touch_msr_bitmap();
3813 * Mark the desired intercept state in shadow bitmap, this is needed
3814 * for resync when the MSR filters change.
3816 if (is_valid_passthrough_msr(msr)) {
3817 int idx = possible_passthrough_msr_slot(msr);
3819 if (idx != -ENOENT) {
3820 if (type & MSR_TYPE_R)
3821 clear_bit(idx, vmx->shadow_msr_intercept.read);
3822 if (type & MSR_TYPE_W)
3823 clear_bit(idx, vmx->shadow_msr_intercept.write);
3827 if ((type & MSR_TYPE_R) &&
3828 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3829 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3830 type &= ~MSR_TYPE_R;
3833 if ((type & MSR_TYPE_W) &&
3834 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3835 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3836 type &= ~MSR_TYPE_W;
3839 if (type & MSR_TYPE_R)
3840 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3842 if (type & MSR_TYPE_W)
3843 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3846 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3848 struct vcpu_vmx *vmx = to_vmx(vcpu);
3849 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3851 if (!cpu_has_vmx_msr_bitmap())
3854 if (static_branch_unlikely(&enable_evmcs))
3855 evmcs_touch_msr_bitmap();
3858 * Mark the desired intercept state in shadow bitmap, this is needed
3859 * for resync when the MSR filter changes.
3861 if (is_valid_passthrough_msr(msr)) {
3862 int idx = possible_passthrough_msr_slot(msr);
3864 if (idx != -ENOENT) {
3865 if (type & MSR_TYPE_R)
3866 set_bit(idx, vmx->shadow_msr_intercept.read);
3867 if (type & MSR_TYPE_W)
3868 set_bit(idx, vmx->shadow_msr_intercept.write);
3872 if (type & MSR_TYPE_R)
3873 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3875 if (type & MSR_TYPE_W)
3876 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3879 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3883 if (cpu_has_secondary_exec_ctrls() &&
3884 (secondary_exec_controls_get(to_vmx(vcpu)) &
3885 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3886 mode |= MSR_BITMAP_MODE_X2APIC;
3887 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3888 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3894 static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
3896 unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3897 unsigned long read_intercept;
3900 read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3902 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3903 unsigned int read_idx = msr / BITS_PER_LONG;
3904 unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3906 msr_bitmap[read_idx] = read_intercept;
3907 msr_bitmap[write_idx] = ~0ul;
3911 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu, u8 mode)
3913 if (!cpu_has_vmx_msr_bitmap())
3916 vmx_reset_x2apic_msrs(vcpu, mode);
3919 * TPR reads and writes can be virtualized even if virtual interrupt
3920 * delivery is not in use.
3922 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
3923 !(mode & MSR_BITMAP_MODE_X2APIC));
3925 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3926 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
3927 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3928 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3932 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3934 struct vcpu_vmx *vmx = to_vmx(vcpu);
3935 u8 mode = vmx_msr_bitmap_mode(vcpu);
3936 u8 changed = mode ^ vmx->msr_bitmap_mode;
3941 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3942 vmx_update_msr_bitmap_x2apic(vcpu, mode);
3944 vmx->msr_bitmap_mode = mode;
3947 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
3949 struct vcpu_vmx *vmx = to_vmx(vcpu);
3950 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3953 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
3954 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
3955 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
3956 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
3957 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3958 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3959 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3963 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3965 struct vcpu_vmx *vmx = to_vmx(vcpu);
3970 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3971 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3972 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3975 rvi = vmx_get_rvi();
3977 vapic_page = vmx->nested.virtual_apic_map.hva;
3978 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3980 return ((rvi & 0xf0) > (vppr & 0xf0));
3983 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
3985 struct vcpu_vmx *vmx = to_vmx(vcpu);
3989 * Set intercept permissions for all potentially passed through MSRs
3990 * again. They will automatically get filtered through the MSR filter,
3991 * so we are back in sync after this.
3993 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
3994 u32 msr = vmx_possible_passthrough_msrs[i];
3995 bool read = test_bit(i, vmx->shadow_msr_intercept.read);
3996 bool write = test_bit(i, vmx->shadow_msr_intercept.write);
3998 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_R, read);
3999 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_W, write);
4002 pt_update_intercept_for_msr(vcpu);
4003 vmx_update_msr_bitmap_x2apic(vcpu, vmx_msr_bitmap_mode(vcpu));
4006 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
4010 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
4012 if (vcpu->mode == IN_GUEST_MODE) {
4014 * The vector of interrupt to be delivered to vcpu had
4015 * been set in PIR before this function.
4017 * Following cases will be reached in this block, and
4018 * we always send a notification event in all cases as
4021 * Case 1: vcpu keeps in non-root mode. Sending a
4022 * notification event posts the interrupt to vcpu.
4024 * Case 2: vcpu exits to root mode and is still
4025 * runnable. PIR will be synced to vIRR before the
4026 * next vcpu entry. Sending a notification event in
4027 * this case has no effect, as vcpu is not in root
4030 * Case 3: vcpu exits to root mode and is blocked.
4031 * vcpu_block() has already synced PIR to vIRR and
4032 * never blocks vcpu if vIRR is not cleared. Therefore,
4033 * a blocked vcpu here does not wait for any requested
4034 * interrupts in PIR, and sending a notification event
4035 * which has no effect is safe here.
4038 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
4045 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4048 struct vcpu_vmx *vmx = to_vmx(vcpu);
4050 if (is_guest_mode(vcpu) &&
4051 vector == vmx->nested.posted_intr_nv) {
4053 * If a posted intr is not recognized by hardware,
4054 * we will accomplish it in the next vmentry.
4056 vmx->nested.pi_pending = true;
4057 kvm_make_request(KVM_REQ_EVENT, vcpu);
4058 /* the PIR and ON have been set by L1. */
4059 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
4060 kvm_vcpu_kick(vcpu);
4066 * Send interrupt to vcpu via posted interrupt way.
4067 * 1. If target vcpu is running(non-root mode), send posted interrupt
4068 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4069 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4070 * interrupt from PIR in next vmentry.
4072 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4074 struct vcpu_vmx *vmx = to_vmx(vcpu);
4077 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4081 if (!vcpu->arch.apicv_active)
4084 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4087 /* If a previous notification has sent the IPI, nothing to do. */
4088 if (pi_test_and_set_on(&vmx->pi_desc))
4091 if (vcpu != kvm_get_running_vcpu() &&
4092 !kvm_vcpu_trigger_posted_interrupt(vcpu, false))
4093 kvm_vcpu_kick(vcpu);
4099 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4100 * will not change in the lifetime of the guest.
4101 * Note that host-state that does change is set elsewhere. E.g., host-state
4102 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4104 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4108 unsigned long cr0, cr3, cr4;
4111 WARN_ON(cr0 & X86_CR0_TS);
4112 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4115 * Save the most likely value for this task's CR3 in the VMCS.
4116 * We can't use __get_current_cr3_fast() because we're not atomic.
4119 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4120 vmx->loaded_vmcs->host_state.cr3 = cr3;
4122 /* Save the most likely value for this task's CR4 in the VMCS. */
4123 cr4 = cr4_read_shadow();
4124 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4125 vmx->loaded_vmcs->host_state.cr4 = cr4;
4127 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4128 #ifdef CONFIG_X86_64
4130 * Load null selectors, so we can avoid reloading them in
4131 * vmx_prepare_switch_to_host(), in case userspace uses
4132 * the null selectors too (the expected case).
4134 vmcs_write16(HOST_DS_SELECTOR, 0);
4135 vmcs_write16(HOST_ES_SELECTOR, 0);
4137 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4138 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4140 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4141 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4143 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4145 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4147 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4148 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4149 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4150 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4152 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4153 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4154 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4157 if (cpu_has_load_ia32_efer())
4158 vmcs_write64(HOST_IA32_EFER, host_efer);
4161 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4163 struct kvm_vcpu *vcpu = &vmx->vcpu;
4165 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4166 ~vcpu->arch.cr4_guest_rsvd_bits;
4168 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PGE;
4169 if (is_guest_mode(&vmx->vcpu))
4170 vcpu->arch.cr4_guest_owned_bits &=
4171 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4172 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4175 u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4177 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4179 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4180 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4183 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4185 if (!enable_preemption_timer)
4186 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4188 return pin_based_exec_ctrl;
4191 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4193 struct vcpu_vmx *vmx = to_vmx(vcpu);
4195 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4196 if (cpu_has_secondary_exec_ctrls()) {
4197 if (kvm_vcpu_apicv_active(vcpu))
4198 secondary_exec_controls_setbit(vmx,
4199 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4200 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4202 secondary_exec_controls_clearbit(vmx,
4203 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4204 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4207 if (cpu_has_vmx_msr_bitmap())
4208 vmx_update_msr_bitmap(vcpu);
4211 u32 vmx_exec_control(struct vcpu_vmx *vmx)
4213 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4215 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4216 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4218 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4219 exec_control &= ~CPU_BASED_TPR_SHADOW;
4220 #ifdef CONFIG_X86_64
4221 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4222 CPU_BASED_CR8_LOAD_EXITING;
4226 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4227 CPU_BASED_CR3_LOAD_EXITING |
4228 CPU_BASED_INVLPG_EXITING;
4229 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4230 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4231 CPU_BASED_MONITOR_EXITING);
4232 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4233 exec_control &= ~CPU_BASED_HLT_EXITING;
4234 return exec_control;
4238 * Adjust a single secondary execution control bit to intercept/allow an
4239 * instruction in the guest. This is usually done based on whether or not a
4240 * feature has been exposed to the guest in order to correctly emulate faults.
4243 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4244 u32 control, bool enabled, bool exiting)
4247 * If the control is for an opt-in feature, clear the control if the
4248 * feature is not exposed to the guest, i.e. not enabled. If the
4249 * control is opt-out, i.e. an exiting control, clear the control if
4250 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4251 * disabled for the associated instruction. Note, the caller is
4252 * responsible presetting exec_control to set all supported bits.
4254 if (enabled == exiting)
4255 *exec_control &= ~control;
4258 * Update the nested MSR settings so that a nested VMM can/can't set
4259 * controls for features that are/aren't exposed to the guest.
4263 vmx->nested.msrs.secondary_ctls_high |= control;
4265 vmx->nested.msrs.secondary_ctls_high &= ~control;
4270 * Wrapper macro for the common case of adjusting a secondary execution control
4271 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4272 * verifies that the control is actually supported by KVM and hardware.
4274 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4278 if (cpu_has_vmx_##name()) { \
4279 __enabled = guest_cpuid_has(&(vmx)->vcpu, \
4280 X86_FEATURE_##feat_name); \
4281 vmx_adjust_secondary_exec_control(vmx, exec_control, \
4282 SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4286 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4287 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4288 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4290 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4291 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4293 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
4295 struct kvm_vcpu *vcpu = &vmx->vcpu;
4297 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4299 if (vmx_pt_mode_is_system())
4300 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4301 if (!cpu_need_virtualize_apic_accesses(vcpu))
4302 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4304 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4306 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4307 enable_unrestricted_guest = 0;
4309 if (!enable_unrestricted_guest)
4310 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4311 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4312 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4313 if (!kvm_vcpu_apicv_active(vcpu))
4314 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4315 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4316 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4318 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4319 * in vmx_set_cr4. */
4320 exec_control &= ~SECONDARY_EXEC_DESC;
4322 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4324 We can NOT enable shadow_vmcs here because we don't have yet
4327 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4330 * PML is enabled/disabled when dirty logging of memsmlots changes, but
4331 * it needs to be set here when dirty logging is already active, e.g.
4332 * if this vCPU was created after dirty logging was enabled.
4334 if (!vcpu->kvm->arch.cpu_dirty_logging_count)
4335 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4337 if (cpu_has_vmx_xsaves()) {
4338 /* Exposing XSAVES only when XSAVE is exposed */
4339 bool xsaves_enabled =
4340 boot_cpu_has(X86_FEATURE_XSAVE) &&
4341 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4342 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4344 vcpu->arch.xsaves_enabled = xsaves_enabled;
4346 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4347 SECONDARY_EXEC_XSAVES,
4348 xsaves_enabled, false);
4352 * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
4353 * feature is exposed to the guest. This creates a virtualization hole
4354 * if both are supported in hardware but only one is exposed to the
4355 * guest, but letting the guest execute RDTSCP or RDPID when either one
4356 * is advertised is preferable to emulating the advertised instruction
4357 * in KVM on #UD, and obviously better than incorrectly injecting #UD.
4359 if (cpu_has_vmx_rdtscp()) {
4360 bool rdpid_or_rdtscp_enabled =
4361 guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
4362 guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
4364 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4365 SECONDARY_EXEC_ENABLE_RDTSCP,
4366 rdpid_or_rdtscp_enabled, false);
4368 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4370 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4371 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4373 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4374 ENABLE_USR_WAIT_PAUSE, false);
4376 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4377 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4379 vmx->secondary_exec_control = exec_control;
4382 #define VMX_XSS_EXIT_BITMAP 0
4385 * Noting that the initialization of Guest-state Area of VMCS is in
4388 static void init_vmcs(struct vcpu_vmx *vmx)
4391 nested_vmx_set_vmcs_shadowing_bitmap();
4393 if (cpu_has_vmx_msr_bitmap())
4394 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4396 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4399 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4401 exec_controls_set(vmx, vmx_exec_control(vmx));
4403 if (cpu_has_secondary_exec_ctrls()) {
4404 vmx_compute_secondary_exec_control(vmx);
4405 secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
4408 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4409 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4410 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4411 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4412 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4414 vmcs_write16(GUEST_INTR_STATUS, 0);
4416 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4417 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4420 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4421 vmcs_write32(PLE_GAP, ple_gap);
4422 vmx->ple_window = ple_window;
4423 vmx->ple_window_dirty = true;
4426 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4427 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4428 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4430 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4431 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4432 vmx_set_constant_host_state(vmx);
4433 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4434 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4436 if (cpu_has_vmx_vmfunc())
4437 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4439 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4440 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4441 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4442 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4443 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4445 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4446 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4448 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4450 /* 22.2.1, 20.8.1 */
4451 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4453 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4454 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4456 set_cr4_guest_host_mask(vmx);
4459 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4461 if (cpu_has_vmx_xsaves())
4462 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4465 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4466 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4469 vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4471 if (vmx_pt_mode_is_host_guest()) {
4472 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4473 /* Bit[6~0] are forced to 1, writes are ignored. */
4474 vmx->pt_desc.guest.output_mask = 0x7F;
4475 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4479 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4481 struct vcpu_vmx *vmx = to_vmx(vcpu);
4482 struct msr_data apic_base_msr;
4485 vmx->rmode.vm86_active = 0;
4488 vmx->msr_ia32_umwait_control = 0;
4490 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4491 vmx->hv_deadline_tsc = -1;
4492 kvm_set_cr8(vcpu, 0);
4495 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4496 MSR_IA32_APICBASE_ENABLE;
4497 if (kvm_vcpu_is_reset_bsp(vcpu))
4498 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4499 apic_base_msr.host_initiated = true;
4500 kvm_set_apic_base(vcpu, &apic_base_msr);
4503 vmx_segment_cache_clear(vmx);
4505 seg_setup(VCPU_SREG_CS);
4506 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4507 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4509 seg_setup(VCPU_SREG_DS);
4510 seg_setup(VCPU_SREG_ES);
4511 seg_setup(VCPU_SREG_FS);
4512 seg_setup(VCPU_SREG_GS);
4513 seg_setup(VCPU_SREG_SS);
4515 vmcs_write16(GUEST_TR_SELECTOR, 0);
4516 vmcs_writel(GUEST_TR_BASE, 0);
4517 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4518 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4520 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4521 vmcs_writel(GUEST_LDTR_BASE, 0);
4522 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4523 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4526 vmcs_write32(GUEST_SYSENTER_CS, 0);
4527 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4528 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4529 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4532 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4533 kvm_rip_write(vcpu, 0xfff0);
4535 vmcs_writel(GUEST_GDTR_BASE, 0);
4536 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4538 vmcs_writel(GUEST_IDTR_BASE, 0);
4539 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4541 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4542 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4543 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4544 if (kvm_mpx_supported())
4545 vmcs_write64(GUEST_BNDCFGS, 0);
4549 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4551 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4552 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4553 if (cpu_need_tpr_shadow(vcpu))
4554 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4555 __pa(vcpu->arch.apic->regs));
4556 vmcs_write32(TPR_THRESHOLD, 0);
4559 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4561 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4562 vmx->vcpu.arch.cr0 = cr0;
4563 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4564 vmx_set_cr4(vcpu, 0);
4565 vmx_set_efer(vcpu, 0);
4567 vmx_update_exception_bitmap(vcpu);
4569 vpid_sync_context(vmx->vpid);
4571 vmx_clear_hlt(vcpu);
4574 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4576 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4579 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4582 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4583 vmx_enable_irq_window(vcpu);
4587 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4590 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4592 struct vcpu_vmx *vmx = to_vmx(vcpu);
4594 int irq = vcpu->arch.interrupt.nr;
4596 trace_kvm_inj_virq(irq);
4598 ++vcpu->stat.irq_injections;
4599 if (vmx->rmode.vm86_active) {
4601 if (vcpu->arch.interrupt.soft)
4602 inc_eip = vcpu->arch.event_exit_inst_len;
4603 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4606 intr = irq | INTR_INFO_VALID_MASK;
4607 if (vcpu->arch.interrupt.soft) {
4608 intr |= INTR_TYPE_SOFT_INTR;
4609 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4610 vmx->vcpu.arch.event_exit_inst_len);
4612 intr |= INTR_TYPE_EXT_INTR;
4613 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4615 vmx_clear_hlt(vcpu);
4618 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4620 struct vcpu_vmx *vmx = to_vmx(vcpu);
4624 * Tracking the NMI-blocked state in software is built upon
4625 * finding the next open IRQ window. This, in turn, depends on
4626 * well-behaving guests: They have to keep IRQs disabled at
4627 * least as long as the NMI handler runs. Otherwise we may
4628 * cause NMI nesting, maybe breaking the guest. But as this is
4629 * highly unlikely, we can live with the residual risk.
4631 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4632 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4635 ++vcpu->stat.nmi_injections;
4636 vmx->loaded_vmcs->nmi_known_unmasked = false;
4638 if (vmx->rmode.vm86_active) {
4639 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4643 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4644 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4646 vmx_clear_hlt(vcpu);
4649 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4651 struct vcpu_vmx *vmx = to_vmx(vcpu);
4655 return vmx->loaded_vmcs->soft_vnmi_blocked;
4656 if (vmx->loaded_vmcs->nmi_known_unmasked)
4658 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4659 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4663 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4665 struct vcpu_vmx *vmx = to_vmx(vcpu);
4668 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4669 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4670 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4673 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4675 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4676 GUEST_INTR_STATE_NMI);
4678 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4679 GUEST_INTR_STATE_NMI);
4683 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4685 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4688 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4691 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4692 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4693 GUEST_INTR_STATE_NMI));
4696 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4698 if (to_vmx(vcpu)->nested.nested_run_pending)
4701 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4702 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4705 return !vmx_nmi_blocked(vcpu);
4708 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4710 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4713 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4714 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4715 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4718 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4720 if (to_vmx(vcpu)->nested.nested_run_pending)
4724 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4725 * e.g. if the IRQ arrived asynchronously after checking nested events.
4727 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4730 return !vmx_interrupt_blocked(vcpu);
4733 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4737 if (enable_unrestricted_guest)
4740 mutex_lock(&kvm->slots_lock);
4741 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4743 mutex_unlock(&kvm->slots_lock);
4746 return PTR_ERR(ret);
4748 to_kvm_vmx(kvm)->tss_addr = addr;
4750 return init_rmode_tss(kvm, ret);
4753 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4755 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4759 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4764 * Update instruction length as we may reinject the exception
4765 * from user space while in guest debugging mode.
4767 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4768 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4769 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4773 return !(vcpu->guest_debug &
4774 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4788 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4789 int vec, u32 err_code)
4792 * Instruction with address size override prefix opcode 0x67
4793 * Cause the #SS fault with 0 error code in VM86 mode.
4795 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4796 if (kvm_emulate_instruction(vcpu, 0)) {
4797 if (vcpu->arch.halt_request) {
4798 vcpu->arch.halt_request = 0;
4799 return kvm_vcpu_halt(vcpu);
4807 * Forward all other exceptions that are valid in real mode.
4808 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4809 * the required debugging infrastructure rework.
4811 kvm_queue_exception(vcpu, vec);
4815 static int handle_machine_check(struct kvm_vcpu *vcpu)
4817 /* handled by vmx_vcpu_run() */
4822 * If the host has split lock detection disabled, then #AC is
4823 * unconditionally injected into the guest, which is the pre split lock
4824 * detection behaviour.
4826 * If the host has split lock detection enabled then #AC is
4827 * only injected into the guest when:
4828 * - Guest CPL == 3 (user mode)
4829 * - Guest has #AC detection enabled in CR0
4830 * - Guest EFLAGS has AC bit set
4832 static inline bool guest_inject_ac(struct kvm_vcpu *vcpu)
4834 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4837 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4838 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4841 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4843 struct vcpu_vmx *vmx = to_vmx(vcpu);
4844 struct kvm_run *kvm_run = vcpu->run;
4845 u32 intr_info, ex_no, error_code;
4846 unsigned long cr2, dr6;
4849 vect_info = vmx->idt_vectoring_info;
4850 intr_info = vmx_get_intr_info(vcpu);
4852 if (is_machine_check(intr_info) || is_nmi(intr_info))
4853 return 1; /* handled by handle_exception_nmi_irqoff() */
4855 if (is_invalid_opcode(intr_info))
4856 return handle_ud(vcpu);
4859 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4860 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4862 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4863 WARN_ON_ONCE(!enable_vmware_backdoor);
4866 * VMware backdoor emulation on #GP interception only handles
4867 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4868 * error code on #GP.
4871 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4874 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4878 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4879 * MMIO, it is better to report an internal error.
4880 * See the comments in vmx_handle_exit.
4882 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4883 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4884 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4885 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4886 vcpu->run->internal.ndata = 4;
4887 vcpu->run->internal.data[0] = vect_info;
4888 vcpu->run->internal.data[1] = intr_info;
4889 vcpu->run->internal.data[2] = error_code;
4890 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
4894 if (is_page_fault(intr_info)) {
4895 cr2 = vmx_get_exit_qual(vcpu);
4896 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
4898 * EPT will cause page fault only if we need to
4899 * detect illegal GPAs.
4901 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
4902 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
4905 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4908 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4910 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4911 return handle_rmode_exception(vcpu, ex_no, error_code);
4915 dr6 = vmx_get_exit_qual(vcpu);
4916 if (!(vcpu->guest_debug &
4917 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4918 if (is_icebp(intr_info))
4919 WARN_ON(!skip_emulated_instruction(vcpu));
4921 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
4924 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
4925 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4929 * Update instruction length as we may reinject #BP from
4930 * user space while in guest debugging mode. Reading it for
4931 * #DB as well causes no harm, it is not used in that case.
4933 vmx->vcpu.arch.event_exit_inst_len =
4934 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4935 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4936 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
4937 kvm_run->debug.arch.exception = ex_no;
4940 if (guest_inject_ac(vcpu)) {
4941 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4946 * Handle split lock. Depending on detection mode this will
4947 * either warn and disable split lock detection for this
4948 * task or force SIGBUS on it.
4950 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4954 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4955 kvm_run->ex.exception = ex_no;
4956 kvm_run->ex.error_code = error_code;
4962 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4964 ++vcpu->stat.irq_exits;
4968 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4970 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4971 vcpu->mmio_needed = 0;
4975 static int handle_io(struct kvm_vcpu *vcpu)
4977 unsigned long exit_qualification;
4978 int size, in, string;
4981 exit_qualification = vmx_get_exit_qual(vcpu);
4982 string = (exit_qualification & 16) != 0;
4984 ++vcpu->stat.io_exits;
4987 return kvm_emulate_instruction(vcpu, 0);
4989 port = exit_qualification >> 16;
4990 size = (exit_qualification & 7) + 1;
4991 in = (exit_qualification & 8) != 0;
4993 return kvm_fast_pio(vcpu, size, port, in);
4997 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5000 * Patch in the VMCALL instruction:
5002 hypercall[0] = 0x0f;
5003 hypercall[1] = 0x01;
5004 hypercall[2] = 0xc1;
5007 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5008 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5010 if (is_guest_mode(vcpu)) {
5011 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5012 unsigned long orig_val = val;
5015 * We get here when L2 changed cr0 in a way that did not change
5016 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5017 * but did change L0 shadowed bits. So we first calculate the
5018 * effective cr0 value that L1 would like to write into the
5019 * hardware. It consists of the L2-owned bits from the new
5020 * value combined with the L1-owned bits from L1's guest_cr0.
5022 val = (val & ~vmcs12->cr0_guest_host_mask) |
5023 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5025 if (!nested_guest_cr0_valid(vcpu, val))
5028 if (kvm_set_cr0(vcpu, val))
5030 vmcs_writel(CR0_READ_SHADOW, orig_val);
5033 if (to_vmx(vcpu)->nested.vmxon &&
5034 !nested_host_cr0_valid(vcpu, val))
5037 return kvm_set_cr0(vcpu, val);
5041 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5043 if (is_guest_mode(vcpu)) {
5044 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5045 unsigned long orig_val = val;
5047 /* analogously to handle_set_cr0 */
5048 val = (val & ~vmcs12->cr4_guest_host_mask) |
5049 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5050 if (kvm_set_cr4(vcpu, val))
5052 vmcs_writel(CR4_READ_SHADOW, orig_val);
5055 return kvm_set_cr4(vcpu, val);
5058 static int handle_desc(struct kvm_vcpu *vcpu)
5060 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
5061 return kvm_emulate_instruction(vcpu, 0);
5064 static int handle_cr(struct kvm_vcpu *vcpu)
5066 unsigned long exit_qualification, val;
5072 exit_qualification = vmx_get_exit_qual(vcpu);
5073 cr = exit_qualification & 15;
5074 reg = (exit_qualification >> 8) & 15;
5075 switch ((exit_qualification >> 4) & 3) {
5076 case 0: /* mov to cr */
5077 val = kvm_register_read(vcpu, reg);
5078 trace_kvm_cr_write(cr, val);
5081 err = handle_set_cr0(vcpu, val);
5082 return kvm_complete_insn_gp(vcpu, err);
5084 WARN_ON_ONCE(enable_unrestricted_guest);
5085 err = kvm_set_cr3(vcpu, val);
5086 return kvm_complete_insn_gp(vcpu, err);
5088 err = handle_set_cr4(vcpu, val);
5089 return kvm_complete_insn_gp(vcpu, err);
5091 u8 cr8_prev = kvm_get_cr8(vcpu);
5093 err = kvm_set_cr8(vcpu, cr8);
5094 ret = kvm_complete_insn_gp(vcpu, err);
5095 if (lapic_in_kernel(vcpu))
5097 if (cr8_prev <= cr8)
5100 * TODO: we might be squashing a
5101 * KVM_GUESTDBG_SINGLESTEP-triggered
5102 * KVM_EXIT_DEBUG here.
5104 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5110 WARN_ONCE(1, "Guest should always own CR0.TS");
5111 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5112 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5113 return kvm_skip_emulated_instruction(vcpu);
5114 case 1: /*mov from cr*/
5117 WARN_ON_ONCE(enable_unrestricted_guest);
5118 val = kvm_read_cr3(vcpu);
5119 kvm_register_write(vcpu, reg, val);
5120 trace_kvm_cr_read(cr, val);
5121 return kvm_skip_emulated_instruction(vcpu);
5123 val = kvm_get_cr8(vcpu);
5124 kvm_register_write(vcpu, reg, val);
5125 trace_kvm_cr_read(cr, val);
5126 return kvm_skip_emulated_instruction(vcpu);
5130 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5131 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5132 kvm_lmsw(vcpu, val);
5134 return kvm_skip_emulated_instruction(vcpu);
5138 vcpu->run->exit_reason = 0;
5139 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5140 (int)(exit_qualification >> 4) & 3, cr);
5144 static int handle_dr(struct kvm_vcpu *vcpu)
5146 unsigned long exit_qualification;
5150 exit_qualification = vmx_get_exit_qual(vcpu);
5151 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5153 /* First, if DR does not exist, trigger UD */
5154 if (!kvm_require_dr(vcpu, dr))
5157 if (kvm_x86_ops.get_cpl(vcpu) > 0)
5160 dr7 = vmcs_readl(GUEST_DR7);
5163 * As the vm-exit takes precedence over the debug trap, we
5164 * need to emulate the latter, either for the host or the
5165 * guest debugging itself.
5167 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5168 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5169 vcpu->run->debug.arch.dr7 = dr7;
5170 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5171 vcpu->run->debug.arch.exception = DB_VECTOR;
5172 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5175 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5180 if (vcpu->guest_debug == 0) {
5181 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5184 * No more DR vmexits; force a reload of the debug registers
5185 * and reenter on this instruction. The next vmexit will
5186 * retrieve the full state of the debug registers.
5188 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5192 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5193 if (exit_qualification & TYPE_MOV_FROM_DR) {
5196 kvm_get_dr(vcpu, dr, &val);
5197 kvm_register_write(vcpu, reg, val);
5200 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5204 return kvm_complete_insn_gp(vcpu, err);
5207 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5209 get_debugreg(vcpu->arch.db[0], 0);
5210 get_debugreg(vcpu->arch.db[1], 1);
5211 get_debugreg(vcpu->arch.db[2], 2);
5212 get_debugreg(vcpu->arch.db[3], 3);
5213 get_debugreg(vcpu->arch.dr6, 6);
5214 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5216 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5217 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5220 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5222 vmcs_writel(GUEST_DR7, val);
5225 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5227 kvm_apic_update_ppr(vcpu);
5231 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5233 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5235 kvm_make_request(KVM_REQ_EVENT, vcpu);
5237 ++vcpu->stat.irq_window_exits;
5241 static int handle_invlpg(struct kvm_vcpu *vcpu)
5243 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5245 kvm_mmu_invlpg(vcpu, exit_qualification);
5246 return kvm_skip_emulated_instruction(vcpu);
5249 static int handle_apic_access(struct kvm_vcpu *vcpu)
5251 if (likely(fasteoi)) {
5252 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5253 int access_type, offset;
5255 access_type = exit_qualification & APIC_ACCESS_TYPE;
5256 offset = exit_qualification & APIC_ACCESS_OFFSET;
5258 * Sane guest uses MOV to write EOI, with written value
5259 * not cared. So make a short-circuit here by avoiding
5260 * heavy instruction emulation.
5262 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5263 (offset == APIC_EOI)) {
5264 kvm_lapic_set_eoi(vcpu);
5265 return kvm_skip_emulated_instruction(vcpu);
5268 return kvm_emulate_instruction(vcpu, 0);
5271 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5273 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5274 int vector = exit_qualification & 0xff;
5276 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5277 kvm_apic_set_eoi_accelerated(vcpu, vector);
5281 static int handle_apic_write(struct kvm_vcpu *vcpu)
5283 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5284 u32 offset = exit_qualification & 0xfff;
5286 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5287 kvm_apic_write_nodecode(vcpu, offset);
5291 static int handle_task_switch(struct kvm_vcpu *vcpu)
5293 struct vcpu_vmx *vmx = to_vmx(vcpu);
5294 unsigned long exit_qualification;
5295 bool has_error_code = false;
5298 int reason, type, idt_v, idt_index;
5300 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5301 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5302 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5304 exit_qualification = vmx_get_exit_qual(vcpu);
5306 reason = (u32)exit_qualification >> 30;
5307 if (reason == TASK_SWITCH_GATE && idt_v) {
5309 case INTR_TYPE_NMI_INTR:
5310 vcpu->arch.nmi_injected = false;
5311 vmx_set_nmi_mask(vcpu, true);
5313 case INTR_TYPE_EXT_INTR:
5314 case INTR_TYPE_SOFT_INTR:
5315 kvm_clear_interrupt_queue(vcpu);
5317 case INTR_TYPE_HARD_EXCEPTION:
5318 if (vmx->idt_vectoring_info &
5319 VECTORING_INFO_DELIVER_CODE_MASK) {
5320 has_error_code = true;
5322 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5325 case INTR_TYPE_SOFT_EXCEPTION:
5326 kvm_clear_exception_queue(vcpu);
5332 tss_selector = exit_qualification;
5334 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5335 type != INTR_TYPE_EXT_INTR &&
5336 type != INTR_TYPE_NMI_INTR))
5337 WARN_ON(!skip_emulated_instruction(vcpu));
5340 * TODO: What about debug traps on tss switch?
5341 * Are we supposed to inject them and update dr6?
5343 return kvm_task_switch(vcpu, tss_selector,
5344 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5345 reason, has_error_code, error_code);
5348 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5350 unsigned long exit_qualification;
5354 exit_qualification = vmx_get_exit_qual(vcpu);
5357 * EPT violation happened while executing iret from NMI,
5358 * "blocked by NMI" bit has to be set before next VM entry.
5359 * There are errata that may cause this bit to not be set:
5362 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5364 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5365 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5367 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5368 trace_kvm_page_fault(gpa, exit_qualification);
5370 /* Is it a read fault? */
5371 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5372 ? PFERR_USER_MASK : 0;
5373 /* Is it a write fault? */
5374 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5375 ? PFERR_WRITE_MASK : 0;
5376 /* Is it a fetch fault? */
5377 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5378 ? PFERR_FETCH_MASK : 0;
5379 /* ept page table entry is present? */
5380 error_code |= (exit_qualification &
5381 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5382 EPT_VIOLATION_EXECUTABLE))
5383 ? PFERR_PRESENT_MASK : 0;
5385 error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
5386 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5388 vcpu->arch.exit_qualification = exit_qualification;
5391 * Check that the GPA doesn't exceed physical memory limits, as that is
5392 * a guest page fault. We have to emulate the instruction here, because
5393 * if the illegal address is that of a paging structure, then
5394 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5395 * would also use advanced VM-exit information for EPT violations to
5396 * reconstruct the page fault error code.
5398 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5399 return kvm_emulate_instruction(vcpu, 0);
5401 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5404 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5408 if (!vmx_can_emulate_instruction(vcpu, NULL, 0))
5412 * A nested guest cannot optimize MMIO vmexits, because we have an
5413 * nGPA here instead of the required GPA.
5415 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5416 if (!is_guest_mode(vcpu) &&
5417 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5418 trace_kvm_fast_mmio(gpa);
5419 return kvm_skip_emulated_instruction(vcpu);
5422 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5425 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5427 WARN_ON_ONCE(!enable_vnmi);
5428 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5429 ++vcpu->stat.nmi_window_exits;
5430 kvm_make_request(KVM_REQ_EVENT, vcpu);
5435 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5437 struct vcpu_vmx *vmx = to_vmx(vcpu);
5438 bool intr_window_requested;
5439 unsigned count = 130;
5441 intr_window_requested = exec_controls_get(vmx) &
5442 CPU_BASED_INTR_WINDOW_EXITING;
5444 while (vmx->emulation_required && count-- != 0) {
5445 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5446 return handle_interrupt_window(&vmx->vcpu);
5448 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5451 if (!kvm_emulate_instruction(vcpu, 0))
5454 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5455 vcpu->arch.exception.pending) {
5456 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5457 vcpu->run->internal.suberror =
5458 KVM_INTERNAL_ERROR_EMULATION;
5459 vcpu->run->internal.ndata = 0;
5463 if (vcpu->arch.halt_request) {
5464 vcpu->arch.halt_request = 0;
5465 return kvm_vcpu_halt(vcpu);
5469 * Note, return 1 and not 0, vcpu_run() will invoke
5470 * xfer_to_guest_mode() which will create a proper return
5473 if (__xfer_to_guest_mode_work_pending())
5480 static void grow_ple_window(struct kvm_vcpu *vcpu)
5482 struct vcpu_vmx *vmx = to_vmx(vcpu);
5483 unsigned int old = vmx->ple_window;
5485 vmx->ple_window = __grow_ple_window(old, ple_window,
5489 if (vmx->ple_window != old) {
5490 vmx->ple_window_dirty = true;
5491 trace_kvm_ple_window_update(vcpu->vcpu_id,
5492 vmx->ple_window, old);
5496 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5498 struct vcpu_vmx *vmx = to_vmx(vcpu);
5499 unsigned int old = vmx->ple_window;
5501 vmx->ple_window = __shrink_ple_window(old, ple_window,
5505 if (vmx->ple_window != old) {
5506 vmx->ple_window_dirty = true;
5507 trace_kvm_ple_window_update(vcpu->vcpu_id,
5508 vmx->ple_window, old);
5513 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5514 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5516 static int handle_pause(struct kvm_vcpu *vcpu)
5518 if (!kvm_pause_in_guest(vcpu->kvm))
5519 grow_ple_window(vcpu);
5522 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5523 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5524 * never set PAUSE_EXITING and just set PLE if supported,
5525 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5527 kvm_vcpu_on_spin(vcpu, true);
5528 return kvm_skip_emulated_instruction(vcpu);
5531 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5536 static int handle_invpcid(struct kvm_vcpu *vcpu)
5538 u32 vmx_instruction_info;
5546 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5547 kvm_queue_exception(vcpu, UD_VECTOR);
5551 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5552 type = kvm_register_read(vcpu, (vmx_instruction_info >> 28) & 0xf);
5555 kvm_inject_gp(vcpu, 0);
5559 /* According to the Intel instruction reference, the memory operand
5560 * is read even if it isn't needed (e.g., for type==all)
5562 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5563 vmx_instruction_info, false,
5564 sizeof(operand), &gva))
5567 return kvm_handle_invpcid(vcpu, type, gva);
5570 static int handle_pml_full(struct kvm_vcpu *vcpu)
5572 unsigned long exit_qualification;
5574 trace_kvm_pml_full(vcpu->vcpu_id);
5576 exit_qualification = vmx_get_exit_qual(vcpu);
5579 * PML buffer FULL happened while executing iret from NMI,
5580 * "blocked by NMI" bit has to be set before next VM entry.
5582 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5584 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5585 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5586 GUEST_INTR_STATE_NMI);
5589 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5590 * here.., and there's no userspace involvement needed for PML.
5595 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5597 struct vcpu_vmx *vmx = to_vmx(vcpu);
5599 if (!vmx->req_immediate_exit &&
5600 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5601 kvm_lapic_expired_hv_timer(vcpu);
5602 return EXIT_FASTPATH_REENTER_GUEST;
5605 return EXIT_FASTPATH_NONE;
5608 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5610 handle_fastpath_preemption_timer(vcpu);
5615 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5616 * are overwritten by nested_vmx_setup() when nested=1.
5618 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5620 kvm_queue_exception(vcpu, UD_VECTOR);
5624 #ifndef CONFIG_X86_SGX_KVM
5625 static int handle_encls(struct kvm_vcpu *vcpu)
5628 * SGX virtualization is disabled. There is no software enable bit for
5629 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
5630 * the guest from executing ENCLS (when SGX is supported by hardware).
5632 kvm_queue_exception(vcpu, UD_VECTOR);
5635 #endif /* CONFIG_X86_SGX_KVM */
5637 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
5639 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
5640 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
5645 * The exit handlers return 1 if the exit was handled fully and guest execution
5646 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5647 * to be done to userspace and return 0.
5649 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5650 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5651 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5652 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5653 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5654 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5655 [EXIT_REASON_CR_ACCESS] = handle_cr,
5656 [EXIT_REASON_DR_ACCESS] = handle_dr,
5657 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5658 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5659 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5660 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5661 [EXIT_REASON_HLT] = kvm_emulate_halt,
5662 [EXIT_REASON_INVD] = kvm_emulate_invd,
5663 [EXIT_REASON_INVLPG] = handle_invlpg,
5664 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
5665 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
5666 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5667 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5668 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5669 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5670 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5671 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5672 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5673 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5674 [EXIT_REASON_VMON] = handle_vmx_instruction,
5675 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5676 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5677 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5678 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5679 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
5680 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
5681 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5682 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5683 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5684 [EXIT_REASON_LDTR_TR] = handle_desc,
5685 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5686 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5687 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5688 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
5689 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5690 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
5691 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5692 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5693 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
5694 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
5695 [EXIT_REASON_PML_FULL] = handle_pml_full,
5696 [EXIT_REASON_INVPCID] = handle_invpcid,
5697 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5698 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5699 [EXIT_REASON_ENCLS] = handle_encls,
5700 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
5703 static const int kvm_vmx_max_exit_handlers =
5704 ARRAY_SIZE(kvm_vmx_exit_handlers);
5706 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2,
5707 u32 *intr_info, u32 *error_code)
5709 struct vcpu_vmx *vmx = to_vmx(vcpu);
5711 *info1 = vmx_get_exit_qual(vcpu);
5712 if (!(vmx->exit_reason.failed_vmentry)) {
5713 *info2 = vmx->idt_vectoring_info;
5714 *intr_info = vmx_get_intr_info(vcpu);
5715 if (is_exception_with_error_code(*intr_info))
5716 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5726 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5729 __free_page(vmx->pml_pg);
5734 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5736 struct vcpu_vmx *vmx = to_vmx(vcpu);
5740 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5742 /* Do nothing if PML buffer is empty */
5743 if (pml_idx == (PML_ENTITY_NUM - 1))
5746 /* PML index always points to next available PML buffer entity */
5747 if (pml_idx >= PML_ENTITY_NUM)
5752 pml_buf = page_address(vmx->pml_pg);
5753 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5756 gpa = pml_buf[pml_idx];
5757 WARN_ON(gpa & (PAGE_SIZE - 1));
5758 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5761 /* reset PML index */
5762 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5765 static void vmx_dump_sel(char *name, uint32_t sel)
5767 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5768 name, vmcs_read16(sel),
5769 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5770 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5771 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5774 static void vmx_dump_dtsel(char *name, uint32_t limit)
5776 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5777 name, vmcs_read32(limit),
5778 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5781 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
5784 struct vmx_msr_entry *e;
5786 pr_err("MSR %s:\n", name);
5787 for (i = 0, e = m->val; i < m->nr; ++i, ++e)
5788 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
5791 void dump_vmcs(struct kvm_vcpu *vcpu)
5793 struct vcpu_vmx *vmx = to_vmx(vcpu);
5794 u32 vmentry_ctl, vmexit_ctl;
5795 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5799 if (!dump_invalid_vmcs) {
5800 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5804 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5805 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5806 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5807 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5808 cr4 = vmcs_readl(GUEST_CR4);
5809 secondary_exec_control = 0;
5810 if (cpu_has_secondary_exec_ctrls())
5811 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5813 pr_err("*** Guest State ***\n");
5814 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5815 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5816 vmcs_readl(CR0_GUEST_HOST_MASK));
5817 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5818 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5819 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5820 if (cpu_has_vmx_ept()) {
5821 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5822 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5823 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5824 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5826 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5827 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5828 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5829 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5830 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5831 vmcs_readl(GUEST_SYSENTER_ESP),
5832 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5833 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5834 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5835 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5836 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5837 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5838 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5839 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5840 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5841 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5842 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5843 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
5844 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
5845 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
5846 else if (efer_slot >= 0)
5847 pr_err("EFER= 0x%016llx (autoload)\n",
5848 vmx->msr_autoload.guest.val[efer_slot].value);
5849 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
5850 pr_err("EFER= 0x%016llx (effective)\n",
5851 vcpu->arch.efer | (EFER_LMA | EFER_LME));
5853 pr_err("EFER= 0x%016llx (effective)\n",
5854 vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
5855 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
5856 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
5857 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5858 vmcs_read64(GUEST_IA32_DEBUGCTL),
5859 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5860 if (cpu_has_load_perf_global_ctrl() &&
5861 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5862 pr_err("PerfGlobCtl = 0x%016llx\n",
5863 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5864 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5865 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5866 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5867 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5868 vmcs_read32(GUEST_ACTIVITY_STATE));
5869 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5870 pr_err("InterruptStatus = %04x\n",
5871 vmcs_read16(GUEST_INTR_STATUS));
5872 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
5873 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
5874 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
5875 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
5877 pr_err("*** Host State ***\n");
5878 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5879 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5880 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5881 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5882 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5883 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5884 vmcs_read16(HOST_TR_SELECTOR));
5885 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5886 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5887 vmcs_readl(HOST_TR_BASE));
5888 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5889 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5890 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5891 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5892 vmcs_readl(HOST_CR4));
5893 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5894 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5895 vmcs_read32(HOST_IA32_SYSENTER_CS),
5896 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5897 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
5898 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
5899 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
5900 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
5901 if (cpu_has_load_perf_global_ctrl() &&
5902 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5903 pr_err("PerfGlobCtl = 0x%016llx\n",
5904 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5905 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
5906 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
5908 pr_err("*** Control State ***\n");
5909 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5910 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5911 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5912 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5913 vmcs_read32(EXCEPTION_BITMAP),
5914 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5915 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5916 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5917 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5918 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5919 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5920 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5921 vmcs_read32(VM_EXIT_INTR_INFO),
5922 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5923 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5924 pr_err(" reason=%08x qualification=%016lx\n",
5925 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5926 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5927 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5928 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5929 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5930 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5931 pr_err("TSC Multiplier = 0x%016llx\n",
5932 vmcs_read64(TSC_MULTIPLIER));
5933 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5934 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5935 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5936 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5938 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5939 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5940 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5941 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5943 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5944 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5945 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5946 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5947 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5948 pr_err("PLE Gap=%08x Window=%08x\n",
5949 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5950 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5951 pr_err("Virtual processor ID = 0x%04x\n",
5952 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5956 * The guest has exited. See if we can fix it or if we need userspace
5959 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
5961 struct vcpu_vmx *vmx = to_vmx(vcpu);
5962 union vmx_exit_reason exit_reason = vmx->exit_reason;
5963 u32 vectoring_info = vmx->idt_vectoring_info;
5964 u16 exit_handler_index;
5967 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5968 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5969 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5970 * mode as if vcpus is in root mode, the PML buffer must has been
5971 * flushed already. Note, PML is never enabled in hardware while
5974 if (enable_pml && !is_guest_mode(vcpu))
5975 vmx_flush_pml_buffer(vcpu);
5978 * We should never reach this point with a pending nested VM-Enter, and
5979 * more specifically emulation of L2 due to invalid guest state (see
5980 * below) should never happen as that means we incorrectly allowed a
5981 * nested VM-Enter with an invalid vmcs12.
5983 WARN_ON_ONCE(vmx->nested.nested_run_pending);
5985 /* If guest state is invalid, start emulating */
5986 if (vmx->emulation_required)
5987 return handle_invalid_guest_state(vcpu);
5989 if (is_guest_mode(vcpu)) {
5991 * PML is never enabled when running L2, bail immediately if a
5992 * PML full exit occurs as something is horribly wrong.
5994 if (exit_reason.basic == EXIT_REASON_PML_FULL)
5995 goto unexpected_vmexit;
5998 * The host physical addresses of some pages of guest memory
5999 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6000 * Page). The CPU may write to these pages via their host
6001 * physical address while L2 is running, bypassing any
6002 * address-translation-based dirty tracking (e.g. EPT write
6005 * Mark them dirty on every exit from L2 to prevent them from
6006 * getting out of sync with dirty tracking.
6008 nested_mark_vmcs12_pages_dirty(vcpu);
6010 if (nested_vmx_reflect_vmexit(vcpu))
6014 if (exit_reason.failed_vmentry) {
6016 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6017 vcpu->run->fail_entry.hardware_entry_failure_reason
6019 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6023 if (unlikely(vmx->fail)) {
6025 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6026 vcpu->run->fail_entry.hardware_entry_failure_reason
6027 = vmcs_read32(VM_INSTRUCTION_ERROR);
6028 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6034 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6035 * delivery event since it indicates guest is accessing MMIO.
6036 * The vm-exit can be triggered again after return to guest that
6037 * will cause infinite loop.
6039 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6040 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6041 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6042 exit_reason.basic != EXIT_REASON_PML_FULL &&
6043 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6044 exit_reason.basic != EXIT_REASON_TASK_SWITCH)) {
6047 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6048 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6049 vcpu->run->internal.data[0] = vectoring_info;
6050 vcpu->run->internal.data[1] = exit_reason.full;
6051 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6052 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6053 vcpu->run->internal.data[ndata++] =
6054 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6056 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6057 vcpu->run->internal.ndata = ndata;
6061 if (unlikely(!enable_vnmi &&
6062 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6063 if (!vmx_interrupt_blocked(vcpu)) {
6064 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6065 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6066 vcpu->arch.nmi_pending) {
6068 * This CPU don't support us in finding the end of an
6069 * NMI-blocked window if the guest runs with IRQs
6070 * disabled. So we pull the trigger after 1 s of
6071 * futile waiting, but inform the user about this.
6073 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6074 "state on VCPU %d after 1 s timeout\n",
6075 __func__, vcpu->vcpu_id);
6076 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6080 if (exit_fastpath != EXIT_FASTPATH_NONE)
6083 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6084 goto unexpected_vmexit;
6085 #ifdef CONFIG_RETPOLINE
6086 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6087 return kvm_emulate_wrmsr(vcpu);
6088 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6089 return handle_preemption_timer(vcpu);
6090 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6091 return handle_interrupt_window(vcpu);
6092 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6093 return handle_external_interrupt(vcpu);
6094 else if (exit_reason.basic == EXIT_REASON_HLT)
6095 return kvm_emulate_halt(vcpu);
6096 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6097 return handle_ept_misconfig(vcpu);
6100 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6101 kvm_vmx_max_exit_handlers);
6102 if (!kvm_vmx_exit_handlers[exit_handler_index])
6103 goto unexpected_vmexit;
6105 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6108 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6111 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6112 vcpu->run->internal.suberror =
6113 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6114 vcpu->run->internal.ndata = 2;
6115 vcpu->run->internal.data[0] = exit_reason.full;
6116 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6120 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6122 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6125 * Even when current exit reason is handled by KVM internally, we
6126 * still need to exit to user space when bus lock detected to inform
6127 * that there is a bus lock in guest.
6129 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6131 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6133 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6140 * Software based L1D cache flush which is used when microcode providing
6141 * the cache control MSR is not loaded.
6143 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6144 * flush it is required to read in 64 KiB because the replacement algorithm
6145 * is not exactly LRU. This could be sized at runtime via topology
6146 * information but as all relevant affected CPUs have 32KiB L1D cache size
6147 * there is no point in doing so.
6149 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6151 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6154 * This code is only executed when the the flush mode is 'cond' or
6157 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6161 * Clear the per-vcpu flush bit, it gets set again
6162 * either from vcpu_run() or from one of the unsafe
6165 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6166 vcpu->arch.l1tf_flush_l1d = false;
6169 * Clear the per-cpu flush bit, it gets set again from
6170 * the interrupt handlers.
6172 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6173 kvm_clear_cpu_l1tf_flush_l1d();
6179 vcpu->stat.l1d_flush++;
6181 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6182 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6187 /* First ensure the pages are in the TLB */
6188 "xorl %%eax, %%eax\n"
6189 ".Lpopulate_tlb:\n\t"
6190 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6191 "addl $4096, %%eax\n\t"
6192 "cmpl %%eax, %[size]\n\t"
6193 "jne .Lpopulate_tlb\n\t"
6194 "xorl %%eax, %%eax\n\t"
6196 /* Now fill the cache */
6197 "xorl %%eax, %%eax\n"
6199 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6200 "addl $64, %%eax\n\t"
6201 "cmpl %%eax, %[size]\n\t"
6202 "jne .Lfill_cache\n\t"
6204 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6206 : "eax", "ebx", "ecx", "edx");
6209 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6211 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6214 if (is_guest_mode(vcpu) &&
6215 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6218 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6219 if (is_guest_mode(vcpu))
6220 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6222 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6225 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6227 struct vcpu_vmx *vmx = to_vmx(vcpu);
6228 u32 sec_exec_control;
6230 if (!lapic_in_kernel(vcpu))
6233 if (!flexpriority_enabled &&
6234 !cpu_has_vmx_virtualize_x2apic_mode())
6237 /* Postpone execution until vmcs01 is the current VMCS. */
6238 if (is_guest_mode(vcpu)) {
6239 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6243 sec_exec_control = secondary_exec_controls_get(vmx);
6244 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6245 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6247 switch (kvm_get_apic_mode(vcpu)) {
6248 case LAPIC_MODE_INVALID:
6249 WARN_ONCE(true, "Invalid local APIC state");
6251 case LAPIC_MODE_DISABLED:
6253 case LAPIC_MODE_XAPIC:
6254 if (flexpriority_enabled) {
6256 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6257 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6260 * Flush the TLB, reloading the APIC access page will
6261 * only do so if its physical address has changed, but
6262 * the guest may have inserted a non-APIC mapping into
6263 * the TLB while the APIC access page was disabled.
6265 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6268 case LAPIC_MODE_X2APIC:
6269 if (cpu_has_vmx_virtualize_x2apic_mode())
6271 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6274 secondary_exec_controls_set(vmx, sec_exec_control);
6276 vmx_update_msr_bitmap(vcpu);
6279 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6283 /* Defer reload until vmcs01 is the current VMCS. */
6284 if (is_guest_mode(vcpu)) {
6285 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6289 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6290 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6293 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6294 if (is_error_page(page))
6297 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6298 vmx_flush_tlb_current(vcpu);
6301 * Do not pin apic access page in memory, the MMU notifier
6302 * will call us again if it is migrated or swapped out.
6307 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6315 status = vmcs_read16(GUEST_INTR_STATUS);
6317 if (max_isr != old) {
6319 status |= max_isr << 8;
6320 vmcs_write16(GUEST_INTR_STATUS, status);
6324 static void vmx_set_rvi(int vector)
6332 status = vmcs_read16(GUEST_INTR_STATUS);
6333 old = (u8)status & 0xff;
6334 if ((u8)vector != old) {
6336 status |= (u8)vector;
6337 vmcs_write16(GUEST_INTR_STATUS, status);
6341 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6344 * When running L2, updating RVI is only relevant when
6345 * vmcs12 virtual-interrupt-delivery enabled.
6346 * However, it can be enabled only when L1 also
6347 * intercepts external-interrupts and in that case
6348 * we should not update vmcs02 RVI but instead intercept
6349 * interrupt. Therefore, do nothing when running L2.
6351 if (!is_guest_mode(vcpu))
6352 vmx_set_rvi(max_irr);
6355 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6357 struct vcpu_vmx *vmx = to_vmx(vcpu);
6359 bool max_irr_updated;
6361 WARN_ON(!vcpu->arch.apicv_active);
6362 if (pi_test_on(&vmx->pi_desc)) {
6363 pi_clear_on(&vmx->pi_desc);
6365 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6366 * But on x86 this is just a compiler barrier anyway.
6368 smp_mb__after_atomic();
6370 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6373 * If we are running L2 and L1 has a new pending interrupt
6374 * which can be injected, we should re-evaluate
6375 * what should be done with this new L1 interrupt.
6376 * If L1 intercepts external-interrupts, we should
6377 * exit from L2 to L1. Otherwise, interrupt should be
6378 * delivered directly to L2.
6380 if (is_guest_mode(vcpu) && max_irr_updated) {
6381 if (nested_exit_on_intr(vcpu))
6382 kvm_vcpu_exiting_guest_mode(vcpu);
6384 kvm_make_request(KVM_REQ_EVENT, vcpu);
6387 max_irr = kvm_lapic_find_highest_irr(vcpu);
6389 vmx_hwapic_irr_update(vcpu, max_irr);
6393 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6395 if (!kvm_vcpu_apicv_active(vcpu))
6398 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6399 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6400 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6401 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6404 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6406 struct vcpu_vmx *vmx = to_vmx(vcpu);
6408 pi_clear_on(&vmx->pi_desc);
6409 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6412 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6414 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu,
6415 unsigned long entry)
6417 kvm_before_interrupt(vcpu);
6418 vmx_do_interrupt_nmi_irqoff(entry);
6419 kvm_after_interrupt(vcpu);
6422 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6424 const unsigned long nmi_entry = (unsigned long)asm_exc_nmi_noist;
6425 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6427 /* if exit due to PF check for async PF */
6428 if (is_page_fault(intr_info))
6429 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6430 /* Handle machine checks before interrupts are enabled */
6431 else if (is_machine_check(intr_info))
6432 kvm_machine_check();
6433 /* We need to handle NMIs before interrupts are enabled */
6434 else if (is_nmi(intr_info))
6435 handle_interrupt_nmi_irqoff(&vmx->vcpu, nmi_entry);
6438 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6440 u32 intr_info = vmx_get_intr_info(vcpu);
6441 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6442 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6444 if (WARN_ONCE(!is_external_intr(intr_info),
6445 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6448 handle_interrupt_nmi_irqoff(vcpu, gate_offset(desc));
6451 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6453 struct vcpu_vmx *vmx = to_vmx(vcpu);
6455 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6456 handle_external_interrupt_irqoff(vcpu);
6457 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
6458 handle_exception_nmi_irqoff(vmx);
6462 * The kvm parameter can be NULL (module initialization, or invocation before
6463 * VM creation). Be sure to check the kvm parameter before using it.
6465 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
6468 case MSR_IA32_SMBASE:
6470 * We cannot do SMM unless we can run the guest in big
6473 return enable_unrestricted_guest || emulate_invalid_guest_state;
6474 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6476 case MSR_AMD64_VIRT_SPEC_CTRL:
6477 /* This is AMD only. */
6484 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6489 bool idtv_info_valid;
6491 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6494 if (vmx->loaded_vmcs->nmi_known_unmasked)
6497 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6498 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6499 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6501 * SDM 3: 27.7.1.2 (September 2008)
6502 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6503 * a guest IRET fault.
6504 * SDM 3: 23.2.2 (September 2008)
6505 * Bit 12 is undefined in any of the following cases:
6506 * If the VM exit sets the valid bit in the IDT-vectoring
6507 * information field.
6508 * If the VM exit is due to a double fault.
6510 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6511 vector != DF_VECTOR && !idtv_info_valid)
6512 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6513 GUEST_INTR_STATE_NMI);
6515 vmx->loaded_vmcs->nmi_known_unmasked =
6516 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6517 & GUEST_INTR_STATE_NMI);
6518 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6519 vmx->loaded_vmcs->vnmi_blocked_time +=
6520 ktime_to_ns(ktime_sub(ktime_get(),
6521 vmx->loaded_vmcs->entry_time));
6524 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6525 u32 idt_vectoring_info,
6526 int instr_len_field,
6527 int error_code_field)
6531 bool idtv_info_valid;
6533 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6535 vcpu->arch.nmi_injected = false;
6536 kvm_clear_exception_queue(vcpu);
6537 kvm_clear_interrupt_queue(vcpu);
6539 if (!idtv_info_valid)
6542 kvm_make_request(KVM_REQ_EVENT, vcpu);
6544 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6545 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6548 case INTR_TYPE_NMI_INTR:
6549 vcpu->arch.nmi_injected = true;
6551 * SDM 3: 27.7.1.2 (September 2008)
6552 * Clear bit "block by NMI" before VM entry if a NMI
6555 vmx_set_nmi_mask(vcpu, false);
6557 case INTR_TYPE_SOFT_EXCEPTION:
6558 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6560 case INTR_TYPE_HARD_EXCEPTION:
6561 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6562 u32 err = vmcs_read32(error_code_field);
6563 kvm_requeue_exception_e(vcpu, vector, err);
6565 kvm_requeue_exception(vcpu, vector);
6567 case INTR_TYPE_SOFT_INTR:
6568 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6570 case INTR_TYPE_EXT_INTR:
6571 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6578 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6580 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6581 VM_EXIT_INSTRUCTION_LEN,
6582 IDT_VECTORING_ERROR_CODE);
6585 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6587 __vmx_complete_interrupts(vcpu,
6588 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6589 VM_ENTRY_INSTRUCTION_LEN,
6590 VM_ENTRY_EXCEPTION_ERROR_CODE);
6592 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6595 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6598 struct perf_guest_switch_msr *msrs;
6600 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
6601 msrs = perf_guest_get_msrs(&nr_msrs);
6605 for (i = 0; i < nr_msrs; i++)
6606 if (msrs[i].host == msrs[i].guest)
6607 clear_atomic_switch_msr(vmx, msrs[i].msr);
6609 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6610 msrs[i].host, false);
6613 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6615 struct vcpu_vmx *vmx = to_vmx(vcpu);
6619 if (vmx->req_immediate_exit) {
6620 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6621 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6622 } else if (vmx->hv_deadline_tsc != -1) {
6624 if (vmx->hv_deadline_tsc > tscl)
6625 /* set_hv_timer ensures the delta fits in 32-bits */
6626 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6627 cpu_preemption_timer_multi);
6631 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6632 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6633 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6634 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6635 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6639 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6641 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6642 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6643 vmcs_writel(HOST_RSP, host_rsp);
6647 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6649 switch (to_vmx(vcpu)->exit_reason.basic) {
6650 case EXIT_REASON_MSR_WRITE:
6651 return handle_fastpath_set_msr_irqoff(vcpu);
6652 case EXIT_REASON_PREEMPTION_TIMER:
6653 return handle_fastpath_preemption_timer(vcpu);
6655 return EXIT_FASTPATH_NONE;
6659 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6660 struct vcpu_vmx *vmx)
6662 kvm_guest_enter_irqoff();
6664 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6665 if (static_branch_unlikely(&vmx_l1d_should_flush))
6666 vmx_l1d_flush(vcpu);
6667 else if (static_branch_unlikely(&mds_user_clear))
6668 mds_clear_cpu_buffers();
6670 if (vcpu->arch.cr2 != native_read_cr2())
6671 native_write_cr2(vcpu->arch.cr2);
6673 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6674 vmx->loaded_vmcs->launched);
6676 vcpu->arch.cr2 = native_read_cr2();
6678 kvm_guest_exit_irqoff();
6681 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6683 struct vcpu_vmx *vmx = to_vmx(vcpu);
6684 unsigned long cr3, cr4;
6686 /* Record the guest's net vcpu time for enforced NMI injections. */
6687 if (unlikely(!enable_vnmi &&
6688 vmx->loaded_vmcs->soft_vnmi_blocked))
6689 vmx->loaded_vmcs->entry_time = ktime_get();
6691 /* Don't enter VMX if guest state is invalid, let the exit handler
6692 start emulation until we arrive back to a valid state */
6693 if (vmx->emulation_required)
6694 return EXIT_FASTPATH_NONE;
6696 trace_kvm_entry(vcpu);
6698 if (vmx->ple_window_dirty) {
6699 vmx->ple_window_dirty = false;
6700 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6704 * We did this in prepare_switch_to_guest, because it needs to
6705 * be within srcu_read_lock.
6707 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6709 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6710 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6711 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6712 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6714 cr3 = __get_current_cr3_fast();
6715 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6716 vmcs_writel(HOST_CR3, cr3);
6717 vmx->loaded_vmcs->host_state.cr3 = cr3;
6720 cr4 = cr4_read_shadow();
6721 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6722 vmcs_writel(HOST_CR4, cr4);
6723 vmx->loaded_vmcs->host_state.cr4 = cr4;
6726 /* When single-stepping over STI and MOV SS, we must clear the
6727 * corresponding interruptibility bits in the guest state. Otherwise
6728 * vmentry fails as it then expects bit 14 (BS) in pending debug
6729 * exceptions being set, but that's not correct for the guest debugging
6731 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6732 vmx_set_interrupt_shadow(vcpu, 0);
6734 kvm_load_guest_xsave_state(vcpu);
6736 pt_guest_enter(vmx);
6738 atomic_switch_perf_msrs(vmx);
6739 if (intel_pmu_lbr_is_enabled(vcpu))
6740 vmx_passthrough_lbr_msrs(vcpu);
6742 if (enable_preemption_timer)
6743 vmx_update_hv_timer(vcpu);
6745 kvm_wait_lapic_expire(vcpu);
6748 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6749 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6750 * is no need to worry about the conditional branch over the wrmsr
6751 * being speculatively taken.
6753 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6755 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6756 vmx_vcpu_enter_exit(vcpu, vmx);
6759 * We do not use IBRS in the kernel. If this vCPU has used the
6760 * SPEC_CTRL MSR it may have left it on; save the value and
6761 * turn it off. This is much more efficient than blindly adding
6762 * it to the atomic save/restore list. Especially as the former
6763 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6765 * For non-nested case:
6766 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6770 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6773 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6774 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6776 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6778 /* All fields are clean at this point */
6779 if (static_branch_unlikely(&enable_evmcs)) {
6780 current_evmcs->hv_clean_fields |=
6781 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6783 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
6786 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6787 if (vmx->host_debugctlmsr)
6788 update_debugctlmsr(vmx->host_debugctlmsr);
6790 #ifndef CONFIG_X86_64
6792 * The sysexit path does not restore ds/es, so we must set them to
6793 * a reasonable value ourselves.
6795 * We can't defer this to vmx_prepare_switch_to_host() since that
6796 * function may be executed in interrupt context, which saves and
6797 * restore segments around it, nullifying its effect.
6799 loadsegment(ds, __USER_DS);
6800 loadsegment(es, __USER_DS);
6803 vmx_register_cache_reset(vcpu);
6807 kvm_load_host_xsave_state(vcpu);
6809 vmx->nested.nested_run_pending = 0;
6810 vmx->idt_vectoring_info = 0;
6812 if (unlikely(vmx->fail)) {
6813 vmx->exit_reason.full = 0xdead;
6814 return EXIT_FASTPATH_NONE;
6817 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
6818 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
6819 kvm_machine_check();
6821 if (likely(!vmx->exit_reason.failed_vmentry))
6822 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6824 trace_kvm_exit(vmx->exit_reason.full, vcpu, KVM_ISA_VMX);
6826 if (unlikely(vmx->exit_reason.failed_vmentry))
6827 return EXIT_FASTPATH_NONE;
6829 vmx->loaded_vmcs->launched = 1;
6831 vmx_recover_nmi_blocking(vmx);
6832 vmx_complete_interrupts(vmx);
6834 if (is_guest_mode(vcpu))
6835 return EXIT_FASTPATH_NONE;
6837 return vmx_exit_handlers_fastpath(vcpu);
6840 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6842 struct vcpu_vmx *vmx = to_vmx(vcpu);
6845 vmx_destroy_pml_buffer(vmx);
6846 free_vpid(vmx->vpid);
6847 nested_vmx_free_vcpu(vcpu);
6848 free_loaded_vmcs(vmx->loaded_vmcs);
6851 static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
6853 struct vmx_uret_msr *tsx_ctrl;
6854 struct vcpu_vmx *vmx;
6857 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6862 vmx->vpid = allocate_vpid();
6865 * If PML is turned on, failure on enabling PML just results in failure
6866 * of creating the vcpu, therefore we can simplify PML logic (by
6867 * avoiding dealing with cases, such as enabling PML partially on vcpus
6868 * for the guest), etc.
6871 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6876 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
6877 vmx->guest_uret_msrs[i].data = 0;
6878 vmx->guest_uret_msrs[i].mask = -1ull;
6880 if (boot_cpu_has(X86_FEATURE_RTM)) {
6882 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception.
6883 * Keep the host value unchanged to avoid changing CPUID bits
6884 * under the host kernel's feet.
6886 tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
6888 vmx->guest_uret_msrs[i].mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6891 err = alloc_loaded_vmcs(&vmx->vmcs01);
6895 /* The MSR bitmap starts with all ones */
6896 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6897 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6899 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
6900 #ifdef CONFIG_X86_64
6901 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
6902 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
6903 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6905 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6906 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6907 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6908 if (kvm_cstate_in_guest(vcpu->kvm)) {
6909 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
6910 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6911 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6912 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6914 vmx->msr_bitmap_mode = 0;
6916 vmx->loaded_vmcs = &vmx->vmcs01;
6918 vmx_vcpu_load(vcpu, cpu);
6923 if (cpu_need_virtualize_apic_accesses(vcpu)) {
6924 err = alloc_apic_access_page(vcpu->kvm);
6929 if (enable_ept && !enable_unrestricted_guest) {
6930 err = init_rmode_identity_map(vcpu->kvm);
6936 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
6938 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6940 vcpu_setup_sgx_lepubkeyhash(vcpu);
6942 vmx->nested.posted_intr_nv = -1;
6943 vmx->nested.current_vmptr = -1ull;
6945 vcpu->arch.microcode_version = 0x100000000ULL;
6946 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
6949 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6950 * or POSTED_INTR_WAKEUP_VECTOR.
6952 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6953 vmx->pi_desc.sn = 1;
6955 #if IS_ENABLED(CONFIG_HYPERV)
6956 vmx->hv_root_ept = INVALID_PAGE;
6961 free_loaded_vmcs(vmx->loaded_vmcs);
6963 vmx_destroy_pml_buffer(vmx);
6965 free_vpid(vmx->vpid);
6969 #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"
6970 #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"
6972 static int vmx_vm_init(struct kvm *kvm)
6974 #if IS_ENABLED(CONFIG_HYPERV)
6975 spin_lock_init(&to_kvm_vmx(kvm)->hv_root_ept_lock);
6979 kvm->arch.pause_in_guest = true;
6981 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6982 switch (l1tf_mitigation) {
6983 case L1TF_MITIGATION_OFF:
6984 case L1TF_MITIGATION_FLUSH_NOWARN:
6985 /* 'I explicitly don't care' is set */
6987 case L1TF_MITIGATION_FLUSH:
6988 case L1TF_MITIGATION_FLUSH_NOSMT:
6989 case L1TF_MITIGATION_FULL:
6991 * Warn upon starting the first VM in a potentially
6992 * insecure environment.
6994 if (sched_smt_active())
6995 pr_warn_once(L1TF_MSG_SMT);
6996 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6997 pr_warn_once(L1TF_MSG_L1D);
6999 case L1TF_MITIGATION_FULL_FORCE:
7000 /* Flush is enforced */
7004 kvm_apicv_init(kvm, enable_apicv);
7008 static int __init vmx_check_processor_compat(void)
7010 struct vmcs_config vmcs_conf;
7011 struct vmx_capability vmx_cap;
7013 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7014 !this_cpu_has(X86_FEATURE_VMX)) {
7015 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7019 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7022 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
7023 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7024 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7025 smp_processor_id());
7031 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7036 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7037 * memory aliases with conflicting memory types and sometimes MCEs.
7038 * We have to be careful as to what are honored and when.
7040 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7041 * UC. The effective memory type is UC or WC depending on guest PAT.
7042 * This was historically the source of MCEs and we want to be
7045 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7046 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7047 * EPT memory type is set to WB. The effective memory type is forced
7050 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7051 * EPT memory type is used to emulate guest CD/MTRR.
7055 cache = MTRR_TYPE_UNCACHABLE;
7059 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7060 ipat = VMX_EPT_IPAT_BIT;
7061 cache = MTRR_TYPE_WRBACK;
7065 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7066 ipat = VMX_EPT_IPAT_BIT;
7067 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7068 cache = MTRR_TYPE_WRBACK;
7070 cache = MTRR_TYPE_UNCACHABLE;
7074 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
7077 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7080 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
7083 * These bits in the secondary execution controls field
7084 * are dynamic, the others are mostly based on the hypervisor
7085 * architecture and the guest's CPUID. Do not touch the
7089 SECONDARY_EXEC_SHADOW_VMCS |
7090 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7091 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7092 SECONDARY_EXEC_DESC;
7094 u32 new_ctl = vmx->secondary_exec_control;
7095 u32 cur_ctl = secondary_exec_controls_get(vmx);
7097 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7101 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7102 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7104 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7106 struct vcpu_vmx *vmx = to_vmx(vcpu);
7107 struct kvm_cpuid_entry2 *entry;
7109 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7110 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7112 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7113 if (entry && (entry->_reg & (_cpuid_mask))) \
7114 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7117 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7118 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7119 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7120 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7121 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7122 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7123 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7124 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7125 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7126 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7127 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7128 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7129 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7130 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7131 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7133 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7134 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7135 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7136 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7137 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7138 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7139 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7141 #undef cr4_fixed1_update
7144 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7146 struct vcpu_vmx *vmx = to_vmx(vcpu);
7148 if (kvm_mpx_supported()) {
7149 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7152 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7153 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7155 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7156 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7161 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7163 struct vcpu_vmx *vmx = to_vmx(vcpu);
7164 struct kvm_cpuid_entry2 *best = NULL;
7167 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7168 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7171 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7172 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7173 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7174 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7177 /* Get the number of configurable Address Ranges for filtering */
7178 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7179 PT_CAP_num_address_ranges);
7181 /* Initialize and clear the no dependency bits */
7182 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7183 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7186 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7187 * will inject an #GP
7189 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7190 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7193 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7194 * PSBFreq can be set
7196 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7197 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7198 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7201 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7202 * MTCFreq can be set
7204 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7205 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7206 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7208 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7209 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7210 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7213 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7214 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7215 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7217 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7218 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7219 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7221 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7222 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7223 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7225 /* unmask address range configure area */
7226 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7227 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7230 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7232 struct vcpu_vmx *vmx = to_vmx(vcpu);
7234 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7235 vcpu->arch.xsaves_enabled = false;
7237 if (cpu_has_secondary_exec_ctrls()) {
7238 vmx_compute_secondary_exec_control(vmx);
7239 vmcs_set_secondary_exec_control(vmx);
7242 if (nested_vmx_allowed(vcpu))
7243 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7244 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7245 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7247 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7248 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7249 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7251 if (nested_vmx_allowed(vcpu)) {
7252 nested_vmx_cr_fixed1_bits_update(vcpu);
7253 nested_vmx_entry_exit_ctls_update(vcpu);
7256 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7257 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7258 update_intel_pt_cfg(vcpu);
7260 if (boot_cpu_has(X86_FEATURE_RTM)) {
7261 struct vmx_uret_msr *msr;
7262 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7264 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7265 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7269 set_cr4_guest_host_mask(vmx);
7271 vmx_write_encls_bitmap(vcpu, NULL);
7272 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7273 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7275 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7277 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7278 vmx->msr_ia32_feature_control_valid_bits |=
7279 FEAT_CTL_SGX_LC_ENABLED;
7281 vmx->msr_ia32_feature_control_valid_bits &=
7282 ~FEAT_CTL_SGX_LC_ENABLED;
7284 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7285 vmx_update_exception_bitmap(vcpu);
7288 static __init void vmx_set_cpu_caps(void)
7294 kvm_cpu_cap_set(X86_FEATURE_VMX);
7297 if (kvm_mpx_supported())
7298 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7299 if (!cpu_has_vmx_invpcid())
7300 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7301 if (vmx_pt_mode_is_host_guest())
7302 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7305 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7306 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7307 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7308 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7311 if (vmx_umip_emulated())
7312 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7316 if (!cpu_has_vmx_xsaves())
7317 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7319 /* CPUID 0x80000001 and 0x7 (RDPID) */
7320 if (!cpu_has_vmx_rdtscp()) {
7321 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7322 kvm_cpu_cap_clear(X86_FEATURE_RDPID);
7325 if (cpu_has_vmx_waitpkg())
7326 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7329 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7331 to_vmx(vcpu)->req_immediate_exit = true;
7334 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7335 struct x86_instruction_info *info)
7337 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7338 unsigned short port;
7342 if (info->intercept == x86_intercept_in ||
7343 info->intercept == x86_intercept_ins) {
7344 port = info->src_val;
7345 size = info->dst_bytes;
7347 port = info->dst_val;
7348 size = info->src_bytes;
7352 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7353 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7356 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7358 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7359 intercept = nested_cpu_has(vmcs12,
7360 CPU_BASED_UNCOND_IO_EXITING);
7362 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7364 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7365 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7368 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7369 struct x86_instruction_info *info,
7370 enum x86_intercept_stage stage,
7371 struct x86_exception *exception)
7373 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7375 switch (info->intercept) {
7377 * RDPID causes #UD if disabled through secondary execution controls.
7378 * Because it is marked as EmulateOnUD, we need to intercept it here.
7379 * Note, RDPID is hidden behind ENABLE_RDTSCP.
7381 case x86_intercept_rdpid:
7382 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7383 exception->vector = UD_VECTOR;
7384 exception->error_code_valid = false;
7385 return X86EMUL_PROPAGATE_FAULT;
7389 case x86_intercept_in:
7390 case x86_intercept_ins:
7391 case x86_intercept_out:
7392 case x86_intercept_outs:
7393 return vmx_check_intercept_io(vcpu, info);
7395 case x86_intercept_lgdt:
7396 case x86_intercept_lidt:
7397 case x86_intercept_lldt:
7398 case x86_intercept_ltr:
7399 case x86_intercept_sgdt:
7400 case x86_intercept_sidt:
7401 case x86_intercept_sldt:
7402 case x86_intercept_str:
7403 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7404 return X86EMUL_CONTINUE;
7406 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7409 /* TODO: check more intercepts... */
7414 return X86EMUL_UNHANDLEABLE;
7417 #ifdef CONFIG_X86_64
7418 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7419 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7420 u64 divisor, u64 *result)
7422 u64 low = a << shift, high = a >> (64 - shift);
7424 /* To avoid the overflow on divq */
7425 if (high >= divisor)
7428 /* Low hold the result, high hold rem which is discarded */
7429 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7430 "rm" (divisor), "0" (low), "1" (high));
7436 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7439 struct vcpu_vmx *vmx;
7440 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7441 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7445 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7446 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7447 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7448 ktimer->timer_advance_ns);
7450 if (delta_tsc > lapic_timer_advance_cycles)
7451 delta_tsc -= lapic_timer_advance_cycles;
7455 /* Convert to host delta tsc if tsc scaling is enabled */
7456 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7457 delta_tsc && u64_shl_div_u64(delta_tsc,
7458 kvm_tsc_scaling_ratio_frac_bits,
7459 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7463 * If the delta tsc can't fit in the 32 bit after the multi shift,
7464 * we can't use the preemption timer.
7465 * It's possible that it fits on later vmentries, but checking
7466 * on every vmentry is costly so we just use an hrtimer.
7468 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7471 vmx->hv_deadline_tsc = tscl + delta_tsc;
7472 *expired = !delta_tsc;
7476 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7478 to_vmx(vcpu)->hv_deadline_tsc = -1;
7482 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7484 if (!kvm_pause_in_guest(vcpu->kvm))
7485 shrink_ple_window(vcpu);
7488 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
7490 struct vcpu_vmx *vmx = to_vmx(vcpu);
7492 if (is_guest_mode(vcpu)) {
7493 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
7498 * Note, cpu_dirty_logging_count can be changed concurrent with this
7499 * code, but in that case another update request will be made and so
7500 * the guest will never run with a stale PML value.
7502 if (vcpu->kvm->arch.cpu_dirty_logging_count)
7503 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7505 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7508 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7510 if (pi_pre_block(vcpu))
7513 if (kvm_lapic_hv_timer_in_use(vcpu))
7514 kvm_lapic_switch_to_sw_timer(vcpu);
7519 static void vmx_post_block(struct kvm_vcpu *vcpu)
7521 if (kvm_x86_ops.set_hv_timer)
7522 kvm_lapic_switch_to_hv_timer(vcpu);
7524 pi_post_block(vcpu);
7527 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7529 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7530 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7531 FEAT_CTL_LMCE_ENABLED;
7533 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7534 ~FEAT_CTL_LMCE_ENABLED;
7537 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7539 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7540 if (to_vmx(vcpu)->nested.nested_run_pending)
7542 return !is_smm(vcpu);
7545 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7547 struct vcpu_vmx *vmx = to_vmx(vcpu);
7549 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7550 if (vmx->nested.smm.guest_mode)
7551 nested_vmx_vmexit(vcpu, -1, 0, 0);
7553 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7554 vmx->nested.vmxon = false;
7555 vmx_clear_hlt(vcpu);
7559 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7561 struct vcpu_vmx *vmx = to_vmx(vcpu);
7564 if (vmx->nested.smm.vmxon) {
7565 vmx->nested.vmxon = true;
7566 vmx->nested.smm.vmxon = false;
7569 if (vmx->nested.smm.guest_mode) {
7570 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7574 vmx->nested.smm.guest_mode = false;
7579 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
7581 /* RSM will cause a vmexit anyway. */
7584 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7586 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
7589 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7591 if (is_guest_mode(vcpu)) {
7592 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7594 if (hrtimer_try_to_cancel(timer) == 1)
7595 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7599 static void hardware_unsetup(void)
7602 nested_vmx_hardware_unsetup();
7607 static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7609 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7610 BIT(APICV_INHIBIT_REASON_HYPERV);
7612 return supported & BIT(bit);
7615 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7616 .hardware_unsetup = hardware_unsetup,
7618 .hardware_enable = hardware_enable,
7619 .hardware_disable = hardware_disable,
7620 .cpu_has_accelerated_tpr = report_flexpriority,
7621 .has_emulated_msr = vmx_has_emulated_msr,
7623 .vm_size = sizeof(struct kvm_vmx),
7624 .vm_init = vmx_vm_init,
7626 .vcpu_create = vmx_create_vcpu,
7627 .vcpu_free = vmx_free_vcpu,
7628 .vcpu_reset = vmx_vcpu_reset,
7630 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7631 .vcpu_load = vmx_vcpu_load,
7632 .vcpu_put = vmx_vcpu_put,
7634 .update_exception_bitmap = vmx_update_exception_bitmap,
7635 .get_msr_feature = vmx_get_msr_feature,
7636 .get_msr = vmx_get_msr,
7637 .set_msr = vmx_set_msr,
7638 .get_segment_base = vmx_get_segment_base,
7639 .get_segment = vmx_get_segment,
7640 .set_segment = vmx_set_segment,
7641 .get_cpl = vmx_get_cpl,
7642 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7643 .set_cr0 = vmx_set_cr0,
7644 .is_valid_cr4 = vmx_is_valid_cr4,
7645 .set_cr4 = vmx_set_cr4,
7646 .set_efer = vmx_set_efer,
7647 .get_idt = vmx_get_idt,
7648 .set_idt = vmx_set_idt,
7649 .get_gdt = vmx_get_gdt,
7650 .set_gdt = vmx_set_gdt,
7651 .set_dr7 = vmx_set_dr7,
7652 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7653 .cache_reg = vmx_cache_reg,
7654 .get_rflags = vmx_get_rflags,
7655 .set_rflags = vmx_set_rflags,
7657 .tlb_flush_all = vmx_flush_tlb_all,
7658 .tlb_flush_current = vmx_flush_tlb_current,
7659 .tlb_flush_gva = vmx_flush_tlb_gva,
7660 .tlb_flush_guest = vmx_flush_tlb_guest,
7662 .run = vmx_vcpu_run,
7663 .handle_exit = vmx_handle_exit,
7664 .skip_emulated_instruction = vmx_skip_emulated_instruction,
7665 .update_emulated_instruction = vmx_update_emulated_instruction,
7666 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7667 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7668 .patch_hypercall = vmx_patch_hypercall,
7669 .set_irq = vmx_inject_irq,
7670 .set_nmi = vmx_inject_nmi,
7671 .queue_exception = vmx_queue_exception,
7672 .cancel_injection = vmx_cancel_injection,
7673 .interrupt_allowed = vmx_interrupt_allowed,
7674 .nmi_allowed = vmx_nmi_allowed,
7675 .get_nmi_mask = vmx_get_nmi_mask,
7676 .set_nmi_mask = vmx_set_nmi_mask,
7677 .enable_nmi_window = vmx_enable_nmi_window,
7678 .enable_irq_window = vmx_enable_irq_window,
7679 .update_cr8_intercept = vmx_update_cr8_intercept,
7680 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7681 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7682 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7683 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7684 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7685 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7686 .hwapic_irr_update = vmx_hwapic_irr_update,
7687 .hwapic_isr_update = vmx_hwapic_isr_update,
7688 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7689 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7690 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7691 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
7693 .set_tss_addr = vmx_set_tss_addr,
7694 .set_identity_map_addr = vmx_set_identity_map_addr,
7695 .get_mt_mask = vmx_get_mt_mask,
7697 .get_exit_info = vmx_get_exit_info,
7699 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
7701 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7703 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7705 .load_mmu_pgd = vmx_load_mmu_pgd,
7707 .check_intercept = vmx_check_intercept,
7708 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7710 .request_immediate_exit = vmx_request_immediate_exit,
7712 .sched_in = vmx_sched_in,
7714 .cpu_dirty_log_size = PML_ENTITY_NUM,
7715 .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
7717 .pre_block = vmx_pre_block,
7718 .post_block = vmx_post_block,
7720 .pmu_ops = &intel_pmu_ops,
7721 .nested_ops = &vmx_nested_ops,
7723 .update_pi_irte = pi_update_irte,
7724 .start_assignment = vmx_pi_start_assignment,
7726 #ifdef CONFIG_X86_64
7727 .set_hv_timer = vmx_set_hv_timer,
7728 .cancel_hv_timer = vmx_cancel_hv_timer,
7731 .setup_mce = vmx_setup_mce,
7733 .smi_allowed = vmx_smi_allowed,
7734 .pre_enter_smm = vmx_pre_enter_smm,
7735 .pre_leave_smm = vmx_pre_leave_smm,
7736 .enable_smi_window = vmx_enable_smi_window,
7738 .can_emulate_instruction = vmx_can_emulate_instruction,
7739 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7740 .migrate_timers = vmx_migrate_timers,
7742 .msr_filter_changed = vmx_msr_filter_changed,
7743 .complete_emulated_msr = kvm_complete_insn_gp,
7745 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
7748 static __init void vmx_setup_user_return_msrs(void)
7752 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
7753 * will emulate SYSCALL in legacy mode if the vendor string in guest
7754 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
7755 * support this emulation, MSR_STAR is included in the list for i386,
7756 * but is never loaded into hardware. MSR_CSTAR is also never loaded
7757 * into hardware and is here purely for emulation purposes.
7759 const u32 vmx_uret_msrs_list[] = {
7760 #ifdef CONFIG_X86_64
7761 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
7763 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
7768 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
7770 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
7771 kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
7774 static __init int hardware_setup(void)
7776 unsigned long host_bndcfgs;
7778 int r, ept_lpage_level;
7781 host_idt_base = dt.address;
7783 vmx_setup_user_return_msrs();
7785 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7788 if (boot_cpu_has(X86_FEATURE_NX))
7789 kvm_enable_efer_bits(EFER_NX);
7791 if (boot_cpu_has(X86_FEATURE_MPX)) {
7792 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7793 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7796 if (!cpu_has_vmx_mpx())
7797 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
7798 XFEATURE_MASK_BNDCSR);
7800 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7801 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7804 if (!cpu_has_vmx_ept() ||
7805 !cpu_has_vmx_ept_4levels() ||
7806 !cpu_has_vmx_ept_mt_wb() ||
7807 !cpu_has_vmx_invept_global())
7810 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7811 enable_ept_ad_bits = 0;
7813 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7814 enable_unrestricted_guest = 0;
7816 if (!cpu_has_vmx_flexpriority())
7817 flexpriority_enabled = 0;
7819 if (!cpu_has_virtual_nmis())
7823 * set_apic_access_page_addr() is used to reload apic access
7824 * page upon invalidation. No need to do anything if not
7825 * using the APIC_ACCESS_ADDR VMCS field.
7827 if (!flexpriority_enabled)
7828 vmx_x86_ops.set_apic_access_page_addr = NULL;
7830 if (!cpu_has_vmx_tpr_shadow())
7831 vmx_x86_ops.update_cr8_intercept = NULL;
7833 #if IS_ENABLED(CONFIG_HYPERV)
7834 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7836 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
7837 vmx_x86_ops.tlb_remote_flush_with_range =
7838 hv_remote_flush_tlb_with_range;
7842 if (!cpu_has_vmx_ple()) {
7845 ple_window_grow = 0;
7847 ple_window_shrink = 0;
7850 if (!cpu_has_vmx_apicv()) {
7852 vmx_x86_ops.sync_pir_to_irr = NULL;
7855 if (cpu_has_vmx_tsc_scaling()) {
7856 kvm_has_tsc_control = true;
7857 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7858 kvm_tsc_scaling_ratio_frac_bits = 48;
7861 kvm_has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
7863 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7866 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
7867 cpu_has_vmx_ept_execute_only());
7870 ept_lpage_level = 0;
7871 else if (cpu_has_vmx_ept_1g_page())
7872 ept_lpage_level = PG_LEVEL_1G;
7873 else if (cpu_has_vmx_ept_2m_page())
7874 ept_lpage_level = PG_LEVEL_2M;
7876 ept_lpage_level = PG_LEVEL_4K;
7877 kvm_configure_mmu(enable_ept, vmx_get_max_tdp_level(), ept_lpage_level);
7880 * Only enable PML when hardware supports PML feature, and both EPT
7881 * and EPT A/D bit features are enabled -- PML depends on them to work.
7883 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7887 vmx_x86_ops.cpu_dirty_log_size = 0;
7889 if (!cpu_has_vmx_preemption_timer())
7890 enable_preemption_timer = false;
7892 if (enable_preemption_timer) {
7893 u64 use_timer_freq = 5000ULL * 1000 * 1000;
7896 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7897 cpu_preemption_timer_multi =
7898 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7901 use_timer_freq = (u64)tsc_khz * 1000;
7902 use_timer_freq >>= cpu_preemption_timer_multi;
7905 * KVM "disables" the preemption timer by setting it to its max
7906 * value. Don't use the timer if it might cause spurious exits
7907 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
7909 if (use_timer_freq > 0xffffffffu / 10)
7910 enable_preemption_timer = false;
7913 if (!enable_preemption_timer) {
7914 vmx_x86_ops.set_hv_timer = NULL;
7915 vmx_x86_ops.cancel_hv_timer = NULL;
7916 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
7919 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
7921 kvm_mce_cap_supported |= MCG_LMCE_P;
7923 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7925 if (!enable_ept || !cpu_has_vmx_intel_pt())
7926 pt_mode = PT_MODE_SYSTEM;
7928 setup_default_sgx_lepubkeyhash();
7931 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7932 vmx_capability.ept);
7934 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7941 r = alloc_kvm_area();
7943 nested_vmx_hardware_unsetup();
7947 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
7948 .cpu_has_kvm_support = cpu_has_kvm_support,
7949 .disabled_by_bios = vmx_disabled_by_bios,
7950 .check_processor_compatibility = vmx_check_processor_compat,
7951 .hardware_setup = hardware_setup,
7953 .runtime_ops = &vmx_x86_ops,
7956 static void vmx_cleanup_l1d_flush(void)
7958 if (vmx_l1d_flush_pages) {
7959 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7960 vmx_l1d_flush_pages = NULL;
7962 /* Restore state so sysfs ignores VMX */
7963 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
7966 static void vmx_exit(void)
7968 #ifdef CONFIG_KEXEC_CORE
7969 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
7975 #if IS_ENABLED(CONFIG_HYPERV)
7976 if (static_branch_unlikely(&enable_evmcs)) {
7978 struct hv_vp_assist_page *vp_ap;
7980 * Reset everything to support using non-enlightened VMCS
7981 * access later (e.g. when we reload the module with
7982 * enlightened_vmcs=0)
7984 for_each_online_cpu(cpu) {
7985 vp_ap = hv_get_vp_assist_page(cpu);
7990 vp_ap->nested_control.features.directhypercall = 0;
7991 vp_ap->current_nested_vmcs = 0;
7992 vp_ap->enlighten_vmentry = 0;
7995 static_branch_disable(&enable_evmcs);
7998 vmx_cleanup_l1d_flush();
8000 module_exit(vmx_exit);
8002 static int __init vmx_init(void)
8006 #if IS_ENABLED(CONFIG_HYPERV)
8008 * Enlightened VMCS usage should be recommended and the host needs
8009 * to support eVMCS v1 or above. We can also disable eVMCS support
8010 * with module parameter.
8012 if (enlightened_vmcs &&
8013 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8014 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8015 KVM_EVMCS_VERSION) {
8018 /* Check that we have assist pages on all online CPUs */
8019 for_each_online_cpu(cpu) {
8020 if (!hv_get_vp_assist_page(cpu)) {
8021 enlightened_vmcs = false;
8026 if (enlightened_vmcs) {
8027 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8028 static_branch_enable(&enable_evmcs);
8031 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8032 vmx_x86_ops.enable_direct_tlbflush
8033 = hv_enable_direct_tlbflush;
8036 enlightened_vmcs = false;
8040 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8041 __alignof__(struct vcpu_vmx), THIS_MODULE);
8046 * Must be called after kvm_init() so enable_ept is properly set
8047 * up. Hand the parameter mitigation value in which was stored in
8048 * the pre module init parser. If no parameter was given, it will
8049 * contain 'auto' which will be turned into the default 'cond'
8052 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8058 for_each_possible_cpu(cpu) {
8059 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8064 #ifdef CONFIG_KEXEC_CORE
8065 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8066 crash_vmclear_local_loaded_vmcss);
8068 vmx_check_vmcs12_offsets();
8071 * Shadow paging doesn't have a (further) performance penalty
8072 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8076 allow_smaller_maxphyaddr = true;
8080 module_init(vmx_init);