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;
459 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
460 * will emulate SYSCALL in legacy mode if the vendor string in guest
461 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
462 * support this emulation, IA32_STAR must always be included in
463 * vmx_uret_msrs_list[], even in i386 builds.
465 static const u32 vmx_uret_msrs_list[] = {
467 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
469 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
473 #if IS_ENABLED(CONFIG_HYPERV)
474 static bool __read_mostly enlightened_vmcs = true;
475 module_param(enlightened_vmcs, bool, 0444);
477 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
480 struct kvm_tlb_range *range = data;
482 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
486 static inline int hv_remote_flush_root_ept(hpa_t root_ept,
487 struct kvm_tlb_range *range)
490 return hyperv_flush_guest_mapping_range(root_ept,
491 kvm_fill_hv_flush_list_func, (void *)range);
493 return hyperv_flush_guest_mapping(root_ept);
496 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
497 struct kvm_tlb_range *range)
499 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
500 struct kvm_vcpu *vcpu;
501 int ret = 0, i, nr_unique_valid_roots;
504 spin_lock(&kvm_vmx->hv_root_ept_lock);
506 if (!VALID_PAGE(kvm_vmx->hv_root_ept)) {
507 nr_unique_valid_roots = 0;
510 * Flush all valid roots, and see if all vCPUs have converged
511 * on a common root, in which case future flushes can skip the
512 * loop and flush the common root.
514 kvm_for_each_vcpu(i, vcpu, kvm) {
515 root = to_vmx(vcpu)->hv_root_ept;
516 if (!VALID_PAGE(root) || root == kvm_vmx->hv_root_ept)
520 * Set the tracked root to the first valid root. Keep
521 * this root for the entirety of the loop even if more
522 * roots are encountered as a low effort optimization
523 * to avoid flushing the same (first) root again.
525 if (++nr_unique_valid_roots == 1)
526 kvm_vmx->hv_root_ept = root;
529 ret = hv_remote_flush_root_ept(root, range);
532 * Stop processing roots if a failure occurred and
533 * multiple valid roots have already been detected.
535 if (ret && nr_unique_valid_roots > 1)
540 * The optimized flush of a single root can't be used if there
541 * are multiple valid roots (obviously).
543 if (nr_unique_valid_roots > 1)
544 kvm_vmx->hv_root_ept = INVALID_PAGE;
546 ret = hv_remote_flush_root_ept(kvm_vmx->hv_root_ept, range);
549 spin_unlock(&kvm_vmx->hv_root_ept_lock);
552 static int hv_remote_flush_tlb(struct kvm *kvm)
554 return hv_remote_flush_tlb_with_range(kvm, NULL);
557 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
559 struct hv_enlightened_vmcs *evmcs;
560 struct hv_partition_assist_pg **p_hv_pa_pg =
561 &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
563 * Synthetic VM-Exit is not enabled in current code and so All
564 * evmcs in singe VM shares same assist page.
567 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
572 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
574 evmcs->partition_assist_page =
576 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
577 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
582 #endif /* IS_ENABLED(CONFIG_HYPERV) */
584 static void hv_track_root_ept(struct kvm_vcpu *vcpu, hpa_t root_ept)
586 #if IS_ENABLED(CONFIG_HYPERV)
587 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
589 if (kvm_x86_ops.tlb_remote_flush == hv_remote_flush_tlb) {
590 spin_lock(&kvm_vmx->hv_root_ept_lock);
591 to_vmx(vcpu)->hv_root_ept = root_ept;
592 if (root_ept != kvm_vmx->hv_root_ept)
593 kvm_vmx->hv_root_ept = INVALID_PAGE;
594 spin_unlock(&kvm_vmx->hv_root_ept_lock);
600 * Comment's format: document - errata name - stepping - processor name.
602 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
604 static u32 vmx_preemption_cpu_tfms[] = {
605 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
607 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
608 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
609 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
611 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
613 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
614 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
616 * 320767.pdf - AAP86 - B1 -
617 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
620 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
622 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
624 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
626 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
627 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
628 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
630 /* Xeon E3-1220 V2 */
634 static inline bool cpu_has_broken_vmx_preemption_timer(void)
636 u32 eax = cpuid_eax(0x00000001), i;
638 /* Clear the reserved bits */
639 eax &= ~(0x3U << 14 | 0xfU << 28);
640 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
641 if (eax == vmx_preemption_cpu_tfms[i])
647 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
649 return flexpriority_enabled && lapic_in_kernel(vcpu);
652 static inline bool report_flexpriority(void)
654 return flexpriority_enabled;
657 static int possible_passthrough_msr_slot(u32 msr)
661 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
662 if (vmx_possible_passthrough_msrs[i] == msr)
668 static bool is_valid_passthrough_msr(u32 msr)
673 case 0x800 ... 0x8ff:
674 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
676 case MSR_IA32_RTIT_STATUS:
677 case MSR_IA32_RTIT_OUTPUT_BASE:
678 case MSR_IA32_RTIT_OUTPUT_MASK:
679 case MSR_IA32_RTIT_CR3_MATCH:
680 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
681 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
684 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
685 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
686 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
687 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
688 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
689 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
693 r = possible_passthrough_msr_slot(msr) != -ENOENT;
695 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
700 static inline int __vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
704 for (i = 0; i < vmx->nr_uret_msrs; ++i)
705 if (vmx_uret_msrs_list[vmx->guest_uret_msrs[i].slot] == msr)
710 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
714 i = __vmx_find_uret_msr(vmx, msr);
716 return &vmx->guest_uret_msrs[i];
720 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
721 struct vmx_uret_msr *msr, u64 data)
725 u64 old_msr_data = msr->data;
727 if (msr - vmx->guest_uret_msrs < vmx->nr_active_uret_msrs) {
729 ret = kvm_set_user_return_msr(msr->slot, msr->data, msr->mask);
732 msr->data = old_msr_data;
737 #ifdef CONFIG_KEXEC_CORE
738 static void crash_vmclear_local_loaded_vmcss(void)
740 int cpu = raw_smp_processor_id();
741 struct loaded_vmcs *v;
743 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
744 loaded_vmcss_on_cpu_link)
747 #endif /* CONFIG_KEXEC_CORE */
749 static void __loaded_vmcs_clear(void *arg)
751 struct loaded_vmcs *loaded_vmcs = arg;
752 int cpu = raw_smp_processor_id();
754 if (loaded_vmcs->cpu != cpu)
755 return; /* vcpu migration can race with cpu offline */
756 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
757 per_cpu(current_vmcs, cpu) = NULL;
759 vmcs_clear(loaded_vmcs->vmcs);
760 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
761 vmcs_clear(loaded_vmcs->shadow_vmcs);
763 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
766 * Ensure all writes to loaded_vmcs, including deleting it from its
767 * current percpu list, complete before setting loaded_vmcs->vcpu to
768 * -1, otherwise a different cpu can see vcpu == -1 first and add
769 * loaded_vmcs to its percpu list before it's deleted from this cpu's
770 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
774 loaded_vmcs->cpu = -1;
775 loaded_vmcs->launched = 0;
778 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
780 int cpu = loaded_vmcs->cpu;
783 smp_call_function_single(cpu,
784 __loaded_vmcs_clear, loaded_vmcs, 1);
787 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
791 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
793 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
794 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
795 vmx->segment_cache.bitmask = 0;
797 ret = vmx->segment_cache.bitmask & mask;
798 vmx->segment_cache.bitmask |= mask;
802 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
804 u16 *p = &vmx->segment_cache.seg[seg].selector;
806 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
807 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
811 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
813 ulong *p = &vmx->segment_cache.seg[seg].base;
815 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
816 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
820 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
822 u32 *p = &vmx->segment_cache.seg[seg].limit;
824 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
825 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
829 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
831 u32 *p = &vmx->segment_cache.seg[seg].ar;
833 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
834 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
838 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
842 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
843 (1u << DB_VECTOR) | (1u << AC_VECTOR);
845 * Guest access to VMware backdoor ports could legitimately
846 * trigger #GP because of TSS I/O permission bitmap.
847 * We intercept those #GP and allow access to them anyway
850 if (enable_vmware_backdoor)
851 eb |= (1u << GP_VECTOR);
852 if ((vcpu->guest_debug &
853 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
854 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
855 eb |= 1u << BP_VECTOR;
856 if (to_vmx(vcpu)->rmode.vm86_active)
858 if (!vmx_need_pf_intercept(vcpu))
859 eb &= ~(1u << PF_VECTOR);
861 /* When we are running a nested L2 guest and L1 specified for it a
862 * certain exception bitmap, we must trap the same exceptions and pass
863 * them to L1. When running L2, we will only handle the exceptions
864 * specified above if L1 did not want them.
866 if (is_guest_mode(vcpu))
867 eb |= get_vmcs12(vcpu)->exception_bitmap;
870 * If EPT is enabled, #PF is only trapped if MAXPHYADDR is mismatched
871 * between guest and host. In that case we only care about present
872 * faults. For vmcs02, however, PFEC_MASK and PFEC_MATCH are set in
873 * prepare_vmcs02_rare.
875 bool selective_pf_trap = enable_ept && (eb & (1u << PF_VECTOR));
876 int mask = selective_pf_trap ? PFERR_PRESENT_MASK : 0;
877 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
878 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, mask);
881 vmcs_write32(EXCEPTION_BITMAP, eb);
885 * Check if MSR is intercepted for currently loaded MSR bitmap.
887 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
889 unsigned long *msr_bitmap;
890 int f = sizeof(unsigned long);
892 if (!cpu_has_vmx_msr_bitmap())
895 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
898 return !!test_bit(msr, msr_bitmap + 0x800 / f);
899 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
901 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
907 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
908 unsigned long entry, unsigned long exit)
910 vm_entry_controls_clearbit(vmx, entry);
911 vm_exit_controls_clearbit(vmx, exit);
914 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
918 for (i = 0; i < m->nr; ++i) {
919 if (m->val[i].index == msr)
925 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
928 struct msr_autoload *m = &vmx->msr_autoload;
932 if (cpu_has_load_ia32_efer()) {
933 clear_atomic_switch_msr_special(vmx,
934 VM_ENTRY_LOAD_IA32_EFER,
935 VM_EXIT_LOAD_IA32_EFER);
939 case MSR_CORE_PERF_GLOBAL_CTRL:
940 if (cpu_has_load_perf_global_ctrl()) {
941 clear_atomic_switch_msr_special(vmx,
942 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
943 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
948 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
952 m->guest.val[i] = m->guest.val[m->guest.nr];
953 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
956 i = vmx_find_loadstore_msr_slot(&m->host, msr);
961 m->host.val[i] = m->host.val[m->host.nr];
962 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
965 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
966 unsigned long entry, unsigned long exit,
967 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
968 u64 guest_val, u64 host_val)
970 vmcs_write64(guest_val_vmcs, guest_val);
971 if (host_val_vmcs != HOST_IA32_EFER)
972 vmcs_write64(host_val_vmcs, host_val);
973 vm_entry_controls_setbit(vmx, entry);
974 vm_exit_controls_setbit(vmx, exit);
977 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
978 u64 guest_val, u64 host_val, bool entry_only)
981 struct msr_autoload *m = &vmx->msr_autoload;
985 if (cpu_has_load_ia32_efer()) {
986 add_atomic_switch_msr_special(vmx,
987 VM_ENTRY_LOAD_IA32_EFER,
988 VM_EXIT_LOAD_IA32_EFER,
991 guest_val, host_val);
995 case MSR_CORE_PERF_GLOBAL_CTRL:
996 if (cpu_has_load_perf_global_ctrl()) {
997 add_atomic_switch_msr_special(vmx,
998 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
999 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1000 GUEST_IA32_PERF_GLOBAL_CTRL,
1001 HOST_IA32_PERF_GLOBAL_CTRL,
1002 guest_val, host_val);
1006 case MSR_IA32_PEBS_ENABLE:
1007 /* PEBS needs a quiescent period after being disabled (to write
1008 * a record). Disabling PEBS through VMX MSR swapping doesn't
1009 * provide that period, so a CPU could write host's record into
1012 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
1015 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
1017 j = vmx_find_loadstore_msr_slot(&m->host, msr);
1019 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
1020 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
1021 printk_once(KERN_WARNING "Not enough msr switch entries. "
1022 "Can't add msr %x\n", msr);
1027 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1029 m->guest.val[i].index = msr;
1030 m->guest.val[i].value = guest_val;
1037 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1039 m->host.val[j].index = msr;
1040 m->host.val[j].value = host_val;
1043 static bool update_transition_efer(struct vcpu_vmx *vmx)
1045 u64 guest_efer = vmx->vcpu.arch.efer;
1046 u64 ignore_bits = 0;
1049 /* Shadow paging assumes NX to be available. */
1051 guest_efer |= EFER_NX;
1054 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1056 ignore_bits |= EFER_SCE;
1057 #ifdef CONFIG_X86_64
1058 ignore_bits |= EFER_LMA | EFER_LME;
1059 /* SCE is meaningful only in long mode on Intel */
1060 if (guest_efer & EFER_LMA)
1061 ignore_bits &= ~(u64)EFER_SCE;
1065 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1066 * On CPUs that support "load IA32_EFER", always switch EFER
1067 * atomically, since it's faster than switching it manually.
1069 if (cpu_has_load_ia32_efer() ||
1070 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1071 if (!(guest_efer & EFER_LMA))
1072 guest_efer &= ~EFER_LME;
1073 if (guest_efer != host_efer)
1074 add_atomic_switch_msr(vmx, MSR_EFER,
1075 guest_efer, host_efer, false);
1077 clear_atomic_switch_msr(vmx, MSR_EFER);
1081 i = __vmx_find_uret_msr(vmx, MSR_EFER);
1085 clear_atomic_switch_msr(vmx, MSR_EFER);
1087 guest_efer &= ~ignore_bits;
1088 guest_efer |= host_efer & ignore_bits;
1090 vmx->guest_uret_msrs[i].data = guest_efer;
1091 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1096 #ifdef CONFIG_X86_32
1098 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1099 * VMCS rather than the segment table. KVM uses this helper to figure
1100 * out the current bases to poke them into the VMCS before entry.
1102 static unsigned long segment_base(u16 selector)
1104 struct desc_struct *table;
1107 if (!(selector & ~SEGMENT_RPL_MASK))
1110 table = get_current_gdt_ro();
1112 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1113 u16 ldt_selector = kvm_read_ldt();
1115 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1118 table = (struct desc_struct *)segment_base(ldt_selector);
1120 v = get_desc_base(&table[selector >> 3]);
1125 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1127 return vmx_pt_mode_is_host_guest() &&
1128 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1131 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1133 /* The base must be 128-byte aligned and a legal physical address. */
1134 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1137 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1141 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1142 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1143 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1144 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1145 for (i = 0; i < addr_range; i++) {
1146 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1147 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1151 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1155 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1156 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1157 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1158 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1159 for (i = 0; i < addr_range; i++) {
1160 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1161 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1165 static void pt_guest_enter(struct vcpu_vmx *vmx)
1167 if (vmx_pt_mode_is_system())
1171 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1172 * Save host state before VM entry.
1174 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1175 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1176 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1177 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1178 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1182 static void pt_guest_exit(struct vcpu_vmx *vmx)
1184 if (vmx_pt_mode_is_system())
1187 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1188 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1189 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1192 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1193 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1196 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1197 unsigned long fs_base, unsigned long gs_base)
1199 if (unlikely(fs_sel != host->fs_sel)) {
1201 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1203 vmcs_write16(HOST_FS_SELECTOR, 0);
1204 host->fs_sel = fs_sel;
1206 if (unlikely(gs_sel != host->gs_sel)) {
1208 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1210 vmcs_write16(HOST_GS_SELECTOR, 0);
1211 host->gs_sel = gs_sel;
1213 if (unlikely(fs_base != host->fs_base)) {
1214 vmcs_writel(HOST_FS_BASE, fs_base);
1215 host->fs_base = fs_base;
1217 if (unlikely(gs_base != host->gs_base)) {
1218 vmcs_writel(HOST_GS_BASE, gs_base);
1219 host->gs_base = gs_base;
1223 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1225 struct vcpu_vmx *vmx = to_vmx(vcpu);
1226 struct vmcs_host_state *host_state;
1227 #ifdef CONFIG_X86_64
1228 int cpu = raw_smp_processor_id();
1230 unsigned long fs_base, gs_base;
1234 vmx->req_immediate_exit = false;
1237 * Note that guest MSRs to be saved/restored can also be changed
1238 * when guest state is loaded. This happens when guest transitions
1239 * to/from long-mode by setting MSR_EFER.LMA.
1241 if (!vmx->guest_uret_msrs_loaded) {
1242 vmx->guest_uret_msrs_loaded = true;
1243 for (i = 0; i < vmx->nr_active_uret_msrs; ++i)
1244 kvm_set_user_return_msr(vmx->guest_uret_msrs[i].slot,
1245 vmx->guest_uret_msrs[i].data,
1246 vmx->guest_uret_msrs[i].mask);
1250 if (vmx->nested.need_vmcs12_to_shadow_sync)
1251 nested_sync_vmcs12_to_shadow(vcpu);
1253 if (vmx->guest_state_loaded)
1256 host_state = &vmx->loaded_vmcs->host_state;
1259 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1260 * allow segment selectors with cpl > 0 or ti == 1.
1262 host_state->ldt_sel = kvm_read_ldt();
1264 #ifdef CONFIG_X86_64
1265 savesegment(ds, host_state->ds_sel);
1266 savesegment(es, host_state->es_sel);
1268 gs_base = cpu_kernelmode_gs_base(cpu);
1269 if (likely(is_64bit_mm(current->mm))) {
1270 current_save_fsgs();
1271 fs_sel = current->thread.fsindex;
1272 gs_sel = current->thread.gsindex;
1273 fs_base = current->thread.fsbase;
1274 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1276 savesegment(fs, fs_sel);
1277 savesegment(gs, gs_sel);
1278 fs_base = read_msr(MSR_FS_BASE);
1279 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1282 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1284 savesegment(fs, fs_sel);
1285 savesegment(gs, gs_sel);
1286 fs_base = segment_base(fs_sel);
1287 gs_base = segment_base(gs_sel);
1290 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1291 vmx->guest_state_loaded = true;
1294 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1296 struct vmcs_host_state *host_state;
1298 if (!vmx->guest_state_loaded)
1301 host_state = &vmx->loaded_vmcs->host_state;
1303 ++vmx->vcpu.stat.host_state_reload;
1305 #ifdef CONFIG_X86_64
1306 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1308 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1309 kvm_load_ldt(host_state->ldt_sel);
1310 #ifdef CONFIG_X86_64
1311 load_gs_index(host_state->gs_sel);
1313 loadsegment(gs, host_state->gs_sel);
1316 if (host_state->fs_sel & 7)
1317 loadsegment(fs, host_state->fs_sel);
1318 #ifdef CONFIG_X86_64
1319 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1320 loadsegment(ds, host_state->ds_sel);
1321 loadsegment(es, host_state->es_sel);
1324 invalidate_tss_limit();
1325 #ifdef CONFIG_X86_64
1326 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1328 load_fixmap_gdt(raw_smp_processor_id());
1329 vmx->guest_state_loaded = false;
1330 vmx->guest_uret_msrs_loaded = false;
1333 #ifdef CONFIG_X86_64
1334 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1337 if (vmx->guest_state_loaded)
1338 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1340 return vmx->msr_guest_kernel_gs_base;
1343 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1346 if (vmx->guest_state_loaded)
1347 wrmsrl(MSR_KERNEL_GS_BASE, data);
1349 vmx->msr_guest_kernel_gs_base = data;
1353 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1354 struct loaded_vmcs *buddy)
1356 struct vcpu_vmx *vmx = to_vmx(vcpu);
1357 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1360 if (!already_loaded) {
1361 loaded_vmcs_clear(vmx->loaded_vmcs);
1362 local_irq_disable();
1365 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1366 * this cpu's percpu list, otherwise it may not yet be deleted
1367 * from its previous cpu's percpu list. Pairs with the
1368 * smb_wmb() in __loaded_vmcs_clear().
1372 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1373 &per_cpu(loaded_vmcss_on_cpu, cpu));
1377 prev = per_cpu(current_vmcs, cpu);
1378 if (prev != vmx->loaded_vmcs->vmcs) {
1379 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1380 vmcs_load(vmx->loaded_vmcs->vmcs);
1383 * No indirect branch prediction barrier needed when switching
1384 * the active VMCS within a guest, e.g. on nested VM-Enter.
1385 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1387 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1388 indirect_branch_prediction_barrier();
1391 if (!already_loaded) {
1392 void *gdt = get_current_gdt_ro();
1393 unsigned long sysenter_esp;
1396 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1397 * TLB entries from its previous association with the vCPU.
1399 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1402 * Linux uses per-cpu TSS and GDT, so set these when switching
1403 * processors. See 22.2.4.
1405 vmcs_writel(HOST_TR_BASE,
1406 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1407 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1409 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1410 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1412 vmx->loaded_vmcs->cpu = cpu;
1415 /* Setup TSC multiplier */
1416 if (kvm_has_tsc_control &&
1417 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1418 decache_tsc_multiplier(vmx);
1422 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1423 * vcpu mutex is already taken.
1425 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1427 struct vcpu_vmx *vmx = to_vmx(vcpu);
1429 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1431 vmx_vcpu_pi_load(vcpu, cpu);
1433 vmx->host_debugctlmsr = get_debugctlmsr();
1436 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1438 vmx_vcpu_pi_put(vcpu);
1440 vmx_prepare_switch_to_host(to_vmx(vcpu));
1443 static bool emulation_required(struct kvm_vcpu *vcpu)
1445 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1448 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1450 struct vcpu_vmx *vmx = to_vmx(vcpu);
1451 unsigned long rflags, save_rflags;
1453 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1454 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1455 rflags = vmcs_readl(GUEST_RFLAGS);
1456 if (vmx->rmode.vm86_active) {
1457 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1458 save_rflags = vmx->rmode.save_rflags;
1459 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1461 vmx->rflags = rflags;
1466 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1468 struct vcpu_vmx *vmx = to_vmx(vcpu);
1469 unsigned long old_rflags;
1471 if (is_unrestricted_guest(vcpu)) {
1472 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1473 vmx->rflags = rflags;
1474 vmcs_writel(GUEST_RFLAGS, rflags);
1478 old_rflags = vmx_get_rflags(vcpu);
1479 vmx->rflags = rflags;
1480 if (vmx->rmode.vm86_active) {
1481 vmx->rmode.save_rflags = rflags;
1482 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1484 vmcs_writel(GUEST_RFLAGS, rflags);
1486 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1487 vmx->emulation_required = emulation_required(vcpu);
1490 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1492 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1495 if (interruptibility & GUEST_INTR_STATE_STI)
1496 ret |= KVM_X86_SHADOW_INT_STI;
1497 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1498 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1503 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1505 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1506 u32 interruptibility = interruptibility_old;
1508 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1510 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1511 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1512 else if (mask & KVM_X86_SHADOW_INT_STI)
1513 interruptibility |= GUEST_INTR_STATE_STI;
1515 if ((interruptibility != interruptibility_old))
1516 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1519 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1521 struct vcpu_vmx *vmx = to_vmx(vcpu);
1522 unsigned long value;
1525 * Any MSR write that attempts to change bits marked reserved will
1528 if (data & vmx->pt_desc.ctl_bitmask)
1532 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1533 * result in a #GP unless the same write also clears TraceEn.
1535 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1536 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1540 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1541 * and FabricEn would cause #GP, if
1542 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1544 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1545 !(data & RTIT_CTL_FABRIC_EN) &&
1546 !intel_pt_validate_cap(vmx->pt_desc.caps,
1547 PT_CAP_single_range_output))
1551 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1552 * utilize encodings marked reserved will cause a #GP fault.
1554 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1555 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1556 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1557 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1559 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1560 PT_CAP_cycle_thresholds);
1561 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1562 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1563 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1565 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1566 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1567 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1568 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1572 * If ADDRx_CFG is reserved or the encodings is >2 will
1573 * cause a #GP fault.
1575 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1576 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1578 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1579 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1581 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1582 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1584 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1585 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1591 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
1594 * Emulation of instructions in SGX enclaves is impossible as RIP does
1595 * not point tthe failing instruction, and even if it did, the code
1596 * stream is inaccessible. Inject #UD instead of exiting to userspace
1597 * so that guest userspace can't DoS the guest simply by triggering
1598 * emulation (enclaves are CPL3 only).
1600 if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1601 kvm_queue_exception(vcpu, UD_VECTOR);
1607 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1609 union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1610 unsigned long rip, orig_rip;
1614 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1615 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1616 * set when EPT misconfig occurs. In practice, real hardware updates
1617 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1618 * (namely Hyper-V) don't set it due to it being undefined behavior,
1619 * i.e. we end up advancing IP with some random value.
1621 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1622 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1623 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1626 * Emulating an enclave's instructions isn't supported as KVM
1627 * cannot access the enclave's memory or its true RIP, e.g. the
1628 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1629 * the RIP that actually triggered the VM-Exit. But, because
1630 * most instructions that cause VM-Exit will #UD in an enclave,
1631 * most instruction-based VM-Exits simply do not occur.
1633 * There are a few exceptions, notably the debug instructions
1634 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1635 * and generate #DB/#BP as expected, which KVM might intercept.
1636 * But again, the CPU does the dirty work and saves an instr
1637 * length of zero so VMMs don't shoot themselves in the foot.
1638 * WARN if KVM tries to skip a non-zero length instruction on
1639 * a VM-Exit from an enclave.
1644 WARN(exit_reason.enclave_mode,
1645 "KVM: skipping instruction after SGX enclave VM-Exit");
1647 orig_rip = kvm_rip_read(vcpu);
1648 rip = orig_rip + instr_len;
1649 #ifdef CONFIG_X86_64
1651 * We need to mask out the high 32 bits of RIP if not in 64-bit
1652 * mode, but just finding out that we are in 64-bit mode is
1653 * quite expensive. Only do it if there was a carry.
1655 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1658 kvm_rip_write(vcpu, rip);
1660 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1665 /* skipping an emulated instruction also counts */
1666 vmx_set_interrupt_shadow(vcpu, 0);
1672 * Recognizes a pending MTF VM-exit and records the nested state for later
1675 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1677 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1678 struct vcpu_vmx *vmx = to_vmx(vcpu);
1680 if (!is_guest_mode(vcpu))
1684 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1685 * T-bit traps. As instruction emulation is completed (i.e. at the
1686 * instruction boundary), any #DB exception pending delivery must be a
1687 * debug-trap. Record the pending MTF state to be delivered in
1688 * vmx_check_nested_events().
1690 if (nested_cpu_has_mtf(vmcs12) &&
1691 (!vcpu->arch.exception.pending ||
1692 vcpu->arch.exception.nr == DB_VECTOR))
1693 vmx->nested.mtf_pending = true;
1695 vmx->nested.mtf_pending = false;
1698 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1700 vmx_update_emulated_instruction(vcpu);
1701 return skip_emulated_instruction(vcpu);
1704 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1707 * Ensure that we clear the HLT state in the VMCS. We don't need to
1708 * explicitly skip the instruction because if the HLT state is set,
1709 * then the instruction is already executing and RIP has already been
1712 if (kvm_hlt_in_guest(vcpu->kvm) &&
1713 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1714 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1717 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1719 struct vcpu_vmx *vmx = to_vmx(vcpu);
1720 unsigned nr = vcpu->arch.exception.nr;
1721 bool has_error_code = vcpu->arch.exception.has_error_code;
1722 u32 error_code = vcpu->arch.exception.error_code;
1723 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1725 kvm_deliver_exception_payload(vcpu);
1727 if (has_error_code) {
1728 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1729 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1732 if (vmx->rmode.vm86_active) {
1734 if (kvm_exception_is_soft(nr))
1735 inc_eip = vcpu->arch.event_exit_inst_len;
1736 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1740 WARN_ON_ONCE(vmx->emulation_required);
1742 if (kvm_exception_is_soft(nr)) {
1743 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1744 vmx->vcpu.arch.event_exit_inst_len);
1745 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1747 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1749 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1751 vmx_clear_hlt(vcpu);
1754 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr)
1756 struct vmx_uret_msr tmp;
1759 from = __vmx_find_uret_msr(vmx, msr);
1762 to = vmx->nr_active_uret_msrs++;
1764 tmp = vmx->guest_uret_msrs[to];
1765 vmx->guest_uret_msrs[to] = vmx->guest_uret_msrs[from];
1766 vmx->guest_uret_msrs[from] = tmp;
1770 * Set up the vmcs to automatically save and restore system
1771 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1772 * mode, as fiddling with msrs is very expensive.
1774 static void setup_msrs(struct vcpu_vmx *vmx)
1776 vmx->guest_uret_msrs_loaded = false;
1777 vmx->nr_active_uret_msrs = 0;
1778 #ifdef CONFIG_X86_64
1780 * The SYSCALL MSRs are only needed on long mode guests, and only
1781 * when EFER.SCE is set.
1783 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1784 vmx_setup_uret_msr(vmx, MSR_STAR);
1785 vmx_setup_uret_msr(vmx, MSR_LSTAR);
1786 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK);
1789 if (update_transition_efer(vmx))
1790 vmx_setup_uret_msr(vmx, MSR_EFER);
1792 if (guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1793 vmx_setup_uret_msr(vmx, MSR_TSC_AUX);
1795 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL);
1797 if (cpu_has_vmx_msr_bitmap())
1798 vmx_update_msr_bitmap(&vmx->vcpu);
1801 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1803 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1804 u64 g_tsc_offset = 0;
1807 * We're here if L1 chose not to trap WRMSR to TSC. According
1808 * to the spec, this should set L1's TSC; The offset that L1
1809 * set for L2 remains unchanged, and still needs to be added
1810 * to the newly set TSC to get L2's TSC.
1812 if (is_guest_mode(vcpu) &&
1813 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
1814 g_tsc_offset = vmcs12->tsc_offset;
1816 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1817 vcpu->arch.tsc_offset - g_tsc_offset,
1819 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1820 return offset + g_tsc_offset;
1824 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1825 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1826 * all guests if the "nested" module option is off, and can also be disabled
1827 * for a single guest by disabling its VMX cpuid bit.
1829 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1831 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1834 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1837 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1839 return !(val & ~valid_bits);
1842 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1844 switch (msr->index) {
1845 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1848 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1849 case MSR_IA32_PERF_CAPABILITIES:
1850 msr->data = vmx_get_perf_capabilities();
1853 return KVM_MSR_RET_INVALID;
1858 * Reads an msr value (of 'msr_index') into 'pdata'.
1859 * Returns 0 on success, non-0 otherwise.
1860 * Assumes vcpu_load() was already called.
1862 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1864 struct vcpu_vmx *vmx = to_vmx(vcpu);
1865 struct vmx_uret_msr *msr;
1868 switch (msr_info->index) {
1869 #ifdef CONFIG_X86_64
1871 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1874 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1876 case MSR_KERNEL_GS_BASE:
1877 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1881 return kvm_get_msr_common(vcpu, msr_info);
1882 case MSR_IA32_TSX_CTRL:
1883 if (!msr_info->host_initiated &&
1884 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1887 case MSR_IA32_UMWAIT_CONTROL:
1888 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1891 msr_info->data = vmx->msr_ia32_umwait_control;
1893 case MSR_IA32_SPEC_CTRL:
1894 if (!msr_info->host_initiated &&
1895 !guest_has_spec_ctrl_msr(vcpu))
1898 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1900 case MSR_IA32_SYSENTER_CS:
1901 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1903 case MSR_IA32_SYSENTER_EIP:
1904 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1906 case MSR_IA32_SYSENTER_ESP:
1907 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1909 case MSR_IA32_BNDCFGS:
1910 if (!kvm_mpx_supported() ||
1911 (!msr_info->host_initiated &&
1912 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1914 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1916 case MSR_IA32_MCG_EXT_CTL:
1917 if (!msr_info->host_initiated &&
1918 !(vmx->msr_ia32_feature_control &
1919 FEAT_CTL_LMCE_ENABLED))
1921 msr_info->data = vcpu->arch.mcg_ext_ctl;
1923 case MSR_IA32_FEAT_CTL:
1924 msr_info->data = vmx->msr_ia32_feature_control;
1926 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
1927 if (!msr_info->host_initiated &&
1928 !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
1930 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
1931 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
1933 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1934 if (!nested_vmx_allowed(vcpu))
1936 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1940 * Enlightened VMCS v1 doesn't have certain fields, but buggy
1941 * Hyper-V versions are still trying to use corresponding
1942 * features when they are exposed. Filter out the essential
1945 if (!msr_info->host_initiated &&
1946 vmx->nested.enlightened_vmcs_enabled)
1947 nested_evmcs_filter_control_msr(msr_info->index,
1950 case MSR_IA32_RTIT_CTL:
1951 if (!vmx_pt_mode_is_host_guest())
1953 msr_info->data = vmx->pt_desc.guest.ctl;
1955 case MSR_IA32_RTIT_STATUS:
1956 if (!vmx_pt_mode_is_host_guest())
1958 msr_info->data = vmx->pt_desc.guest.status;
1960 case MSR_IA32_RTIT_CR3_MATCH:
1961 if (!vmx_pt_mode_is_host_guest() ||
1962 !intel_pt_validate_cap(vmx->pt_desc.caps,
1963 PT_CAP_cr3_filtering))
1965 msr_info->data = vmx->pt_desc.guest.cr3_match;
1967 case MSR_IA32_RTIT_OUTPUT_BASE:
1968 if (!vmx_pt_mode_is_host_guest() ||
1969 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1970 PT_CAP_topa_output) &&
1971 !intel_pt_validate_cap(vmx->pt_desc.caps,
1972 PT_CAP_single_range_output)))
1974 msr_info->data = vmx->pt_desc.guest.output_base;
1976 case MSR_IA32_RTIT_OUTPUT_MASK:
1977 if (!vmx_pt_mode_is_host_guest() ||
1978 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1979 PT_CAP_topa_output) &&
1980 !intel_pt_validate_cap(vmx->pt_desc.caps,
1981 PT_CAP_single_range_output)))
1983 msr_info->data = vmx->pt_desc.guest.output_mask;
1985 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1986 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1987 if (!vmx_pt_mode_is_host_guest() ||
1988 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1989 PT_CAP_num_address_ranges)))
1992 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1994 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1997 if (!msr_info->host_initiated &&
1998 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2001 case MSR_IA32_DEBUGCTLMSR:
2002 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
2006 msr = vmx_find_uret_msr(vmx, msr_info->index);
2008 msr_info->data = msr->data;
2011 return kvm_get_msr_common(vcpu, msr_info);
2017 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
2020 #ifdef CONFIG_X86_64
2021 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
2024 return (unsigned long)data;
2027 static u64 vcpu_supported_debugctl(struct kvm_vcpu *vcpu)
2029 u64 debugctl = vmx_supported_debugctl();
2031 if (!intel_pmu_lbr_is_enabled(vcpu))
2032 debugctl &= ~DEBUGCTLMSR_LBR_MASK;
2038 * Writes msr value into the appropriate "register".
2039 * Returns 0 on success, non-0 otherwise.
2040 * Assumes vcpu_load() was already called.
2042 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2044 struct vcpu_vmx *vmx = to_vmx(vcpu);
2045 struct vmx_uret_msr *msr;
2047 u32 msr_index = msr_info->index;
2048 u64 data = msr_info->data;
2051 switch (msr_index) {
2053 ret = kvm_set_msr_common(vcpu, msr_info);
2055 #ifdef CONFIG_X86_64
2057 vmx_segment_cache_clear(vmx);
2058 vmcs_writel(GUEST_FS_BASE, data);
2061 vmx_segment_cache_clear(vmx);
2062 vmcs_writel(GUEST_GS_BASE, data);
2064 case MSR_KERNEL_GS_BASE:
2065 vmx_write_guest_kernel_gs_base(vmx, data);
2068 case MSR_IA32_SYSENTER_CS:
2069 if (is_guest_mode(vcpu))
2070 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2071 vmcs_write32(GUEST_SYSENTER_CS, data);
2073 case MSR_IA32_SYSENTER_EIP:
2074 if (is_guest_mode(vcpu)) {
2075 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2076 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2078 vmcs_writel(GUEST_SYSENTER_EIP, data);
2080 case MSR_IA32_SYSENTER_ESP:
2081 if (is_guest_mode(vcpu)) {
2082 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2083 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2085 vmcs_writel(GUEST_SYSENTER_ESP, data);
2087 case MSR_IA32_DEBUGCTLMSR: {
2088 u64 invalid = data & ~vcpu_supported_debugctl(vcpu);
2089 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2090 if (report_ignored_msrs)
2091 vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
2093 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2094 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2100 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2101 VM_EXIT_SAVE_DEBUG_CONTROLS)
2102 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2104 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2105 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2106 (data & DEBUGCTLMSR_LBR))
2107 intel_pmu_create_guest_lbr_event(vcpu);
2110 case MSR_IA32_BNDCFGS:
2111 if (!kvm_mpx_supported() ||
2112 (!msr_info->host_initiated &&
2113 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2115 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2116 (data & MSR_IA32_BNDCFGS_RSVD))
2118 vmcs_write64(GUEST_BNDCFGS, data);
2120 case MSR_IA32_UMWAIT_CONTROL:
2121 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2124 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2125 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2128 vmx->msr_ia32_umwait_control = data;
2130 case MSR_IA32_SPEC_CTRL:
2131 if (!msr_info->host_initiated &&
2132 !guest_has_spec_ctrl_msr(vcpu))
2135 if (kvm_spec_ctrl_test_value(data))
2138 vmx->spec_ctrl = data;
2144 * When it's written (to non-zero) for the first time, pass
2148 * The handling of the MSR bitmap for L2 guests is done in
2149 * nested_vmx_prepare_msr_bitmap. We should not touch the
2150 * vmcs02.msr_bitmap here since it gets completely overwritten
2151 * in the merging. We update the vmcs01 here for L1 as well
2152 * since it will end up touching the MSR anyway now.
2154 vmx_disable_intercept_for_msr(vcpu,
2158 case MSR_IA32_TSX_CTRL:
2159 if (!msr_info->host_initiated &&
2160 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2162 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2165 case MSR_IA32_PRED_CMD:
2166 if (!msr_info->host_initiated &&
2167 !guest_has_pred_cmd_msr(vcpu))
2170 if (data & ~PRED_CMD_IBPB)
2172 if (!boot_cpu_has(X86_FEATURE_IBPB))
2177 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2181 * When it's written (to non-zero) for the first time, pass
2185 * The handling of the MSR bitmap for L2 guests is done in
2186 * nested_vmx_prepare_msr_bitmap. We should not touch the
2187 * vmcs02.msr_bitmap here since it gets completely overwritten
2190 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
2192 case MSR_IA32_CR_PAT:
2193 if (!kvm_pat_valid(data))
2196 if (is_guest_mode(vcpu) &&
2197 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2198 get_vmcs12(vcpu)->guest_ia32_pat = data;
2200 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2201 vmcs_write64(GUEST_IA32_PAT, data);
2202 vcpu->arch.pat = data;
2205 ret = kvm_set_msr_common(vcpu, msr_info);
2207 case MSR_IA32_TSC_ADJUST:
2208 ret = kvm_set_msr_common(vcpu, msr_info);
2210 case MSR_IA32_MCG_EXT_CTL:
2211 if ((!msr_info->host_initiated &&
2212 !(to_vmx(vcpu)->msr_ia32_feature_control &
2213 FEAT_CTL_LMCE_ENABLED)) ||
2214 (data & ~MCG_EXT_CTL_LMCE_EN))
2216 vcpu->arch.mcg_ext_ctl = data;
2218 case MSR_IA32_FEAT_CTL:
2219 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2220 (to_vmx(vcpu)->msr_ia32_feature_control &
2221 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2223 vmx->msr_ia32_feature_control = data;
2224 if (msr_info->host_initiated && data == 0)
2225 vmx_leave_nested(vcpu);
2227 /* SGX may be enabled/disabled by guest's firmware */
2228 vmx_write_encls_bitmap(vcpu, NULL);
2230 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2232 * On real hardware, the LE hash MSRs are writable before
2233 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2234 * at which point SGX related bits in IA32_FEATURE_CONTROL
2237 * KVM does not emulate SGX activation for simplicity, so
2238 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2239 * is unlocked. This is technically not architectural
2240 * behavior, but it's close enough.
2242 if (!msr_info->host_initiated &&
2243 (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2244 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2245 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2247 vmx->msr_ia32_sgxlepubkeyhash
2248 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2250 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2251 if (!msr_info->host_initiated)
2252 return 1; /* they are read-only */
2253 if (!nested_vmx_allowed(vcpu))
2255 return vmx_set_vmx_msr(vcpu, msr_index, data);
2256 case MSR_IA32_RTIT_CTL:
2257 if (!vmx_pt_mode_is_host_guest() ||
2258 vmx_rtit_ctl_check(vcpu, data) ||
2261 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2262 vmx->pt_desc.guest.ctl = data;
2263 pt_update_intercept_for_msr(vcpu);
2265 case MSR_IA32_RTIT_STATUS:
2266 if (!pt_can_write_msr(vmx))
2268 if (data & MSR_IA32_RTIT_STATUS_MASK)
2270 vmx->pt_desc.guest.status = data;
2272 case MSR_IA32_RTIT_CR3_MATCH:
2273 if (!pt_can_write_msr(vmx))
2275 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2276 PT_CAP_cr3_filtering))
2278 vmx->pt_desc.guest.cr3_match = data;
2280 case MSR_IA32_RTIT_OUTPUT_BASE:
2281 if (!pt_can_write_msr(vmx))
2283 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2284 PT_CAP_topa_output) &&
2285 !intel_pt_validate_cap(vmx->pt_desc.caps,
2286 PT_CAP_single_range_output))
2288 if (!pt_output_base_valid(vcpu, data))
2290 vmx->pt_desc.guest.output_base = data;
2292 case MSR_IA32_RTIT_OUTPUT_MASK:
2293 if (!pt_can_write_msr(vmx))
2295 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2296 PT_CAP_topa_output) &&
2297 !intel_pt_validate_cap(vmx->pt_desc.caps,
2298 PT_CAP_single_range_output))
2300 vmx->pt_desc.guest.output_mask = data;
2302 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2303 if (!pt_can_write_msr(vmx))
2305 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2306 if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2307 PT_CAP_num_address_ranges))
2309 if (is_noncanonical_address(data, vcpu))
2312 vmx->pt_desc.guest.addr_b[index / 2] = data;
2314 vmx->pt_desc.guest.addr_a[index / 2] = data;
2317 if (!msr_info->host_initiated &&
2318 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2320 /* Check reserved bit, higher 32 bits should be zero */
2321 if ((data >> 32) != 0)
2324 case MSR_IA32_PERF_CAPABILITIES:
2325 if (data && !vcpu_to_pmu(vcpu)->version)
2327 if (data & PMU_CAP_LBR_FMT) {
2328 if ((data & PMU_CAP_LBR_FMT) !=
2329 (vmx_get_perf_capabilities() & PMU_CAP_LBR_FMT))
2331 if (!intel_pmu_lbr_is_compatible(vcpu))
2334 ret = kvm_set_msr_common(vcpu, msr_info);
2339 msr = vmx_find_uret_msr(vmx, msr_index);
2341 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2343 ret = kvm_set_msr_common(vcpu, msr_info);
2349 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2351 unsigned long guest_owned_bits;
2353 kvm_register_mark_available(vcpu, reg);
2357 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2360 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2362 case VCPU_EXREG_PDPTR:
2364 ept_save_pdptrs(vcpu);
2366 case VCPU_EXREG_CR0:
2367 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2369 vcpu->arch.cr0 &= ~guest_owned_bits;
2370 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2372 case VCPU_EXREG_CR3:
2373 if (is_unrestricted_guest(vcpu) ||
2374 (enable_ept && is_paging(vcpu)))
2375 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2377 case VCPU_EXREG_CR4:
2378 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2380 vcpu->arch.cr4 &= ~guest_owned_bits;
2381 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2389 static __init int cpu_has_kvm_support(void)
2391 return cpu_has_vmx();
2394 static __init int vmx_disabled_by_bios(void)
2396 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2397 !boot_cpu_has(X86_FEATURE_VMX);
2400 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2404 cr4_set_bits(X86_CR4_VMXE);
2406 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2407 _ASM_EXTABLE(1b, %l[fault])
2408 : : [vmxon_pointer] "m"(vmxon_pointer)
2413 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2414 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2415 cr4_clear_bits(X86_CR4_VMXE);
2420 static int hardware_enable(void)
2422 int cpu = raw_smp_processor_id();
2423 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2426 if (cr4_read_shadow() & X86_CR4_VMXE)
2430 * This can happen if we hot-added a CPU but failed to allocate
2431 * VP assist page for it.
2433 if (static_branch_unlikely(&enable_evmcs) &&
2434 !hv_get_vp_assist_page(cpu))
2437 intel_pt_handle_vmx(1);
2439 r = kvm_cpu_vmxon(phys_addr);
2441 intel_pt_handle_vmx(0);
2451 static void vmclear_local_loaded_vmcss(void)
2453 int cpu = raw_smp_processor_id();
2454 struct loaded_vmcs *v, *n;
2456 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2457 loaded_vmcss_on_cpu_link)
2458 __loaded_vmcs_clear(v);
2461 static void hardware_disable(void)
2463 vmclear_local_loaded_vmcss();
2466 kvm_spurious_fault();
2468 intel_pt_handle_vmx(0);
2472 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2473 * directly instead of going through cpu_has(), to ensure KVM is trapping
2474 * ENCLS whenever it's supported in hardware. It does not matter whether
2475 * the host OS supports or has enabled SGX.
2477 static bool cpu_has_sgx(void)
2479 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2482 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2483 u32 msr, u32 *result)
2485 u32 vmx_msr_low, vmx_msr_high;
2486 u32 ctl = ctl_min | ctl_opt;
2488 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2490 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2491 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2493 /* Ensure minimum (required) set of control bits are supported. */
2501 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2502 struct vmx_capability *vmx_cap)
2504 u32 vmx_msr_low, vmx_msr_high;
2505 u32 min, opt, min2, opt2;
2506 u32 _pin_based_exec_control = 0;
2507 u32 _cpu_based_exec_control = 0;
2508 u32 _cpu_based_2nd_exec_control = 0;
2509 u32 _vmexit_control = 0;
2510 u32 _vmentry_control = 0;
2512 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2513 min = CPU_BASED_HLT_EXITING |
2514 #ifdef CONFIG_X86_64
2515 CPU_BASED_CR8_LOAD_EXITING |
2516 CPU_BASED_CR8_STORE_EXITING |
2518 CPU_BASED_CR3_LOAD_EXITING |
2519 CPU_BASED_CR3_STORE_EXITING |
2520 CPU_BASED_UNCOND_IO_EXITING |
2521 CPU_BASED_MOV_DR_EXITING |
2522 CPU_BASED_USE_TSC_OFFSETTING |
2523 CPU_BASED_MWAIT_EXITING |
2524 CPU_BASED_MONITOR_EXITING |
2525 CPU_BASED_INVLPG_EXITING |
2526 CPU_BASED_RDPMC_EXITING;
2528 opt = CPU_BASED_TPR_SHADOW |
2529 CPU_BASED_USE_MSR_BITMAPS |
2530 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2531 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2532 &_cpu_based_exec_control) < 0)
2534 #ifdef CONFIG_X86_64
2535 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2536 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2537 ~CPU_BASED_CR8_STORE_EXITING;
2539 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2541 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2542 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2543 SECONDARY_EXEC_WBINVD_EXITING |
2544 SECONDARY_EXEC_ENABLE_VPID |
2545 SECONDARY_EXEC_ENABLE_EPT |
2546 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2547 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2548 SECONDARY_EXEC_DESC |
2549 SECONDARY_EXEC_ENABLE_RDTSCP |
2550 SECONDARY_EXEC_ENABLE_INVPCID |
2551 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2552 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2553 SECONDARY_EXEC_SHADOW_VMCS |
2554 SECONDARY_EXEC_XSAVES |
2555 SECONDARY_EXEC_RDSEED_EXITING |
2556 SECONDARY_EXEC_RDRAND_EXITING |
2557 SECONDARY_EXEC_ENABLE_PML |
2558 SECONDARY_EXEC_TSC_SCALING |
2559 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2560 SECONDARY_EXEC_PT_USE_GPA |
2561 SECONDARY_EXEC_PT_CONCEAL_VMX |
2562 SECONDARY_EXEC_ENABLE_VMFUNC |
2563 SECONDARY_EXEC_BUS_LOCK_DETECTION;
2565 opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2566 if (adjust_vmx_controls(min2, opt2,
2567 MSR_IA32_VMX_PROCBASED_CTLS2,
2568 &_cpu_based_2nd_exec_control) < 0)
2571 #ifndef CONFIG_X86_64
2572 if (!(_cpu_based_2nd_exec_control &
2573 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2574 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2577 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2578 _cpu_based_2nd_exec_control &= ~(
2579 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2580 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2581 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2583 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2584 &vmx_cap->ept, &vmx_cap->vpid);
2586 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2587 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2589 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2590 CPU_BASED_CR3_STORE_EXITING |
2591 CPU_BASED_INVLPG_EXITING);
2592 } else if (vmx_cap->ept) {
2594 pr_warn_once("EPT CAP should not exist if not support "
2595 "1-setting enable EPT VM-execution control\n");
2597 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2600 pr_warn_once("VPID CAP should not exist if not support "
2601 "1-setting enable VPID VM-execution control\n");
2604 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2605 #ifdef CONFIG_X86_64
2606 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2608 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2609 VM_EXIT_LOAD_IA32_PAT |
2610 VM_EXIT_LOAD_IA32_EFER |
2611 VM_EXIT_CLEAR_BNDCFGS |
2612 VM_EXIT_PT_CONCEAL_PIP |
2613 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2614 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2615 &_vmexit_control) < 0)
2618 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2619 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2620 PIN_BASED_VMX_PREEMPTION_TIMER;
2621 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2622 &_pin_based_exec_control) < 0)
2625 if (cpu_has_broken_vmx_preemption_timer())
2626 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2627 if (!(_cpu_based_2nd_exec_control &
2628 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2629 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2631 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2632 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2633 VM_ENTRY_LOAD_IA32_PAT |
2634 VM_ENTRY_LOAD_IA32_EFER |
2635 VM_ENTRY_LOAD_BNDCFGS |
2636 VM_ENTRY_PT_CONCEAL_PIP |
2637 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2638 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2639 &_vmentry_control) < 0)
2643 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2644 * can't be used due to an errata where VM Exit may incorrectly clear
2645 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2646 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2648 if (boot_cpu_data.x86 == 0x6) {
2649 switch (boot_cpu_data.x86_model) {
2650 case 26: /* AAK155 */
2651 case 30: /* AAP115 */
2652 case 37: /* AAT100 */
2653 case 44: /* BC86,AAY89,BD102 */
2655 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2656 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2657 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2658 "does not work properly. Using workaround\n");
2666 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2668 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2669 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2672 #ifdef CONFIG_X86_64
2673 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2674 if (vmx_msr_high & (1u<<16))
2678 /* Require Write-Back (WB) memory type for VMCS accesses. */
2679 if (((vmx_msr_high >> 18) & 15) != 6)
2682 vmcs_conf->size = vmx_msr_high & 0x1fff;
2683 vmcs_conf->order = get_order(vmcs_conf->size);
2684 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2686 vmcs_conf->revision_id = vmx_msr_low;
2688 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2689 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2690 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2691 vmcs_conf->vmexit_ctrl = _vmexit_control;
2692 vmcs_conf->vmentry_ctrl = _vmentry_control;
2694 #if IS_ENABLED(CONFIG_HYPERV)
2695 if (enlightened_vmcs)
2696 evmcs_sanitize_exec_ctrls(vmcs_conf);
2702 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2704 int node = cpu_to_node(cpu);
2708 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2711 vmcs = page_address(pages);
2712 memset(vmcs, 0, vmcs_config.size);
2714 /* KVM supports Enlightened VMCS v1 only */
2715 if (static_branch_unlikely(&enable_evmcs))
2716 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2718 vmcs->hdr.revision_id = vmcs_config.revision_id;
2721 vmcs->hdr.shadow_vmcs = 1;
2725 void free_vmcs(struct vmcs *vmcs)
2727 free_pages((unsigned long)vmcs, vmcs_config.order);
2731 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2733 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2735 if (!loaded_vmcs->vmcs)
2737 loaded_vmcs_clear(loaded_vmcs);
2738 free_vmcs(loaded_vmcs->vmcs);
2739 loaded_vmcs->vmcs = NULL;
2740 if (loaded_vmcs->msr_bitmap)
2741 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2742 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2745 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2747 loaded_vmcs->vmcs = alloc_vmcs(false);
2748 if (!loaded_vmcs->vmcs)
2751 vmcs_clear(loaded_vmcs->vmcs);
2753 loaded_vmcs->shadow_vmcs = NULL;
2754 loaded_vmcs->hv_timer_soft_disabled = false;
2755 loaded_vmcs->cpu = -1;
2756 loaded_vmcs->launched = 0;
2758 if (cpu_has_vmx_msr_bitmap()) {
2759 loaded_vmcs->msr_bitmap = (unsigned long *)
2760 __get_free_page(GFP_KERNEL_ACCOUNT);
2761 if (!loaded_vmcs->msr_bitmap)
2763 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2765 if (IS_ENABLED(CONFIG_HYPERV) &&
2766 static_branch_unlikely(&enable_evmcs) &&
2767 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2768 struct hv_enlightened_vmcs *evmcs =
2769 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2771 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2775 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2776 memset(&loaded_vmcs->controls_shadow, 0,
2777 sizeof(struct vmcs_controls_shadow));
2782 free_loaded_vmcs(loaded_vmcs);
2786 static void free_kvm_area(void)
2790 for_each_possible_cpu(cpu) {
2791 free_vmcs(per_cpu(vmxarea, cpu));
2792 per_cpu(vmxarea, cpu) = NULL;
2796 static __init int alloc_kvm_area(void)
2800 for_each_possible_cpu(cpu) {
2803 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2810 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2811 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2812 * revision_id reported by MSR_IA32_VMX_BASIC.
2814 * However, even though not explicitly documented by
2815 * TLFS, VMXArea passed as VMXON argument should
2816 * still be marked with revision_id reported by
2819 if (static_branch_unlikely(&enable_evmcs))
2820 vmcs->hdr.revision_id = vmcs_config.revision_id;
2822 per_cpu(vmxarea, cpu) = vmcs;
2827 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2828 struct kvm_segment *save)
2830 if (!emulate_invalid_guest_state) {
2832 * CS and SS RPL should be equal during guest entry according
2833 * to VMX spec, but in reality it is not always so. Since vcpu
2834 * is in the middle of the transition from real mode to
2835 * protected mode it is safe to assume that RPL 0 is a good
2838 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2839 save->selector &= ~SEGMENT_RPL_MASK;
2840 save->dpl = save->selector & SEGMENT_RPL_MASK;
2843 vmx_set_segment(vcpu, save, seg);
2846 static void enter_pmode(struct kvm_vcpu *vcpu)
2848 unsigned long flags;
2849 struct vcpu_vmx *vmx = to_vmx(vcpu);
2852 * Update real mode segment cache. It may be not up-to-date if segment
2853 * register was written while vcpu was in a guest mode.
2855 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2856 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2857 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2858 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2859 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2860 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2862 vmx->rmode.vm86_active = 0;
2864 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2866 flags = vmcs_readl(GUEST_RFLAGS);
2867 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2868 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2869 vmcs_writel(GUEST_RFLAGS, flags);
2871 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2872 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2874 vmx_update_exception_bitmap(vcpu);
2876 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2877 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2878 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2879 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2880 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2881 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2884 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2886 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2887 struct kvm_segment var = *save;
2890 if (seg == VCPU_SREG_CS)
2893 if (!emulate_invalid_guest_state) {
2894 var.selector = var.base >> 4;
2895 var.base = var.base & 0xffff0;
2905 if (save->base & 0xf)
2906 printk_once(KERN_WARNING "kvm: segment base is not "
2907 "paragraph aligned when entering "
2908 "protected mode (seg=%d)", seg);
2911 vmcs_write16(sf->selector, var.selector);
2912 vmcs_writel(sf->base, var.base);
2913 vmcs_write32(sf->limit, var.limit);
2914 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2917 static void enter_rmode(struct kvm_vcpu *vcpu)
2919 unsigned long flags;
2920 struct vcpu_vmx *vmx = to_vmx(vcpu);
2921 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2923 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2924 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2925 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2926 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2927 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2928 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2929 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2931 vmx->rmode.vm86_active = 1;
2934 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2935 * vcpu. Warn the user that an update is overdue.
2937 if (!kvm_vmx->tss_addr)
2938 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2939 "called before entering vcpu\n");
2941 vmx_segment_cache_clear(vmx);
2943 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2944 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2945 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2947 flags = vmcs_readl(GUEST_RFLAGS);
2948 vmx->rmode.save_rflags = flags;
2950 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2952 vmcs_writel(GUEST_RFLAGS, flags);
2953 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2954 vmx_update_exception_bitmap(vcpu);
2956 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2957 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2958 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2959 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2960 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2961 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2963 kvm_mmu_reset_context(vcpu);
2966 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2968 struct vcpu_vmx *vmx = to_vmx(vcpu);
2969 struct vmx_uret_msr *msr = vmx_find_uret_msr(vmx, MSR_EFER);
2971 /* Nothing to do if hardware doesn't support EFER. */
2975 vcpu->arch.efer = efer;
2976 if (efer & EFER_LMA) {
2977 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2980 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2982 msr->data = efer & ~EFER_LME;
2988 #ifdef CONFIG_X86_64
2990 static void enter_lmode(struct kvm_vcpu *vcpu)
2994 vmx_segment_cache_clear(to_vmx(vcpu));
2996 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2997 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2998 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3000 vmcs_write32(GUEST_TR_AR_BYTES,
3001 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
3002 | VMX_AR_TYPE_BUSY_64_TSS);
3004 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3007 static void exit_lmode(struct kvm_vcpu *vcpu)
3009 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
3010 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3015 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
3017 struct vcpu_vmx *vmx = to_vmx(vcpu);
3020 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
3021 * the CPU is not required to invalidate guest-physical mappings on
3022 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
3023 * associated with the root EPT structure and not any particular VPID
3024 * (INVVPID also isn't required to invalidate guest-physical mappings).
3028 } else if (enable_vpid) {
3029 if (cpu_has_vmx_invvpid_global()) {
3030 vpid_sync_vcpu_global();
3032 vpid_sync_vcpu_single(vmx->vpid);
3033 vpid_sync_vcpu_single(vmx->nested.vpid02);
3038 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
3040 struct kvm_mmu *mmu = vcpu->arch.mmu;
3041 u64 root_hpa = mmu->root_hpa;
3043 /* No flush required if the current context is invalid. */
3044 if (!VALID_PAGE(root_hpa))
3048 ept_sync_context(construct_eptp(vcpu, root_hpa,
3049 mmu->shadow_root_level));
3050 else if (!is_guest_mode(vcpu))
3051 vpid_sync_context(to_vmx(vcpu)->vpid);
3053 vpid_sync_context(nested_get_vpid02(vcpu));
3056 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3059 * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
3060 * vmx_flush_tlb_guest() for an explanation of why this is ok.
3062 vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
3065 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3068 * vpid_sync_context() is a nop if vmx->vpid==0, e.g. if enable_vpid==0
3069 * or a vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit
3070 * are required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3071 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3072 * i.e. no explicit INVVPID is necessary.
3074 vpid_sync_context(to_vmx(vcpu)->vpid);
3077 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3079 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3081 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3084 if (is_pae_paging(vcpu)) {
3085 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3086 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3087 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3088 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3092 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3094 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3096 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3099 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3100 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3101 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3102 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3104 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
3107 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3109 struct kvm_vcpu *vcpu)
3111 struct vcpu_vmx *vmx = to_vmx(vcpu);
3113 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3114 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3115 if (!(cr0 & X86_CR0_PG)) {
3116 /* From paging/starting to nonpaging */
3117 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3118 CPU_BASED_CR3_STORE_EXITING);
3119 vcpu->arch.cr0 = cr0;
3120 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3121 } else if (!is_paging(vcpu)) {
3122 /* From nonpaging to paging */
3123 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3124 CPU_BASED_CR3_STORE_EXITING);
3125 vcpu->arch.cr0 = cr0;
3126 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3129 if (!(cr0 & X86_CR0_WP))
3130 *hw_cr0 &= ~X86_CR0_WP;
3133 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3135 struct vcpu_vmx *vmx = to_vmx(vcpu);
3136 unsigned long hw_cr0;
3138 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3139 if (is_unrestricted_guest(vcpu))
3140 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3142 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3144 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3147 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3151 #ifdef CONFIG_X86_64
3152 if (vcpu->arch.efer & EFER_LME) {
3153 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3155 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3160 if (enable_ept && !is_unrestricted_guest(vcpu))
3161 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3163 vmcs_writel(CR0_READ_SHADOW, cr0);
3164 vmcs_writel(GUEST_CR0, hw_cr0);
3165 vcpu->arch.cr0 = cr0;
3166 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3168 /* depends on vcpu->arch.cr0 to be set to a new value */
3169 vmx->emulation_required = emulation_required(vcpu);
3172 static int vmx_get_max_tdp_level(void)
3174 if (cpu_has_vmx_ept_5levels())
3179 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3181 u64 eptp = VMX_EPTP_MT_WB;
3183 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3185 if (enable_ept_ad_bits &&
3186 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3187 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3193 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3196 struct kvm *kvm = vcpu->kvm;
3197 bool update_guest_cr3 = true;
3198 unsigned long guest_cr3;
3202 eptp = construct_eptp(vcpu, root_hpa, root_level);
3203 vmcs_write64(EPT_POINTER, eptp);
3205 hv_track_root_ept(vcpu, root_hpa);
3207 if (!enable_unrestricted_guest && !is_paging(vcpu))
3208 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3209 else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3210 guest_cr3 = vcpu->arch.cr3;
3211 else /* vmcs01.GUEST_CR3 is already up-to-date. */
3212 update_guest_cr3 = false;
3213 vmx_ept_load_pdptrs(vcpu);
3215 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3218 if (update_guest_cr3)
3219 vmcs_writel(GUEST_CR3, guest_cr3);
3222 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3225 * We operate under the default treatment of SMM, so VMX cannot be
3226 * enabled under SMM. Note, whether or not VMXE is allowed at all is
3227 * handled by kvm_is_valid_cr4().
3229 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3232 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3238 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3240 unsigned long old_cr4 = vcpu->arch.cr4;
3241 struct vcpu_vmx *vmx = to_vmx(vcpu);
3243 * Pass through host's Machine Check Enable value to hw_cr4, which
3244 * is in force while we are in guest mode. Do not let guests control
3245 * this bit, even if host CR4.MCE == 0.
3247 unsigned long hw_cr4;
3249 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3250 if (is_unrestricted_guest(vcpu))
3251 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3252 else if (vmx->rmode.vm86_active)
3253 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3255 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3257 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3258 if (cr4 & X86_CR4_UMIP) {
3259 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3260 hw_cr4 &= ~X86_CR4_UMIP;
3261 } else if (!is_guest_mode(vcpu) ||
3262 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3263 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3267 vcpu->arch.cr4 = cr4;
3268 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3270 if (!is_unrestricted_guest(vcpu)) {
3272 if (!is_paging(vcpu)) {
3273 hw_cr4 &= ~X86_CR4_PAE;
3274 hw_cr4 |= X86_CR4_PSE;
3275 } else if (!(cr4 & X86_CR4_PAE)) {
3276 hw_cr4 &= ~X86_CR4_PAE;
3281 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3282 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3283 * to be manually disabled when guest switches to non-paging
3286 * If !enable_unrestricted_guest, the CPU is always running
3287 * with CR0.PG=1 and CR4 needs to be modified.
3288 * If enable_unrestricted_guest, the CPU automatically
3289 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3291 if (!is_paging(vcpu))
3292 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3295 vmcs_writel(CR4_READ_SHADOW, cr4);
3296 vmcs_writel(GUEST_CR4, hw_cr4);
3298 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3299 kvm_update_cpuid_runtime(vcpu);
3302 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3304 struct vcpu_vmx *vmx = to_vmx(vcpu);
3307 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3308 *var = vmx->rmode.segs[seg];
3309 if (seg == VCPU_SREG_TR
3310 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3312 var->base = vmx_read_guest_seg_base(vmx, seg);
3313 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3316 var->base = vmx_read_guest_seg_base(vmx, seg);
3317 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3318 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3319 ar = vmx_read_guest_seg_ar(vmx, seg);
3320 var->unusable = (ar >> 16) & 1;
3321 var->type = ar & 15;
3322 var->s = (ar >> 4) & 1;
3323 var->dpl = (ar >> 5) & 3;
3325 * Some userspaces do not preserve unusable property. Since usable
3326 * segment has to be present according to VMX spec we can use present
3327 * property to amend userspace bug by making unusable segment always
3328 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3329 * segment as unusable.
3331 var->present = !var->unusable;
3332 var->avl = (ar >> 12) & 1;
3333 var->l = (ar >> 13) & 1;
3334 var->db = (ar >> 14) & 1;
3335 var->g = (ar >> 15) & 1;
3338 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3340 struct kvm_segment s;
3342 if (to_vmx(vcpu)->rmode.vm86_active) {
3343 vmx_get_segment(vcpu, &s, seg);
3346 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3349 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3351 struct vcpu_vmx *vmx = to_vmx(vcpu);
3353 if (unlikely(vmx->rmode.vm86_active))
3356 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3357 return VMX_AR_DPL(ar);
3361 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3365 if (var->unusable || !var->present)
3368 ar = var->type & 15;
3369 ar |= (var->s & 1) << 4;
3370 ar |= (var->dpl & 3) << 5;
3371 ar |= (var->present & 1) << 7;
3372 ar |= (var->avl & 1) << 12;
3373 ar |= (var->l & 1) << 13;
3374 ar |= (var->db & 1) << 14;
3375 ar |= (var->g & 1) << 15;
3381 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3383 struct vcpu_vmx *vmx = to_vmx(vcpu);
3384 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3386 vmx_segment_cache_clear(vmx);
3388 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3389 vmx->rmode.segs[seg] = *var;
3390 if (seg == VCPU_SREG_TR)
3391 vmcs_write16(sf->selector, var->selector);
3393 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3397 vmcs_writel(sf->base, var->base);
3398 vmcs_write32(sf->limit, var->limit);
3399 vmcs_write16(sf->selector, var->selector);
3402 * Fix the "Accessed" bit in AR field of segment registers for older
3404 * IA32 arch specifies that at the time of processor reset the
3405 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3406 * is setting it to 0 in the userland code. This causes invalid guest
3407 * state vmexit when "unrestricted guest" mode is turned on.
3408 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3409 * tree. Newer qemu binaries with that qemu fix would not need this
3412 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3413 var->type |= 0x1; /* Accessed */
3415 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3418 vmx->emulation_required = emulation_required(vcpu);
3421 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3423 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3425 *db = (ar >> 14) & 1;
3426 *l = (ar >> 13) & 1;
3429 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3431 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3432 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3435 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3437 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3438 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3441 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3443 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3444 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3447 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3449 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3450 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3453 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3455 struct kvm_segment var;
3458 vmx_get_segment(vcpu, &var, seg);
3460 if (seg == VCPU_SREG_CS)
3462 ar = vmx_segment_access_rights(&var);
3464 if (var.base != (var.selector << 4))
3466 if (var.limit != 0xffff)
3474 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3476 struct kvm_segment cs;
3477 unsigned int cs_rpl;
3479 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3480 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3484 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3488 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3489 if (cs.dpl > cs_rpl)
3492 if (cs.dpl != cs_rpl)
3498 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3502 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3504 struct kvm_segment ss;
3505 unsigned int ss_rpl;
3507 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3508 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3512 if (ss.type != 3 && ss.type != 7)
3516 if (ss.dpl != ss_rpl) /* DPL != RPL */
3524 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3526 struct kvm_segment var;
3529 vmx_get_segment(vcpu, &var, seg);
3530 rpl = var.selector & SEGMENT_RPL_MASK;
3538 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3539 if (var.dpl < rpl) /* DPL < RPL */
3543 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3549 static bool tr_valid(struct kvm_vcpu *vcpu)
3551 struct kvm_segment tr;
3553 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3557 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3559 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3567 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3569 struct kvm_segment ldtr;
3571 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3575 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3585 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3587 struct kvm_segment cs, ss;
3589 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3590 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3592 return ((cs.selector & SEGMENT_RPL_MASK) ==
3593 (ss.selector & SEGMENT_RPL_MASK));
3597 * Check if guest state is valid. Returns true if valid, false if
3599 * We assume that registers are always usable
3601 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3603 /* real mode guest state checks */
3604 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3605 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3607 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3609 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3611 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3613 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3615 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3618 /* protected mode guest state checks */
3619 if (!cs_ss_rpl_check(vcpu))
3621 if (!code_segment_valid(vcpu))
3623 if (!stack_segment_valid(vcpu))
3625 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3627 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3629 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3631 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3633 if (!tr_valid(vcpu))
3635 if (!ldtr_valid(vcpu))
3639 * - Add checks on RIP
3640 * - Add checks on RFLAGS
3646 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3648 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3652 for (i = 0; i < 3; i++) {
3653 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3657 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3658 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3662 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3668 static int init_rmode_identity_map(struct kvm *kvm)
3670 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3675 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3676 mutex_lock(&kvm->slots_lock);
3678 if (likely(kvm_vmx->ept_identity_pagetable_done))
3681 if (!kvm_vmx->ept_identity_map_addr)
3682 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3684 uaddr = __x86_set_memory_region(kvm,
3685 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3686 kvm_vmx->ept_identity_map_addr,
3688 if (IS_ERR(uaddr)) {
3693 /* Set up identity-mapping pagetable for EPT in real mode */
3694 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3695 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3696 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3697 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3702 kvm_vmx->ept_identity_pagetable_done = true;
3705 mutex_unlock(&kvm->slots_lock);
3709 static void seg_setup(int seg)
3711 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3714 vmcs_write16(sf->selector, 0);
3715 vmcs_writel(sf->base, 0);
3716 vmcs_write32(sf->limit, 0xffff);
3718 if (seg == VCPU_SREG_CS)
3719 ar |= 0x08; /* code segment */
3721 vmcs_write32(sf->ar_bytes, ar);
3724 static int alloc_apic_access_page(struct kvm *kvm)
3730 mutex_lock(&kvm->slots_lock);
3731 if (kvm->arch.apic_access_page_done)
3733 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3734 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3740 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3741 if (is_error_page(page)) {
3747 * Do not pin the page in memory, so that memory hot-unplug
3748 * is able to migrate it.
3751 kvm->arch.apic_access_page_done = true;
3753 mutex_unlock(&kvm->slots_lock);
3757 int allocate_vpid(void)
3763 spin_lock(&vmx_vpid_lock);
3764 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3765 if (vpid < VMX_NR_VPIDS)
3766 __set_bit(vpid, vmx_vpid_bitmap);
3769 spin_unlock(&vmx_vpid_lock);
3773 void free_vpid(int vpid)
3775 if (!enable_vpid || vpid == 0)
3777 spin_lock(&vmx_vpid_lock);
3778 __clear_bit(vpid, vmx_vpid_bitmap);
3779 spin_unlock(&vmx_vpid_lock);
3782 static void vmx_clear_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3784 int f = sizeof(unsigned long);
3787 __clear_bit(msr, msr_bitmap + 0x000 / f);
3788 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3789 __clear_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3792 static void vmx_clear_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3794 int f = sizeof(unsigned long);
3797 __clear_bit(msr, msr_bitmap + 0x800 / f);
3798 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3799 __clear_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3802 static void vmx_set_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3804 int f = sizeof(unsigned long);
3807 __set_bit(msr, msr_bitmap + 0x000 / f);
3808 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3809 __set_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3812 static void vmx_set_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3814 int f = sizeof(unsigned long);
3817 __set_bit(msr, msr_bitmap + 0x800 / f);
3818 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3819 __set_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3822 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3824 struct vcpu_vmx *vmx = to_vmx(vcpu);
3825 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3827 if (!cpu_has_vmx_msr_bitmap())
3830 if (static_branch_unlikely(&enable_evmcs))
3831 evmcs_touch_msr_bitmap();
3834 * Mark the desired intercept state in shadow bitmap, this is needed
3835 * for resync when the MSR filters change.
3837 if (is_valid_passthrough_msr(msr)) {
3838 int idx = possible_passthrough_msr_slot(msr);
3840 if (idx != -ENOENT) {
3841 if (type & MSR_TYPE_R)
3842 clear_bit(idx, vmx->shadow_msr_intercept.read);
3843 if (type & MSR_TYPE_W)
3844 clear_bit(idx, vmx->shadow_msr_intercept.write);
3848 if ((type & MSR_TYPE_R) &&
3849 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3850 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3851 type &= ~MSR_TYPE_R;
3854 if ((type & MSR_TYPE_W) &&
3855 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3856 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3857 type &= ~MSR_TYPE_W;
3860 if (type & MSR_TYPE_R)
3861 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3863 if (type & MSR_TYPE_W)
3864 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3867 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3869 struct vcpu_vmx *vmx = to_vmx(vcpu);
3870 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3872 if (!cpu_has_vmx_msr_bitmap())
3875 if (static_branch_unlikely(&enable_evmcs))
3876 evmcs_touch_msr_bitmap();
3879 * Mark the desired intercept state in shadow bitmap, this is needed
3880 * for resync when the MSR filter changes.
3882 if (is_valid_passthrough_msr(msr)) {
3883 int idx = possible_passthrough_msr_slot(msr);
3885 if (idx != -ENOENT) {
3886 if (type & MSR_TYPE_R)
3887 set_bit(idx, vmx->shadow_msr_intercept.read);
3888 if (type & MSR_TYPE_W)
3889 set_bit(idx, vmx->shadow_msr_intercept.write);
3893 if (type & MSR_TYPE_R)
3894 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3896 if (type & MSR_TYPE_W)
3897 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3900 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3904 if (cpu_has_secondary_exec_ctrls() &&
3905 (secondary_exec_controls_get(to_vmx(vcpu)) &
3906 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3907 mode |= MSR_BITMAP_MODE_X2APIC;
3908 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3909 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3915 static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
3917 unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3918 unsigned long read_intercept;
3921 read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3923 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3924 unsigned int read_idx = msr / BITS_PER_LONG;
3925 unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3927 msr_bitmap[read_idx] = read_intercept;
3928 msr_bitmap[write_idx] = ~0ul;
3932 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu, u8 mode)
3934 if (!cpu_has_vmx_msr_bitmap())
3937 vmx_reset_x2apic_msrs(vcpu, mode);
3940 * TPR reads and writes can be virtualized even if virtual interrupt
3941 * delivery is not in use.
3943 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
3944 !(mode & MSR_BITMAP_MODE_X2APIC));
3946 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3947 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
3948 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3949 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3953 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3955 struct vcpu_vmx *vmx = to_vmx(vcpu);
3956 u8 mode = vmx_msr_bitmap_mode(vcpu);
3957 u8 changed = mode ^ vmx->msr_bitmap_mode;
3962 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3963 vmx_update_msr_bitmap_x2apic(vcpu, mode);
3965 vmx->msr_bitmap_mode = mode;
3968 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
3970 struct vcpu_vmx *vmx = to_vmx(vcpu);
3971 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3974 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
3975 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
3976 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
3977 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
3978 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3979 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3980 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3984 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3986 struct vcpu_vmx *vmx = to_vmx(vcpu);
3991 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3992 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3993 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3996 rvi = vmx_get_rvi();
3998 vapic_page = vmx->nested.virtual_apic_map.hva;
3999 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
4001 return ((rvi & 0xf0) > (vppr & 0xf0));
4004 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
4006 struct vcpu_vmx *vmx = to_vmx(vcpu);
4010 * Set intercept permissions for all potentially passed through MSRs
4011 * again. They will automatically get filtered through the MSR filter,
4012 * so we are back in sync after this.
4014 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
4015 u32 msr = vmx_possible_passthrough_msrs[i];
4016 bool read = test_bit(i, vmx->shadow_msr_intercept.read);
4017 bool write = test_bit(i, vmx->shadow_msr_intercept.write);
4019 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_R, read);
4020 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_W, write);
4023 pt_update_intercept_for_msr(vcpu);
4024 vmx_update_msr_bitmap_x2apic(vcpu, vmx_msr_bitmap_mode(vcpu));
4027 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
4031 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
4033 if (vcpu->mode == IN_GUEST_MODE) {
4035 * The vector of interrupt to be delivered to vcpu had
4036 * been set in PIR before this function.
4038 * Following cases will be reached in this block, and
4039 * we always send a notification event in all cases as
4042 * Case 1: vcpu keeps in non-root mode. Sending a
4043 * notification event posts the interrupt to vcpu.
4045 * Case 2: vcpu exits to root mode and is still
4046 * runnable. PIR will be synced to vIRR before the
4047 * next vcpu entry. Sending a notification event in
4048 * this case has no effect, as vcpu is not in root
4051 * Case 3: vcpu exits to root mode and is blocked.
4052 * vcpu_block() has already synced PIR to vIRR and
4053 * never blocks vcpu if vIRR is not cleared. Therefore,
4054 * a blocked vcpu here does not wait for any requested
4055 * interrupts in PIR, and sending a notification event
4056 * which has no effect is safe here.
4059 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
4066 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4069 struct vcpu_vmx *vmx = to_vmx(vcpu);
4071 if (is_guest_mode(vcpu) &&
4072 vector == vmx->nested.posted_intr_nv) {
4074 * If a posted intr is not recognized by hardware,
4075 * we will accomplish it in the next vmentry.
4077 vmx->nested.pi_pending = true;
4078 kvm_make_request(KVM_REQ_EVENT, vcpu);
4079 /* the PIR and ON have been set by L1. */
4080 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
4081 kvm_vcpu_kick(vcpu);
4087 * Send interrupt to vcpu via posted interrupt way.
4088 * 1. If target vcpu is running(non-root mode), send posted interrupt
4089 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4090 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4091 * interrupt from PIR in next vmentry.
4093 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4095 struct vcpu_vmx *vmx = to_vmx(vcpu);
4098 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4102 if (!vcpu->arch.apicv_active)
4105 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4108 /* If a previous notification has sent the IPI, nothing to do. */
4109 if (pi_test_and_set_on(&vmx->pi_desc))
4112 if (vcpu != kvm_get_running_vcpu() &&
4113 !kvm_vcpu_trigger_posted_interrupt(vcpu, false))
4114 kvm_vcpu_kick(vcpu);
4120 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4121 * will not change in the lifetime of the guest.
4122 * Note that host-state that does change is set elsewhere. E.g., host-state
4123 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4125 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4129 unsigned long cr0, cr3, cr4;
4132 WARN_ON(cr0 & X86_CR0_TS);
4133 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4136 * Save the most likely value for this task's CR3 in the VMCS.
4137 * We can't use __get_current_cr3_fast() because we're not atomic.
4140 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4141 vmx->loaded_vmcs->host_state.cr3 = cr3;
4143 /* Save the most likely value for this task's CR4 in the VMCS. */
4144 cr4 = cr4_read_shadow();
4145 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4146 vmx->loaded_vmcs->host_state.cr4 = cr4;
4148 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4149 #ifdef CONFIG_X86_64
4151 * Load null selectors, so we can avoid reloading them in
4152 * vmx_prepare_switch_to_host(), in case userspace uses
4153 * the null selectors too (the expected case).
4155 vmcs_write16(HOST_DS_SELECTOR, 0);
4156 vmcs_write16(HOST_ES_SELECTOR, 0);
4158 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4159 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4161 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4162 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4164 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4166 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4168 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4169 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4170 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4171 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4173 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4174 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4175 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4178 if (cpu_has_load_ia32_efer())
4179 vmcs_write64(HOST_IA32_EFER, host_efer);
4182 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4184 struct kvm_vcpu *vcpu = &vmx->vcpu;
4186 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4187 ~vcpu->arch.cr4_guest_rsvd_bits;
4189 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PGE;
4190 if (is_guest_mode(&vmx->vcpu))
4191 vcpu->arch.cr4_guest_owned_bits &=
4192 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4193 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4196 u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4198 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4200 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4201 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4204 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4206 if (!enable_preemption_timer)
4207 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4209 return pin_based_exec_ctrl;
4212 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4214 struct vcpu_vmx *vmx = to_vmx(vcpu);
4216 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4217 if (cpu_has_secondary_exec_ctrls()) {
4218 if (kvm_vcpu_apicv_active(vcpu))
4219 secondary_exec_controls_setbit(vmx,
4220 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4221 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4223 secondary_exec_controls_clearbit(vmx,
4224 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4225 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4228 if (cpu_has_vmx_msr_bitmap())
4229 vmx_update_msr_bitmap(vcpu);
4232 u32 vmx_exec_control(struct vcpu_vmx *vmx)
4234 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4236 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4237 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4239 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4240 exec_control &= ~CPU_BASED_TPR_SHADOW;
4241 #ifdef CONFIG_X86_64
4242 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4243 CPU_BASED_CR8_LOAD_EXITING;
4247 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4248 CPU_BASED_CR3_LOAD_EXITING |
4249 CPU_BASED_INVLPG_EXITING;
4250 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4251 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4252 CPU_BASED_MONITOR_EXITING);
4253 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4254 exec_control &= ~CPU_BASED_HLT_EXITING;
4255 return exec_control;
4259 * Adjust a single secondary execution control bit to intercept/allow an
4260 * instruction in the guest. This is usually done based on whether or not a
4261 * feature has been exposed to the guest in order to correctly emulate faults.
4264 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4265 u32 control, bool enabled, bool exiting)
4268 * If the control is for an opt-in feature, clear the control if the
4269 * feature is not exposed to the guest, i.e. not enabled. If the
4270 * control is opt-out, i.e. an exiting control, clear the control if
4271 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4272 * disabled for the associated instruction. Note, the caller is
4273 * responsible presetting exec_control to set all supported bits.
4275 if (enabled == exiting)
4276 *exec_control &= ~control;
4279 * Update the nested MSR settings so that a nested VMM can/can't set
4280 * controls for features that are/aren't exposed to the guest.
4284 vmx->nested.msrs.secondary_ctls_high |= control;
4286 vmx->nested.msrs.secondary_ctls_high &= ~control;
4291 * Wrapper macro for the common case of adjusting a secondary execution control
4292 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4293 * verifies that the control is actually supported by KVM and hardware.
4295 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4299 if (cpu_has_vmx_##name()) { \
4300 __enabled = guest_cpuid_has(&(vmx)->vcpu, \
4301 X86_FEATURE_##feat_name); \
4302 vmx_adjust_secondary_exec_control(vmx, exec_control, \
4303 SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4307 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4308 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4309 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4311 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4312 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4314 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
4316 struct kvm_vcpu *vcpu = &vmx->vcpu;
4318 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4320 if (vmx_pt_mode_is_system())
4321 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4322 if (!cpu_need_virtualize_apic_accesses(vcpu))
4323 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4325 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4327 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4328 enable_unrestricted_guest = 0;
4330 if (!enable_unrestricted_guest)
4331 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4332 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4333 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4334 if (!kvm_vcpu_apicv_active(vcpu))
4335 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4336 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4337 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4339 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4340 * in vmx_set_cr4. */
4341 exec_control &= ~SECONDARY_EXEC_DESC;
4343 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4345 We can NOT enable shadow_vmcs here because we don't have yet
4348 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4351 * PML is enabled/disabled when dirty logging of memsmlots changes, but
4352 * it needs to be set here when dirty logging is already active, e.g.
4353 * if this vCPU was created after dirty logging was enabled.
4355 if (!vcpu->kvm->arch.cpu_dirty_logging_count)
4356 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4358 if (cpu_has_vmx_xsaves()) {
4359 /* Exposing XSAVES only when XSAVE is exposed */
4360 bool xsaves_enabled =
4361 boot_cpu_has(X86_FEATURE_XSAVE) &&
4362 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4363 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4365 vcpu->arch.xsaves_enabled = xsaves_enabled;
4367 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4368 SECONDARY_EXEC_XSAVES,
4369 xsaves_enabled, false);
4372 vmx_adjust_sec_exec_feature(vmx, &exec_control, rdtscp, RDTSCP);
4373 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4375 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4376 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4378 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4379 ENABLE_USR_WAIT_PAUSE, false);
4381 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4382 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4384 vmx->secondary_exec_control = exec_control;
4387 #define VMX_XSS_EXIT_BITMAP 0
4390 * Noting that the initialization of Guest-state Area of VMCS is in
4393 static void init_vmcs(struct vcpu_vmx *vmx)
4396 nested_vmx_set_vmcs_shadowing_bitmap();
4398 if (cpu_has_vmx_msr_bitmap())
4399 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4401 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4404 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4406 exec_controls_set(vmx, vmx_exec_control(vmx));
4408 if (cpu_has_secondary_exec_ctrls()) {
4409 vmx_compute_secondary_exec_control(vmx);
4410 secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
4413 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4414 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4415 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4416 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4417 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4419 vmcs_write16(GUEST_INTR_STATUS, 0);
4421 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4422 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4425 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4426 vmcs_write32(PLE_GAP, ple_gap);
4427 vmx->ple_window = ple_window;
4428 vmx->ple_window_dirty = true;
4431 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4432 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4433 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4435 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4436 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4437 vmx_set_constant_host_state(vmx);
4438 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4439 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4441 if (cpu_has_vmx_vmfunc())
4442 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4444 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4445 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4446 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4447 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4448 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4450 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4451 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4453 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4455 /* 22.2.1, 20.8.1 */
4456 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4458 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4459 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4461 set_cr4_guest_host_mask(vmx);
4464 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4466 if (cpu_has_vmx_xsaves())
4467 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4470 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4471 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4474 vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4476 if (vmx_pt_mode_is_host_guest()) {
4477 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4478 /* Bit[6~0] are forced to 1, writes are ignored. */
4479 vmx->pt_desc.guest.output_mask = 0x7F;
4480 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4484 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4486 struct vcpu_vmx *vmx = to_vmx(vcpu);
4487 struct msr_data apic_base_msr;
4490 vmx->rmode.vm86_active = 0;
4493 vmx->msr_ia32_umwait_control = 0;
4495 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4496 vmx->hv_deadline_tsc = -1;
4497 kvm_set_cr8(vcpu, 0);
4500 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4501 MSR_IA32_APICBASE_ENABLE;
4502 if (kvm_vcpu_is_reset_bsp(vcpu))
4503 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4504 apic_base_msr.host_initiated = true;
4505 kvm_set_apic_base(vcpu, &apic_base_msr);
4508 vmx_segment_cache_clear(vmx);
4510 seg_setup(VCPU_SREG_CS);
4511 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4512 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4514 seg_setup(VCPU_SREG_DS);
4515 seg_setup(VCPU_SREG_ES);
4516 seg_setup(VCPU_SREG_FS);
4517 seg_setup(VCPU_SREG_GS);
4518 seg_setup(VCPU_SREG_SS);
4520 vmcs_write16(GUEST_TR_SELECTOR, 0);
4521 vmcs_writel(GUEST_TR_BASE, 0);
4522 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4523 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4525 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4526 vmcs_writel(GUEST_LDTR_BASE, 0);
4527 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4528 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4531 vmcs_write32(GUEST_SYSENTER_CS, 0);
4532 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4533 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4534 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4537 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4538 kvm_rip_write(vcpu, 0xfff0);
4540 vmcs_writel(GUEST_GDTR_BASE, 0);
4541 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4543 vmcs_writel(GUEST_IDTR_BASE, 0);
4544 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4546 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4547 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4548 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4549 if (kvm_mpx_supported())
4550 vmcs_write64(GUEST_BNDCFGS, 0);
4554 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4556 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4557 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4558 if (cpu_need_tpr_shadow(vcpu))
4559 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4560 __pa(vcpu->arch.apic->regs));
4561 vmcs_write32(TPR_THRESHOLD, 0);
4564 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4566 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4567 vmx->vcpu.arch.cr0 = cr0;
4568 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4569 vmx_set_cr4(vcpu, 0);
4570 vmx_set_efer(vcpu, 0);
4572 vmx_update_exception_bitmap(vcpu);
4574 vpid_sync_context(vmx->vpid);
4576 vmx_clear_hlt(vcpu);
4579 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4581 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4584 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4587 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4588 vmx_enable_irq_window(vcpu);
4592 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4595 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4597 struct vcpu_vmx *vmx = to_vmx(vcpu);
4599 int irq = vcpu->arch.interrupt.nr;
4601 trace_kvm_inj_virq(irq);
4603 ++vcpu->stat.irq_injections;
4604 if (vmx->rmode.vm86_active) {
4606 if (vcpu->arch.interrupt.soft)
4607 inc_eip = vcpu->arch.event_exit_inst_len;
4608 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4611 intr = irq | INTR_INFO_VALID_MASK;
4612 if (vcpu->arch.interrupt.soft) {
4613 intr |= INTR_TYPE_SOFT_INTR;
4614 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4615 vmx->vcpu.arch.event_exit_inst_len);
4617 intr |= INTR_TYPE_EXT_INTR;
4618 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4620 vmx_clear_hlt(vcpu);
4623 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4625 struct vcpu_vmx *vmx = to_vmx(vcpu);
4629 * Tracking the NMI-blocked state in software is built upon
4630 * finding the next open IRQ window. This, in turn, depends on
4631 * well-behaving guests: They have to keep IRQs disabled at
4632 * least as long as the NMI handler runs. Otherwise we may
4633 * cause NMI nesting, maybe breaking the guest. But as this is
4634 * highly unlikely, we can live with the residual risk.
4636 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4637 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4640 ++vcpu->stat.nmi_injections;
4641 vmx->loaded_vmcs->nmi_known_unmasked = false;
4643 if (vmx->rmode.vm86_active) {
4644 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4648 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4649 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4651 vmx_clear_hlt(vcpu);
4654 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4656 struct vcpu_vmx *vmx = to_vmx(vcpu);
4660 return vmx->loaded_vmcs->soft_vnmi_blocked;
4661 if (vmx->loaded_vmcs->nmi_known_unmasked)
4663 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4664 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4668 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4670 struct vcpu_vmx *vmx = to_vmx(vcpu);
4673 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4674 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4675 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4678 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4680 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4681 GUEST_INTR_STATE_NMI);
4683 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4684 GUEST_INTR_STATE_NMI);
4688 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4690 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4693 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4696 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4697 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4698 GUEST_INTR_STATE_NMI));
4701 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4703 if (to_vmx(vcpu)->nested.nested_run_pending)
4706 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4707 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4710 return !vmx_nmi_blocked(vcpu);
4713 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4715 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4718 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4719 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4720 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4723 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4725 if (to_vmx(vcpu)->nested.nested_run_pending)
4729 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4730 * e.g. if the IRQ arrived asynchronously after checking nested events.
4732 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4735 return !vmx_interrupt_blocked(vcpu);
4738 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4742 if (enable_unrestricted_guest)
4745 mutex_lock(&kvm->slots_lock);
4746 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4748 mutex_unlock(&kvm->slots_lock);
4751 return PTR_ERR(ret);
4753 to_kvm_vmx(kvm)->tss_addr = addr;
4755 return init_rmode_tss(kvm, ret);
4758 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4760 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4764 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4769 * Update instruction length as we may reinject the exception
4770 * from user space while in guest debugging mode.
4772 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4773 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4774 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4778 return !(vcpu->guest_debug &
4779 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4793 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4794 int vec, u32 err_code)
4797 * Instruction with address size override prefix opcode 0x67
4798 * Cause the #SS fault with 0 error code in VM86 mode.
4800 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4801 if (kvm_emulate_instruction(vcpu, 0)) {
4802 if (vcpu->arch.halt_request) {
4803 vcpu->arch.halt_request = 0;
4804 return kvm_vcpu_halt(vcpu);
4812 * Forward all other exceptions that are valid in real mode.
4813 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4814 * the required debugging infrastructure rework.
4816 kvm_queue_exception(vcpu, vec);
4820 static int handle_machine_check(struct kvm_vcpu *vcpu)
4822 /* handled by vmx_vcpu_run() */
4827 * If the host has split lock detection disabled, then #AC is
4828 * unconditionally injected into the guest, which is the pre split lock
4829 * detection behaviour.
4831 * If the host has split lock detection enabled then #AC is
4832 * only injected into the guest when:
4833 * - Guest CPL == 3 (user mode)
4834 * - Guest has #AC detection enabled in CR0
4835 * - Guest EFLAGS has AC bit set
4837 static inline bool guest_inject_ac(struct kvm_vcpu *vcpu)
4839 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4842 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4843 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4846 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4848 struct vcpu_vmx *vmx = to_vmx(vcpu);
4849 struct kvm_run *kvm_run = vcpu->run;
4850 u32 intr_info, ex_no, error_code;
4851 unsigned long cr2, rip, dr6;
4854 vect_info = vmx->idt_vectoring_info;
4855 intr_info = vmx_get_intr_info(vcpu);
4857 if (is_machine_check(intr_info) || is_nmi(intr_info))
4858 return 1; /* handled by handle_exception_nmi_irqoff() */
4860 if (is_invalid_opcode(intr_info))
4861 return handle_ud(vcpu);
4864 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4865 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4867 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4868 WARN_ON_ONCE(!enable_vmware_backdoor);
4871 * VMware backdoor emulation on #GP interception only handles
4872 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4873 * error code on #GP.
4876 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4879 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4883 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4884 * MMIO, it is better to report an internal error.
4885 * See the comments in vmx_handle_exit.
4887 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4888 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4889 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4890 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4891 vcpu->run->internal.ndata = 4;
4892 vcpu->run->internal.data[0] = vect_info;
4893 vcpu->run->internal.data[1] = intr_info;
4894 vcpu->run->internal.data[2] = error_code;
4895 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
4899 if (is_page_fault(intr_info)) {
4900 cr2 = vmx_get_exit_qual(vcpu);
4901 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
4903 * EPT will cause page fault only if we need to
4904 * detect illegal GPAs.
4906 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
4907 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
4910 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4913 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4915 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4916 return handle_rmode_exception(vcpu, ex_no, error_code);
4920 dr6 = vmx_get_exit_qual(vcpu);
4921 if (!(vcpu->guest_debug &
4922 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4923 if (is_icebp(intr_info))
4924 WARN_ON(!skip_emulated_instruction(vcpu));
4926 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
4929 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
4930 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4934 * Update instruction length as we may reinject #BP from
4935 * user space while in guest debugging mode. Reading it for
4936 * #DB as well causes no harm, it is not used in that case.
4938 vmx->vcpu.arch.event_exit_inst_len =
4939 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4940 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4941 rip = kvm_rip_read(vcpu);
4942 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4943 kvm_run->debug.arch.exception = ex_no;
4946 if (guest_inject_ac(vcpu)) {
4947 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4952 * Handle split lock. Depending on detection mode this will
4953 * either warn and disable split lock detection for this
4954 * task or force SIGBUS on it.
4956 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4960 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4961 kvm_run->ex.exception = ex_no;
4962 kvm_run->ex.error_code = error_code;
4968 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4970 ++vcpu->stat.irq_exits;
4974 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4976 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4977 vcpu->mmio_needed = 0;
4981 static int handle_io(struct kvm_vcpu *vcpu)
4983 unsigned long exit_qualification;
4984 int size, in, string;
4987 exit_qualification = vmx_get_exit_qual(vcpu);
4988 string = (exit_qualification & 16) != 0;
4990 ++vcpu->stat.io_exits;
4993 return kvm_emulate_instruction(vcpu, 0);
4995 port = exit_qualification >> 16;
4996 size = (exit_qualification & 7) + 1;
4997 in = (exit_qualification & 8) != 0;
4999 return kvm_fast_pio(vcpu, size, port, in);
5003 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5006 * Patch in the VMCALL instruction:
5008 hypercall[0] = 0x0f;
5009 hypercall[1] = 0x01;
5010 hypercall[2] = 0xc1;
5013 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5014 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5016 if (is_guest_mode(vcpu)) {
5017 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5018 unsigned long orig_val = val;
5021 * We get here when L2 changed cr0 in a way that did not change
5022 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5023 * but did change L0 shadowed bits. So we first calculate the
5024 * effective cr0 value that L1 would like to write into the
5025 * hardware. It consists of the L2-owned bits from the new
5026 * value combined with the L1-owned bits from L1's guest_cr0.
5028 val = (val & ~vmcs12->cr0_guest_host_mask) |
5029 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5031 if (!nested_guest_cr0_valid(vcpu, val))
5034 if (kvm_set_cr0(vcpu, val))
5036 vmcs_writel(CR0_READ_SHADOW, orig_val);
5039 if (to_vmx(vcpu)->nested.vmxon &&
5040 !nested_host_cr0_valid(vcpu, val))
5043 return kvm_set_cr0(vcpu, val);
5047 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5049 if (is_guest_mode(vcpu)) {
5050 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5051 unsigned long orig_val = val;
5053 /* analogously to handle_set_cr0 */
5054 val = (val & ~vmcs12->cr4_guest_host_mask) |
5055 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5056 if (kvm_set_cr4(vcpu, val))
5058 vmcs_writel(CR4_READ_SHADOW, orig_val);
5061 return kvm_set_cr4(vcpu, val);
5064 static int handle_desc(struct kvm_vcpu *vcpu)
5066 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
5067 return kvm_emulate_instruction(vcpu, 0);
5070 static int handle_cr(struct kvm_vcpu *vcpu)
5072 unsigned long exit_qualification, val;
5078 exit_qualification = vmx_get_exit_qual(vcpu);
5079 cr = exit_qualification & 15;
5080 reg = (exit_qualification >> 8) & 15;
5081 switch ((exit_qualification >> 4) & 3) {
5082 case 0: /* mov to cr */
5083 val = kvm_register_read(vcpu, reg);
5084 trace_kvm_cr_write(cr, val);
5087 err = handle_set_cr0(vcpu, val);
5088 return kvm_complete_insn_gp(vcpu, err);
5090 WARN_ON_ONCE(enable_unrestricted_guest);
5091 err = kvm_set_cr3(vcpu, val);
5092 return kvm_complete_insn_gp(vcpu, err);
5094 err = handle_set_cr4(vcpu, val);
5095 return kvm_complete_insn_gp(vcpu, err);
5097 u8 cr8_prev = kvm_get_cr8(vcpu);
5099 err = kvm_set_cr8(vcpu, cr8);
5100 ret = kvm_complete_insn_gp(vcpu, err);
5101 if (lapic_in_kernel(vcpu))
5103 if (cr8_prev <= cr8)
5106 * TODO: we might be squashing a
5107 * KVM_GUESTDBG_SINGLESTEP-triggered
5108 * KVM_EXIT_DEBUG here.
5110 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5116 WARN_ONCE(1, "Guest should always own CR0.TS");
5117 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5118 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5119 return kvm_skip_emulated_instruction(vcpu);
5120 case 1: /*mov from cr*/
5123 WARN_ON_ONCE(enable_unrestricted_guest);
5124 val = kvm_read_cr3(vcpu);
5125 kvm_register_write(vcpu, reg, val);
5126 trace_kvm_cr_read(cr, val);
5127 return kvm_skip_emulated_instruction(vcpu);
5129 val = kvm_get_cr8(vcpu);
5130 kvm_register_write(vcpu, reg, val);
5131 trace_kvm_cr_read(cr, val);
5132 return kvm_skip_emulated_instruction(vcpu);
5136 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5137 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5138 kvm_lmsw(vcpu, val);
5140 return kvm_skip_emulated_instruction(vcpu);
5144 vcpu->run->exit_reason = 0;
5145 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5146 (int)(exit_qualification >> 4) & 3, cr);
5150 static int handle_dr(struct kvm_vcpu *vcpu)
5152 unsigned long exit_qualification;
5156 exit_qualification = vmx_get_exit_qual(vcpu);
5157 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5159 /* First, if DR does not exist, trigger UD */
5160 if (!kvm_require_dr(vcpu, dr))
5163 if (kvm_x86_ops.get_cpl(vcpu) > 0)
5166 dr7 = vmcs_readl(GUEST_DR7);
5169 * As the vm-exit takes precedence over the debug trap, we
5170 * need to emulate the latter, either for the host or the
5171 * guest debugging itself.
5173 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5174 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5175 vcpu->run->debug.arch.dr7 = dr7;
5176 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5177 vcpu->run->debug.arch.exception = DB_VECTOR;
5178 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5181 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5186 if (vcpu->guest_debug == 0) {
5187 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5190 * No more DR vmexits; force a reload of the debug registers
5191 * and reenter on this instruction. The next vmexit will
5192 * retrieve the full state of the debug registers.
5194 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5198 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5199 if (exit_qualification & TYPE_MOV_FROM_DR) {
5202 kvm_get_dr(vcpu, dr, &val);
5203 kvm_register_write(vcpu, reg, val);
5206 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5210 return kvm_complete_insn_gp(vcpu, err);
5213 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5215 get_debugreg(vcpu->arch.db[0], 0);
5216 get_debugreg(vcpu->arch.db[1], 1);
5217 get_debugreg(vcpu->arch.db[2], 2);
5218 get_debugreg(vcpu->arch.db[3], 3);
5219 get_debugreg(vcpu->arch.dr6, 6);
5220 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5222 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5223 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5226 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5228 vmcs_writel(GUEST_DR7, val);
5231 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5233 kvm_apic_update_ppr(vcpu);
5237 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5239 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5241 kvm_make_request(KVM_REQ_EVENT, vcpu);
5243 ++vcpu->stat.irq_window_exits;
5247 static int handle_invlpg(struct kvm_vcpu *vcpu)
5249 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5251 kvm_mmu_invlpg(vcpu, exit_qualification);
5252 return kvm_skip_emulated_instruction(vcpu);
5255 static int handle_apic_access(struct kvm_vcpu *vcpu)
5257 if (likely(fasteoi)) {
5258 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5259 int access_type, offset;
5261 access_type = exit_qualification & APIC_ACCESS_TYPE;
5262 offset = exit_qualification & APIC_ACCESS_OFFSET;
5264 * Sane guest uses MOV to write EOI, with written value
5265 * not cared. So make a short-circuit here by avoiding
5266 * heavy instruction emulation.
5268 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5269 (offset == APIC_EOI)) {
5270 kvm_lapic_set_eoi(vcpu);
5271 return kvm_skip_emulated_instruction(vcpu);
5274 return kvm_emulate_instruction(vcpu, 0);
5277 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5279 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5280 int vector = exit_qualification & 0xff;
5282 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5283 kvm_apic_set_eoi_accelerated(vcpu, vector);
5287 static int handle_apic_write(struct kvm_vcpu *vcpu)
5289 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5290 u32 offset = exit_qualification & 0xfff;
5292 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5293 kvm_apic_write_nodecode(vcpu, offset);
5297 static int handle_task_switch(struct kvm_vcpu *vcpu)
5299 struct vcpu_vmx *vmx = to_vmx(vcpu);
5300 unsigned long exit_qualification;
5301 bool has_error_code = false;
5304 int reason, type, idt_v, idt_index;
5306 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5307 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5308 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5310 exit_qualification = vmx_get_exit_qual(vcpu);
5312 reason = (u32)exit_qualification >> 30;
5313 if (reason == TASK_SWITCH_GATE && idt_v) {
5315 case INTR_TYPE_NMI_INTR:
5316 vcpu->arch.nmi_injected = false;
5317 vmx_set_nmi_mask(vcpu, true);
5319 case INTR_TYPE_EXT_INTR:
5320 case INTR_TYPE_SOFT_INTR:
5321 kvm_clear_interrupt_queue(vcpu);
5323 case INTR_TYPE_HARD_EXCEPTION:
5324 if (vmx->idt_vectoring_info &
5325 VECTORING_INFO_DELIVER_CODE_MASK) {
5326 has_error_code = true;
5328 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5331 case INTR_TYPE_SOFT_EXCEPTION:
5332 kvm_clear_exception_queue(vcpu);
5338 tss_selector = exit_qualification;
5340 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5341 type != INTR_TYPE_EXT_INTR &&
5342 type != INTR_TYPE_NMI_INTR))
5343 WARN_ON(!skip_emulated_instruction(vcpu));
5346 * TODO: What about debug traps on tss switch?
5347 * Are we supposed to inject them and update dr6?
5349 return kvm_task_switch(vcpu, tss_selector,
5350 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5351 reason, has_error_code, error_code);
5354 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5356 unsigned long exit_qualification;
5360 exit_qualification = vmx_get_exit_qual(vcpu);
5363 * EPT violation happened while executing iret from NMI,
5364 * "blocked by NMI" bit has to be set before next VM entry.
5365 * There are errata that may cause this bit to not be set:
5368 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5370 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5371 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5373 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5374 trace_kvm_page_fault(gpa, exit_qualification);
5376 /* Is it a read fault? */
5377 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5378 ? PFERR_USER_MASK : 0;
5379 /* Is it a write fault? */
5380 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5381 ? PFERR_WRITE_MASK : 0;
5382 /* Is it a fetch fault? */
5383 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5384 ? PFERR_FETCH_MASK : 0;
5385 /* ept page table entry is present? */
5386 error_code |= (exit_qualification &
5387 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5388 EPT_VIOLATION_EXECUTABLE))
5389 ? PFERR_PRESENT_MASK : 0;
5391 error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
5392 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5394 vcpu->arch.exit_qualification = exit_qualification;
5397 * Check that the GPA doesn't exceed physical memory limits, as that is
5398 * a guest page fault. We have to emulate the instruction here, because
5399 * if the illegal address is that of a paging structure, then
5400 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5401 * would also use advanced VM-exit information for EPT violations to
5402 * reconstruct the page fault error code.
5404 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5405 return kvm_emulate_instruction(vcpu, 0);
5407 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5410 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5414 if (!vmx_can_emulate_instruction(vcpu, NULL, 0))
5418 * A nested guest cannot optimize MMIO vmexits, because we have an
5419 * nGPA here instead of the required GPA.
5421 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5422 if (!is_guest_mode(vcpu) &&
5423 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5424 trace_kvm_fast_mmio(gpa);
5425 return kvm_skip_emulated_instruction(vcpu);
5428 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5431 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5433 WARN_ON_ONCE(!enable_vnmi);
5434 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5435 ++vcpu->stat.nmi_window_exits;
5436 kvm_make_request(KVM_REQ_EVENT, vcpu);
5441 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5443 struct vcpu_vmx *vmx = to_vmx(vcpu);
5444 bool intr_window_requested;
5445 unsigned count = 130;
5447 intr_window_requested = exec_controls_get(vmx) &
5448 CPU_BASED_INTR_WINDOW_EXITING;
5450 while (vmx->emulation_required && count-- != 0) {
5451 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5452 return handle_interrupt_window(&vmx->vcpu);
5454 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5457 if (!kvm_emulate_instruction(vcpu, 0))
5460 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5461 vcpu->arch.exception.pending) {
5462 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5463 vcpu->run->internal.suberror =
5464 KVM_INTERNAL_ERROR_EMULATION;
5465 vcpu->run->internal.ndata = 0;
5469 if (vcpu->arch.halt_request) {
5470 vcpu->arch.halt_request = 0;
5471 return kvm_vcpu_halt(vcpu);
5475 * Note, return 1 and not 0, vcpu_run() will invoke
5476 * xfer_to_guest_mode() which will create a proper return
5479 if (__xfer_to_guest_mode_work_pending())
5486 static void grow_ple_window(struct kvm_vcpu *vcpu)
5488 struct vcpu_vmx *vmx = to_vmx(vcpu);
5489 unsigned int old = vmx->ple_window;
5491 vmx->ple_window = __grow_ple_window(old, ple_window,
5495 if (vmx->ple_window != old) {
5496 vmx->ple_window_dirty = true;
5497 trace_kvm_ple_window_update(vcpu->vcpu_id,
5498 vmx->ple_window, old);
5502 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5504 struct vcpu_vmx *vmx = to_vmx(vcpu);
5505 unsigned int old = vmx->ple_window;
5507 vmx->ple_window = __shrink_ple_window(old, ple_window,
5511 if (vmx->ple_window != old) {
5512 vmx->ple_window_dirty = true;
5513 trace_kvm_ple_window_update(vcpu->vcpu_id,
5514 vmx->ple_window, old);
5519 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5520 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5522 static int handle_pause(struct kvm_vcpu *vcpu)
5524 if (!kvm_pause_in_guest(vcpu->kvm))
5525 grow_ple_window(vcpu);
5528 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5529 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5530 * never set PAUSE_EXITING and just set PLE if supported,
5531 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5533 kvm_vcpu_on_spin(vcpu, true);
5534 return kvm_skip_emulated_instruction(vcpu);
5537 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5542 static int handle_invpcid(struct kvm_vcpu *vcpu)
5544 u32 vmx_instruction_info;
5552 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5553 kvm_queue_exception(vcpu, UD_VECTOR);
5557 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5558 type = kvm_register_read(vcpu, (vmx_instruction_info >> 28) & 0xf);
5561 kvm_inject_gp(vcpu, 0);
5565 /* According to the Intel instruction reference, the memory operand
5566 * is read even if it isn't needed (e.g., for type==all)
5568 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5569 vmx_instruction_info, false,
5570 sizeof(operand), &gva))
5573 return kvm_handle_invpcid(vcpu, type, gva);
5576 static int handle_pml_full(struct kvm_vcpu *vcpu)
5578 unsigned long exit_qualification;
5580 trace_kvm_pml_full(vcpu->vcpu_id);
5582 exit_qualification = vmx_get_exit_qual(vcpu);
5585 * PML buffer FULL happened while executing iret from NMI,
5586 * "blocked by NMI" bit has to be set before next VM entry.
5588 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5590 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5591 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5592 GUEST_INTR_STATE_NMI);
5595 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5596 * here.., and there's no userspace involvement needed for PML.
5601 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5603 struct vcpu_vmx *vmx = to_vmx(vcpu);
5605 if (!vmx->req_immediate_exit &&
5606 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5607 kvm_lapic_expired_hv_timer(vcpu);
5608 return EXIT_FASTPATH_REENTER_GUEST;
5611 return EXIT_FASTPATH_NONE;
5614 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5616 handle_fastpath_preemption_timer(vcpu);
5621 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5622 * are overwritten by nested_vmx_setup() when nested=1.
5624 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5626 kvm_queue_exception(vcpu, UD_VECTOR);
5630 #ifndef CONFIG_X86_SGX_KVM
5631 static int handle_encls(struct kvm_vcpu *vcpu)
5634 * SGX virtualization is disabled. There is no software enable bit for
5635 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
5636 * the guest from executing ENCLS (when SGX is supported by hardware).
5638 kvm_queue_exception(vcpu, UD_VECTOR);
5641 #endif /* CONFIG_X86_SGX_KVM */
5643 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
5645 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
5646 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
5651 * The exit handlers return 1 if the exit was handled fully and guest execution
5652 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5653 * to be done to userspace and return 0.
5655 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5656 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5657 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5658 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5659 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5660 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5661 [EXIT_REASON_CR_ACCESS] = handle_cr,
5662 [EXIT_REASON_DR_ACCESS] = handle_dr,
5663 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5664 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5665 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5666 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5667 [EXIT_REASON_HLT] = kvm_emulate_halt,
5668 [EXIT_REASON_INVD] = kvm_emulate_invd,
5669 [EXIT_REASON_INVLPG] = handle_invlpg,
5670 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
5671 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
5672 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5673 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5674 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5675 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5676 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5677 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5678 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5679 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5680 [EXIT_REASON_VMON] = handle_vmx_instruction,
5681 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5682 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5683 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5684 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5685 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
5686 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
5687 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5688 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5689 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5690 [EXIT_REASON_LDTR_TR] = handle_desc,
5691 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5692 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5693 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5694 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
5695 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5696 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
5697 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5698 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5699 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
5700 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
5701 [EXIT_REASON_PML_FULL] = handle_pml_full,
5702 [EXIT_REASON_INVPCID] = handle_invpcid,
5703 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5704 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5705 [EXIT_REASON_ENCLS] = handle_encls,
5706 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
5709 static const int kvm_vmx_max_exit_handlers =
5710 ARRAY_SIZE(kvm_vmx_exit_handlers);
5712 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2,
5713 u32 *intr_info, u32 *error_code)
5715 struct vcpu_vmx *vmx = to_vmx(vcpu);
5717 *info1 = vmx_get_exit_qual(vcpu);
5718 if (!(vmx->exit_reason.failed_vmentry)) {
5719 *info2 = vmx->idt_vectoring_info;
5720 *intr_info = vmx_get_intr_info(vcpu);
5721 if (is_exception_with_error_code(*intr_info))
5722 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5732 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5735 __free_page(vmx->pml_pg);
5740 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5742 struct vcpu_vmx *vmx = to_vmx(vcpu);
5746 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5748 /* Do nothing if PML buffer is empty */
5749 if (pml_idx == (PML_ENTITY_NUM - 1))
5752 /* PML index always points to next available PML buffer entity */
5753 if (pml_idx >= PML_ENTITY_NUM)
5758 pml_buf = page_address(vmx->pml_pg);
5759 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5762 gpa = pml_buf[pml_idx];
5763 WARN_ON(gpa & (PAGE_SIZE - 1));
5764 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5767 /* reset PML index */
5768 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5771 static void vmx_dump_sel(char *name, uint32_t sel)
5773 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5774 name, vmcs_read16(sel),
5775 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5776 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5777 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5780 static void vmx_dump_dtsel(char *name, uint32_t limit)
5782 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5783 name, vmcs_read32(limit),
5784 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5787 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
5790 struct vmx_msr_entry *e;
5792 pr_err("MSR %s:\n", name);
5793 for (i = 0, e = m->val; i < m->nr; ++i, ++e)
5794 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
5797 void dump_vmcs(struct kvm_vcpu *vcpu)
5799 struct vcpu_vmx *vmx = to_vmx(vcpu);
5800 u32 vmentry_ctl, vmexit_ctl;
5801 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5805 if (!dump_invalid_vmcs) {
5806 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5810 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5811 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5812 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5813 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5814 cr4 = vmcs_readl(GUEST_CR4);
5815 secondary_exec_control = 0;
5816 if (cpu_has_secondary_exec_ctrls())
5817 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5819 pr_err("*** Guest State ***\n");
5820 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5821 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5822 vmcs_readl(CR0_GUEST_HOST_MASK));
5823 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5824 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5825 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5826 if (cpu_has_vmx_ept()) {
5827 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5828 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5829 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5830 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5832 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5833 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5834 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5835 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5836 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5837 vmcs_readl(GUEST_SYSENTER_ESP),
5838 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5839 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5840 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5841 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5842 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5843 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5844 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5845 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5846 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5847 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5848 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5849 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
5850 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
5851 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
5852 else if (efer_slot >= 0)
5853 pr_err("EFER= 0x%016llx (autoload)\n",
5854 vmx->msr_autoload.guest.val[efer_slot].value);
5855 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
5856 pr_err("EFER= 0x%016llx (effective)\n",
5857 vcpu->arch.efer | (EFER_LMA | EFER_LME));
5859 pr_err("EFER= 0x%016llx (effective)\n",
5860 vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
5861 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
5862 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
5863 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5864 vmcs_read64(GUEST_IA32_DEBUGCTL),
5865 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5866 if (cpu_has_load_perf_global_ctrl() &&
5867 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5868 pr_err("PerfGlobCtl = 0x%016llx\n",
5869 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5870 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5871 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5872 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5873 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5874 vmcs_read32(GUEST_ACTIVITY_STATE));
5875 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5876 pr_err("InterruptStatus = %04x\n",
5877 vmcs_read16(GUEST_INTR_STATUS));
5878 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
5879 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
5880 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
5881 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
5883 pr_err("*** Host State ***\n");
5884 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5885 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5886 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5887 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5888 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5889 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5890 vmcs_read16(HOST_TR_SELECTOR));
5891 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5892 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5893 vmcs_readl(HOST_TR_BASE));
5894 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5895 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5896 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5897 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5898 vmcs_readl(HOST_CR4));
5899 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5900 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5901 vmcs_read32(HOST_IA32_SYSENTER_CS),
5902 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5903 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
5904 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
5905 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
5906 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
5907 if (cpu_has_load_perf_global_ctrl() &&
5908 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5909 pr_err("PerfGlobCtl = 0x%016llx\n",
5910 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5911 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
5912 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
5914 pr_err("*** Control State ***\n");
5915 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5916 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5917 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5918 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5919 vmcs_read32(EXCEPTION_BITMAP),
5920 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5921 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5922 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5923 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5924 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5925 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5926 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5927 vmcs_read32(VM_EXIT_INTR_INFO),
5928 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5929 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5930 pr_err(" reason=%08x qualification=%016lx\n",
5931 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5932 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5933 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5934 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5935 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5936 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5937 pr_err("TSC Multiplier = 0x%016llx\n",
5938 vmcs_read64(TSC_MULTIPLIER));
5939 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5940 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5941 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5942 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5944 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5945 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5946 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5947 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5949 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5950 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5951 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5952 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5953 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5954 pr_err("PLE Gap=%08x Window=%08x\n",
5955 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5956 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5957 pr_err("Virtual processor ID = 0x%04x\n",
5958 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5962 * The guest has exited. See if we can fix it or if we need userspace
5965 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
5967 struct vcpu_vmx *vmx = to_vmx(vcpu);
5968 union vmx_exit_reason exit_reason = vmx->exit_reason;
5969 u32 vectoring_info = vmx->idt_vectoring_info;
5970 u16 exit_handler_index;
5973 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5974 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5975 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5976 * mode as if vcpus is in root mode, the PML buffer must has been
5977 * flushed already. Note, PML is never enabled in hardware while
5980 if (enable_pml && !is_guest_mode(vcpu))
5981 vmx_flush_pml_buffer(vcpu);
5984 * We should never reach this point with a pending nested VM-Enter, and
5985 * more specifically emulation of L2 due to invalid guest state (see
5986 * below) should never happen as that means we incorrectly allowed a
5987 * nested VM-Enter with an invalid vmcs12.
5989 WARN_ON_ONCE(vmx->nested.nested_run_pending);
5991 /* If guest state is invalid, start emulating */
5992 if (vmx->emulation_required)
5993 return handle_invalid_guest_state(vcpu);
5995 if (is_guest_mode(vcpu)) {
5997 * PML is never enabled when running L2, bail immediately if a
5998 * PML full exit occurs as something is horribly wrong.
6000 if (exit_reason.basic == EXIT_REASON_PML_FULL)
6001 goto unexpected_vmexit;
6004 * The host physical addresses of some pages of guest memory
6005 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6006 * Page). The CPU may write to these pages via their host
6007 * physical address while L2 is running, bypassing any
6008 * address-translation-based dirty tracking (e.g. EPT write
6011 * Mark them dirty on every exit from L2 to prevent them from
6012 * getting out of sync with dirty tracking.
6014 nested_mark_vmcs12_pages_dirty(vcpu);
6016 if (nested_vmx_reflect_vmexit(vcpu))
6020 if (exit_reason.failed_vmentry) {
6022 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6023 vcpu->run->fail_entry.hardware_entry_failure_reason
6025 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6029 if (unlikely(vmx->fail)) {
6031 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6032 vcpu->run->fail_entry.hardware_entry_failure_reason
6033 = vmcs_read32(VM_INSTRUCTION_ERROR);
6034 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6040 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6041 * delivery event since it indicates guest is accessing MMIO.
6042 * The vm-exit can be triggered again after return to guest that
6043 * will cause infinite loop.
6045 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6046 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6047 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6048 exit_reason.basic != EXIT_REASON_PML_FULL &&
6049 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6050 exit_reason.basic != EXIT_REASON_TASK_SWITCH)) {
6053 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6054 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6055 vcpu->run->internal.data[0] = vectoring_info;
6056 vcpu->run->internal.data[1] = exit_reason.full;
6057 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6058 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6059 vcpu->run->internal.data[ndata++] =
6060 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6062 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6063 vcpu->run->internal.ndata = ndata;
6067 if (unlikely(!enable_vnmi &&
6068 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6069 if (!vmx_interrupt_blocked(vcpu)) {
6070 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6071 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6072 vcpu->arch.nmi_pending) {
6074 * This CPU don't support us in finding the end of an
6075 * NMI-blocked window if the guest runs with IRQs
6076 * disabled. So we pull the trigger after 1 s of
6077 * futile waiting, but inform the user about this.
6079 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6080 "state on VCPU %d after 1 s timeout\n",
6081 __func__, vcpu->vcpu_id);
6082 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6086 if (exit_fastpath != EXIT_FASTPATH_NONE)
6089 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6090 goto unexpected_vmexit;
6091 #ifdef CONFIG_RETPOLINE
6092 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6093 return kvm_emulate_wrmsr(vcpu);
6094 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6095 return handle_preemption_timer(vcpu);
6096 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6097 return handle_interrupt_window(vcpu);
6098 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6099 return handle_external_interrupt(vcpu);
6100 else if (exit_reason.basic == EXIT_REASON_HLT)
6101 return kvm_emulate_halt(vcpu);
6102 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6103 return handle_ept_misconfig(vcpu);
6106 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6107 kvm_vmx_max_exit_handlers);
6108 if (!kvm_vmx_exit_handlers[exit_handler_index])
6109 goto unexpected_vmexit;
6111 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6114 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6117 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6118 vcpu->run->internal.suberror =
6119 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6120 vcpu->run->internal.ndata = 2;
6121 vcpu->run->internal.data[0] = exit_reason.full;
6122 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6126 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6128 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6131 * Even when current exit reason is handled by KVM internally, we
6132 * still need to exit to user space when bus lock detected to inform
6133 * that there is a bus lock in guest.
6135 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6137 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6139 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6146 * Software based L1D cache flush which is used when microcode providing
6147 * the cache control MSR is not loaded.
6149 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6150 * flush it is required to read in 64 KiB because the replacement algorithm
6151 * is not exactly LRU. This could be sized at runtime via topology
6152 * information but as all relevant affected CPUs have 32KiB L1D cache size
6153 * there is no point in doing so.
6155 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6157 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6160 * This code is only executed when the the flush mode is 'cond' or
6163 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6167 * Clear the per-vcpu flush bit, it gets set again
6168 * either from vcpu_run() or from one of the unsafe
6171 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6172 vcpu->arch.l1tf_flush_l1d = false;
6175 * Clear the per-cpu flush bit, it gets set again from
6176 * the interrupt handlers.
6178 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6179 kvm_clear_cpu_l1tf_flush_l1d();
6185 vcpu->stat.l1d_flush++;
6187 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6188 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6193 /* First ensure the pages are in the TLB */
6194 "xorl %%eax, %%eax\n"
6195 ".Lpopulate_tlb:\n\t"
6196 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6197 "addl $4096, %%eax\n\t"
6198 "cmpl %%eax, %[size]\n\t"
6199 "jne .Lpopulate_tlb\n\t"
6200 "xorl %%eax, %%eax\n\t"
6202 /* Now fill the cache */
6203 "xorl %%eax, %%eax\n"
6205 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6206 "addl $64, %%eax\n\t"
6207 "cmpl %%eax, %[size]\n\t"
6208 "jne .Lfill_cache\n\t"
6210 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6212 : "eax", "ebx", "ecx", "edx");
6215 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6217 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6220 if (is_guest_mode(vcpu) &&
6221 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6224 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6225 if (is_guest_mode(vcpu))
6226 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6228 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6231 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6233 struct vcpu_vmx *vmx = to_vmx(vcpu);
6234 u32 sec_exec_control;
6236 if (!lapic_in_kernel(vcpu))
6239 if (!flexpriority_enabled &&
6240 !cpu_has_vmx_virtualize_x2apic_mode())
6243 /* Postpone execution until vmcs01 is the current VMCS. */
6244 if (is_guest_mode(vcpu)) {
6245 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6249 sec_exec_control = secondary_exec_controls_get(vmx);
6250 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6251 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6253 switch (kvm_get_apic_mode(vcpu)) {
6254 case LAPIC_MODE_INVALID:
6255 WARN_ONCE(true, "Invalid local APIC state");
6256 case LAPIC_MODE_DISABLED:
6258 case LAPIC_MODE_XAPIC:
6259 if (flexpriority_enabled) {
6261 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6262 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6265 * Flush the TLB, reloading the APIC access page will
6266 * only do so if its physical address has changed, but
6267 * the guest may have inserted a non-APIC mapping into
6268 * the TLB while the APIC access page was disabled.
6270 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6273 case LAPIC_MODE_X2APIC:
6274 if (cpu_has_vmx_virtualize_x2apic_mode())
6276 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6279 secondary_exec_controls_set(vmx, sec_exec_control);
6281 vmx_update_msr_bitmap(vcpu);
6284 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6288 /* Defer reload until vmcs01 is the current VMCS. */
6289 if (is_guest_mode(vcpu)) {
6290 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6294 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6295 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6298 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6299 if (is_error_page(page))
6302 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6303 vmx_flush_tlb_current(vcpu);
6306 * Do not pin apic access page in memory, the MMU notifier
6307 * will call us again if it is migrated or swapped out.
6312 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6320 status = vmcs_read16(GUEST_INTR_STATUS);
6322 if (max_isr != old) {
6324 status |= max_isr << 8;
6325 vmcs_write16(GUEST_INTR_STATUS, status);
6329 static void vmx_set_rvi(int vector)
6337 status = vmcs_read16(GUEST_INTR_STATUS);
6338 old = (u8)status & 0xff;
6339 if ((u8)vector != old) {
6341 status |= (u8)vector;
6342 vmcs_write16(GUEST_INTR_STATUS, status);
6346 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6349 * When running L2, updating RVI is only relevant when
6350 * vmcs12 virtual-interrupt-delivery enabled.
6351 * However, it can be enabled only when L1 also
6352 * intercepts external-interrupts and in that case
6353 * we should not update vmcs02 RVI but instead intercept
6354 * interrupt. Therefore, do nothing when running L2.
6356 if (!is_guest_mode(vcpu))
6357 vmx_set_rvi(max_irr);
6360 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6362 struct vcpu_vmx *vmx = to_vmx(vcpu);
6364 bool max_irr_updated;
6366 WARN_ON(!vcpu->arch.apicv_active);
6367 if (pi_test_on(&vmx->pi_desc)) {
6368 pi_clear_on(&vmx->pi_desc);
6370 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6371 * But on x86 this is just a compiler barrier anyway.
6373 smp_mb__after_atomic();
6375 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6378 * If we are running L2 and L1 has a new pending interrupt
6379 * which can be injected, we should re-evaluate
6380 * what should be done with this new L1 interrupt.
6381 * If L1 intercepts external-interrupts, we should
6382 * exit from L2 to L1. Otherwise, interrupt should be
6383 * delivered directly to L2.
6385 if (is_guest_mode(vcpu) && max_irr_updated) {
6386 if (nested_exit_on_intr(vcpu))
6387 kvm_vcpu_exiting_guest_mode(vcpu);
6389 kvm_make_request(KVM_REQ_EVENT, vcpu);
6392 max_irr = kvm_lapic_find_highest_irr(vcpu);
6394 vmx_hwapic_irr_update(vcpu, max_irr);
6398 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6400 if (!kvm_vcpu_apicv_active(vcpu))
6403 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6404 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6405 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6406 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6409 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6411 struct vcpu_vmx *vmx = to_vmx(vcpu);
6413 pi_clear_on(&vmx->pi_desc);
6414 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6417 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6419 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu,
6420 unsigned long entry)
6422 kvm_before_interrupt(vcpu);
6423 vmx_do_interrupt_nmi_irqoff(entry);
6424 kvm_after_interrupt(vcpu);
6427 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6429 const unsigned long nmi_entry = (unsigned long)asm_exc_nmi_noist;
6430 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6432 /* if exit due to PF check for async PF */
6433 if (is_page_fault(intr_info))
6434 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6435 /* Handle machine checks before interrupts are enabled */
6436 else if (is_machine_check(intr_info))
6437 kvm_machine_check();
6438 /* We need to handle NMIs before interrupts are enabled */
6439 else if (is_nmi(intr_info))
6440 handle_interrupt_nmi_irqoff(&vmx->vcpu, nmi_entry);
6443 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6445 u32 intr_info = vmx_get_intr_info(vcpu);
6446 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6447 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6449 if (WARN_ONCE(!is_external_intr(intr_info),
6450 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6453 handle_interrupt_nmi_irqoff(vcpu, gate_offset(desc));
6456 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6458 struct vcpu_vmx *vmx = to_vmx(vcpu);
6460 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6461 handle_external_interrupt_irqoff(vcpu);
6462 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
6463 handle_exception_nmi_irqoff(vmx);
6467 * The kvm parameter can be NULL (module initialization, or invocation before
6468 * VM creation). Be sure to check the kvm parameter before using it.
6470 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
6473 case MSR_IA32_SMBASE:
6475 * We cannot do SMM unless we can run the guest in big
6478 return enable_unrestricted_guest || emulate_invalid_guest_state;
6479 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6481 case MSR_AMD64_VIRT_SPEC_CTRL:
6482 /* This is AMD only. */
6489 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6494 bool idtv_info_valid;
6496 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6499 if (vmx->loaded_vmcs->nmi_known_unmasked)
6502 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6503 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6504 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6506 * SDM 3: 27.7.1.2 (September 2008)
6507 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6508 * a guest IRET fault.
6509 * SDM 3: 23.2.2 (September 2008)
6510 * Bit 12 is undefined in any of the following cases:
6511 * If the VM exit sets the valid bit in the IDT-vectoring
6512 * information field.
6513 * If the VM exit is due to a double fault.
6515 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6516 vector != DF_VECTOR && !idtv_info_valid)
6517 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6518 GUEST_INTR_STATE_NMI);
6520 vmx->loaded_vmcs->nmi_known_unmasked =
6521 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6522 & GUEST_INTR_STATE_NMI);
6523 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6524 vmx->loaded_vmcs->vnmi_blocked_time +=
6525 ktime_to_ns(ktime_sub(ktime_get(),
6526 vmx->loaded_vmcs->entry_time));
6529 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6530 u32 idt_vectoring_info,
6531 int instr_len_field,
6532 int error_code_field)
6536 bool idtv_info_valid;
6538 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6540 vcpu->arch.nmi_injected = false;
6541 kvm_clear_exception_queue(vcpu);
6542 kvm_clear_interrupt_queue(vcpu);
6544 if (!idtv_info_valid)
6547 kvm_make_request(KVM_REQ_EVENT, vcpu);
6549 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6550 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6553 case INTR_TYPE_NMI_INTR:
6554 vcpu->arch.nmi_injected = true;
6556 * SDM 3: 27.7.1.2 (September 2008)
6557 * Clear bit "block by NMI" before VM entry if a NMI
6560 vmx_set_nmi_mask(vcpu, false);
6562 case INTR_TYPE_SOFT_EXCEPTION:
6563 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6565 case INTR_TYPE_HARD_EXCEPTION:
6566 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6567 u32 err = vmcs_read32(error_code_field);
6568 kvm_requeue_exception_e(vcpu, vector, err);
6570 kvm_requeue_exception(vcpu, vector);
6572 case INTR_TYPE_SOFT_INTR:
6573 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6575 case INTR_TYPE_EXT_INTR:
6576 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6583 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6585 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6586 VM_EXIT_INSTRUCTION_LEN,
6587 IDT_VECTORING_ERROR_CODE);
6590 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6592 __vmx_complete_interrupts(vcpu,
6593 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6594 VM_ENTRY_INSTRUCTION_LEN,
6595 VM_ENTRY_EXCEPTION_ERROR_CODE);
6597 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6600 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6603 struct perf_guest_switch_msr *msrs;
6605 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
6606 msrs = perf_guest_get_msrs(&nr_msrs);
6610 for (i = 0; i < nr_msrs; i++)
6611 if (msrs[i].host == msrs[i].guest)
6612 clear_atomic_switch_msr(vmx, msrs[i].msr);
6614 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6615 msrs[i].host, false);
6618 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6620 struct vcpu_vmx *vmx = to_vmx(vcpu);
6624 if (vmx->req_immediate_exit) {
6625 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6626 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6627 } else if (vmx->hv_deadline_tsc != -1) {
6629 if (vmx->hv_deadline_tsc > tscl)
6630 /* set_hv_timer ensures the delta fits in 32-bits */
6631 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6632 cpu_preemption_timer_multi);
6636 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6637 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6638 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6639 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6640 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6644 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6646 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6647 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6648 vmcs_writel(HOST_RSP, host_rsp);
6652 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6654 switch (to_vmx(vcpu)->exit_reason.basic) {
6655 case EXIT_REASON_MSR_WRITE:
6656 return handle_fastpath_set_msr_irqoff(vcpu);
6657 case EXIT_REASON_PREEMPTION_TIMER:
6658 return handle_fastpath_preemption_timer(vcpu);
6660 return EXIT_FASTPATH_NONE;
6664 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6665 struct vcpu_vmx *vmx)
6668 * VMENTER enables interrupts (host state), but the kernel state is
6669 * interrupts disabled when this is invoked. Also tell RCU about
6670 * it. This is the same logic as for exit_to_user_mode().
6672 * This ensures that e.g. latency analysis on the host observes
6673 * guest mode as interrupt enabled.
6675 * guest_enter_irqoff() informs context tracking about the
6676 * transition to guest mode and if enabled adjusts RCU state
6679 instrumentation_begin();
6680 trace_hardirqs_on_prepare();
6681 lockdep_hardirqs_on_prepare(CALLER_ADDR0);
6682 instrumentation_end();
6684 guest_enter_irqoff();
6685 lockdep_hardirqs_on(CALLER_ADDR0);
6687 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6688 if (static_branch_unlikely(&vmx_l1d_should_flush))
6689 vmx_l1d_flush(vcpu);
6690 else if (static_branch_unlikely(&mds_user_clear))
6691 mds_clear_cpu_buffers();
6693 if (vcpu->arch.cr2 != native_read_cr2())
6694 native_write_cr2(vcpu->arch.cr2);
6696 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6697 vmx->loaded_vmcs->launched);
6699 vcpu->arch.cr2 = native_read_cr2();
6702 * VMEXIT disables interrupts (host state), but tracing and lockdep
6703 * have them in state 'on' as recorded before entering guest mode.
6704 * Same as enter_from_user_mode().
6706 * guest_exit_irqoff() restores host context and reinstates RCU if
6707 * enabled and required.
6709 * This needs to be done before the below as native_read_msr()
6710 * contains a tracepoint and x86_spec_ctrl_restore_host() calls
6711 * into world and some more.
6713 lockdep_hardirqs_off(CALLER_ADDR0);
6714 guest_exit_irqoff();
6716 instrumentation_begin();
6717 trace_hardirqs_off_finish();
6718 instrumentation_end();
6721 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6723 struct vcpu_vmx *vmx = to_vmx(vcpu);
6724 unsigned long cr3, cr4;
6726 /* Record the guest's net vcpu time for enforced NMI injections. */
6727 if (unlikely(!enable_vnmi &&
6728 vmx->loaded_vmcs->soft_vnmi_blocked))
6729 vmx->loaded_vmcs->entry_time = ktime_get();
6731 /* Don't enter VMX if guest state is invalid, let the exit handler
6732 start emulation until we arrive back to a valid state */
6733 if (vmx->emulation_required)
6734 return EXIT_FASTPATH_NONE;
6736 trace_kvm_entry(vcpu);
6738 if (vmx->ple_window_dirty) {
6739 vmx->ple_window_dirty = false;
6740 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6744 * We did this in prepare_switch_to_guest, because it needs to
6745 * be within srcu_read_lock.
6747 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6749 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6750 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6751 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6752 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6754 cr3 = __get_current_cr3_fast();
6755 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6756 vmcs_writel(HOST_CR3, cr3);
6757 vmx->loaded_vmcs->host_state.cr3 = cr3;
6760 cr4 = cr4_read_shadow();
6761 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6762 vmcs_writel(HOST_CR4, cr4);
6763 vmx->loaded_vmcs->host_state.cr4 = cr4;
6766 /* When single-stepping over STI and MOV SS, we must clear the
6767 * corresponding interruptibility bits in the guest state. Otherwise
6768 * vmentry fails as it then expects bit 14 (BS) in pending debug
6769 * exceptions being set, but that's not correct for the guest debugging
6771 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6772 vmx_set_interrupt_shadow(vcpu, 0);
6774 kvm_load_guest_xsave_state(vcpu);
6776 pt_guest_enter(vmx);
6778 atomic_switch_perf_msrs(vmx);
6779 if (intel_pmu_lbr_is_enabled(vcpu))
6780 vmx_passthrough_lbr_msrs(vcpu);
6782 if (enable_preemption_timer)
6783 vmx_update_hv_timer(vcpu);
6785 kvm_wait_lapic_expire(vcpu);
6788 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6789 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6790 * is no need to worry about the conditional branch over the wrmsr
6791 * being speculatively taken.
6793 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6795 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6796 vmx_vcpu_enter_exit(vcpu, vmx);
6799 * We do not use IBRS in the kernel. If this vCPU has used the
6800 * SPEC_CTRL MSR it may have left it on; save the value and
6801 * turn it off. This is much more efficient than blindly adding
6802 * it to the atomic save/restore list. Especially as the former
6803 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6805 * For non-nested case:
6806 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6810 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6813 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6814 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6816 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6818 /* All fields are clean at this point */
6819 if (static_branch_unlikely(&enable_evmcs)) {
6820 current_evmcs->hv_clean_fields |=
6821 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6823 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
6826 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6827 if (vmx->host_debugctlmsr)
6828 update_debugctlmsr(vmx->host_debugctlmsr);
6830 #ifndef CONFIG_X86_64
6832 * The sysexit path does not restore ds/es, so we must set them to
6833 * a reasonable value ourselves.
6835 * We can't defer this to vmx_prepare_switch_to_host() since that
6836 * function may be executed in interrupt context, which saves and
6837 * restore segments around it, nullifying its effect.
6839 loadsegment(ds, __USER_DS);
6840 loadsegment(es, __USER_DS);
6843 vmx_register_cache_reset(vcpu);
6847 kvm_load_host_xsave_state(vcpu);
6849 vmx->nested.nested_run_pending = 0;
6850 vmx->idt_vectoring_info = 0;
6852 if (unlikely(vmx->fail)) {
6853 vmx->exit_reason.full = 0xdead;
6854 return EXIT_FASTPATH_NONE;
6857 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
6858 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
6859 kvm_machine_check();
6861 if (likely(!vmx->exit_reason.failed_vmentry))
6862 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6864 trace_kvm_exit(vmx->exit_reason.full, vcpu, KVM_ISA_VMX);
6866 if (unlikely(vmx->exit_reason.failed_vmentry))
6867 return EXIT_FASTPATH_NONE;
6869 vmx->loaded_vmcs->launched = 1;
6871 vmx_recover_nmi_blocking(vmx);
6872 vmx_complete_interrupts(vmx);
6874 if (is_guest_mode(vcpu))
6875 return EXIT_FASTPATH_NONE;
6877 return vmx_exit_handlers_fastpath(vcpu);
6880 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6882 struct vcpu_vmx *vmx = to_vmx(vcpu);
6885 vmx_destroy_pml_buffer(vmx);
6886 free_vpid(vmx->vpid);
6887 nested_vmx_free_vcpu(vcpu);
6888 free_loaded_vmcs(vmx->loaded_vmcs);
6891 static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
6893 struct vcpu_vmx *vmx;
6896 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6901 vmx->vpid = allocate_vpid();
6904 * If PML is turned on, failure on enabling PML just results in failure
6905 * of creating the vcpu, therefore we can simplify PML logic (by
6906 * avoiding dealing with cases, such as enabling PML partially on vcpus
6907 * for the guest), etc.
6910 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6915 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
6917 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i) {
6918 u32 index = vmx_uret_msrs_list[i];
6919 u32 data_low, data_high;
6920 int j = vmx->nr_uret_msrs;
6922 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6924 if (wrmsr_safe(index, data_low, data_high) < 0)
6927 vmx->guest_uret_msrs[j].slot = i;
6928 vmx->guest_uret_msrs[j].data = 0;
6930 case MSR_IA32_TSX_CTRL:
6932 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID
6933 * interception. Keep the host value unchanged to avoid
6934 * changing CPUID bits under the host kernel's feet.
6936 * hle=0, rtm=0, tsx_ctrl=1 can be found with some
6937 * combinations of new kernel and old userspace. If
6938 * those guests run on a tsx=off host, do allow guests
6939 * to use TSX_CTRL, but do not change the value on the
6940 * host so that TSX remains always disabled.
6942 if (boot_cpu_has(X86_FEATURE_RTM))
6943 vmx->guest_uret_msrs[j].mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6945 vmx->guest_uret_msrs[j].mask = 0;
6948 vmx->guest_uret_msrs[j].mask = -1ull;
6951 ++vmx->nr_uret_msrs;
6954 err = alloc_loaded_vmcs(&vmx->vmcs01);
6958 /* The MSR bitmap starts with all ones */
6959 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6960 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6962 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
6963 #ifdef CONFIG_X86_64
6964 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
6965 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
6966 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6968 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6969 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6970 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6971 if (kvm_cstate_in_guest(vcpu->kvm)) {
6972 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
6973 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6974 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6975 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6977 vmx->msr_bitmap_mode = 0;
6979 vmx->loaded_vmcs = &vmx->vmcs01;
6981 vmx_vcpu_load(vcpu, cpu);
6986 if (cpu_need_virtualize_apic_accesses(vcpu)) {
6987 err = alloc_apic_access_page(vcpu->kvm);
6992 if (enable_ept && !enable_unrestricted_guest) {
6993 err = init_rmode_identity_map(vcpu->kvm);
6999 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
7001 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
7003 vcpu_setup_sgx_lepubkeyhash(vcpu);
7005 vmx->nested.posted_intr_nv = -1;
7006 vmx->nested.current_vmptr = -1ull;
7008 vcpu->arch.microcode_version = 0x100000000ULL;
7009 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
7012 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
7013 * or POSTED_INTR_WAKEUP_VECTOR.
7015 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
7016 vmx->pi_desc.sn = 1;
7018 #if IS_ENABLED(CONFIG_HYPERV)
7019 vmx->hv_root_ept = INVALID_PAGE;
7024 free_loaded_vmcs(vmx->loaded_vmcs);
7026 vmx_destroy_pml_buffer(vmx);
7028 free_vpid(vmx->vpid);
7032 #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"
7033 #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"
7035 static int vmx_vm_init(struct kvm *kvm)
7037 #if IS_ENABLED(CONFIG_HYPERV)
7038 spin_lock_init(&to_kvm_vmx(kvm)->hv_root_ept_lock);
7042 kvm->arch.pause_in_guest = true;
7044 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7045 switch (l1tf_mitigation) {
7046 case L1TF_MITIGATION_OFF:
7047 case L1TF_MITIGATION_FLUSH_NOWARN:
7048 /* 'I explicitly don't care' is set */
7050 case L1TF_MITIGATION_FLUSH:
7051 case L1TF_MITIGATION_FLUSH_NOSMT:
7052 case L1TF_MITIGATION_FULL:
7054 * Warn upon starting the first VM in a potentially
7055 * insecure environment.
7057 if (sched_smt_active())
7058 pr_warn_once(L1TF_MSG_SMT);
7059 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7060 pr_warn_once(L1TF_MSG_L1D);
7062 case L1TF_MITIGATION_FULL_FORCE:
7063 /* Flush is enforced */
7067 kvm_apicv_init(kvm, enable_apicv);
7071 static int __init vmx_check_processor_compat(void)
7073 struct vmcs_config vmcs_conf;
7074 struct vmx_capability vmx_cap;
7076 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7077 !this_cpu_has(X86_FEATURE_VMX)) {
7078 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7082 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7085 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
7086 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7087 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7088 smp_processor_id());
7094 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7099 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7100 * memory aliases with conflicting memory types and sometimes MCEs.
7101 * We have to be careful as to what are honored and when.
7103 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7104 * UC. The effective memory type is UC or WC depending on guest PAT.
7105 * This was historically the source of MCEs and we want to be
7108 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7109 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7110 * EPT memory type is set to WB. The effective memory type is forced
7113 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7114 * EPT memory type is used to emulate guest CD/MTRR.
7118 cache = MTRR_TYPE_UNCACHABLE;
7122 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7123 ipat = VMX_EPT_IPAT_BIT;
7124 cache = MTRR_TYPE_WRBACK;
7128 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7129 ipat = VMX_EPT_IPAT_BIT;
7130 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7131 cache = MTRR_TYPE_WRBACK;
7133 cache = MTRR_TYPE_UNCACHABLE;
7137 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
7140 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7143 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
7146 * These bits in the secondary execution controls field
7147 * are dynamic, the others are mostly based on the hypervisor
7148 * architecture and the guest's CPUID. Do not touch the
7152 SECONDARY_EXEC_SHADOW_VMCS |
7153 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7154 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7155 SECONDARY_EXEC_DESC;
7157 u32 new_ctl = vmx->secondary_exec_control;
7158 u32 cur_ctl = secondary_exec_controls_get(vmx);
7160 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7164 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7165 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7167 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7169 struct vcpu_vmx *vmx = to_vmx(vcpu);
7170 struct kvm_cpuid_entry2 *entry;
7172 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7173 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7175 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7176 if (entry && (entry->_reg & (_cpuid_mask))) \
7177 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7180 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7181 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7182 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7183 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7184 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7185 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7186 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7187 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7188 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7189 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7190 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7191 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7192 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7193 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7194 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7196 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7197 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7198 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7199 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7200 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7201 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7202 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7204 #undef cr4_fixed1_update
7207 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7209 struct vcpu_vmx *vmx = to_vmx(vcpu);
7211 if (kvm_mpx_supported()) {
7212 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7215 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7216 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7218 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7219 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7224 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7226 struct vcpu_vmx *vmx = to_vmx(vcpu);
7227 struct kvm_cpuid_entry2 *best = NULL;
7230 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7231 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7234 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7235 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7236 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7237 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7240 /* Get the number of configurable Address Ranges for filtering */
7241 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7242 PT_CAP_num_address_ranges);
7244 /* Initialize and clear the no dependency bits */
7245 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7246 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7249 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7250 * will inject an #GP
7252 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7253 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7256 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7257 * PSBFreq can be set
7259 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7260 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7261 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7264 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7265 * MTCFreq can be set
7267 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7268 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7269 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7271 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7272 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7273 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7276 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7277 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7278 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7280 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7281 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7282 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7284 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7285 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7286 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7288 /* unmask address range configure area */
7289 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7290 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7293 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7295 struct vcpu_vmx *vmx = to_vmx(vcpu);
7297 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7298 vcpu->arch.xsaves_enabled = false;
7300 if (cpu_has_secondary_exec_ctrls()) {
7301 vmx_compute_secondary_exec_control(vmx);
7302 vmcs_set_secondary_exec_control(vmx);
7305 if (nested_vmx_allowed(vcpu))
7306 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7307 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7308 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7310 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7311 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7312 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7314 if (nested_vmx_allowed(vcpu)) {
7315 nested_vmx_cr_fixed1_bits_update(vcpu);
7316 nested_vmx_entry_exit_ctls_update(vcpu);
7319 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7320 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7321 update_intel_pt_cfg(vcpu);
7323 if (boot_cpu_has(X86_FEATURE_RTM)) {
7324 struct vmx_uret_msr *msr;
7325 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7327 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7328 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7332 set_cr4_guest_host_mask(vmx);
7334 vmx_write_encls_bitmap(vcpu, NULL);
7335 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7336 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7338 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7340 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7341 vmx->msr_ia32_feature_control_valid_bits |=
7342 FEAT_CTL_SGX_LC_ENABLED;
7344 vmx->msr_ia32_feature_control_valid_bits &=
7345 ~FEAT_CTL_SGX_LC_ENABLED;
7347 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7348 vmx_update_exception_bitmap(vcpu);
7351 static __init void vmx_set_cpu_caps(void)
7357 kvm_cpu_cap_set(X86_FEATURE_VMX);
7360 if (kvm_mpx_supported())
7361 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7362 if (!cpu_has_vmx_invpcid())
7363 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7364 if (vmx_pt_mode_is_host_guest())
7365 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7368 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7369 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7370 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7371 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7374 if (vmx_umip_emulated())
7375 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7379 if (!cpu_has_vmx_xsaves())
7380 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7382 /* CPUID 0x80000001 */
7383 if (!cpu_has_vmx_rdtscp())
7384 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7386 if (cpu_has_vmx_waitpkg())
7387 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7390 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7392 to_vmx(vcpu)->req_immediate_exit = true;
7395 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7396 struct x86_instruction_info *info)
7398 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7399 unsigned short port;
7403 if (info->intercept == x86_intercept_in ||
7404 info->intercept == x86_intercept_ins) {
7405 port = info->src_val;
7406 size = info->dst_bytes;
7408 port = info->dst_val;
7409 size = info->src_bytes;
7413 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7414 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7417 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7419 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7420 intercept = nested_cpu_has(vmcs12,
7421 CPU_BASED_UNCOND_IO_EXITING);
7423 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7425 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7426 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7429 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7430 struct x86_instruction_info *info,
7431 enum x86_intercept_stage stage,
7432 struct x86_exception *exception)
7434 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7436 switch (info->intercept) {
7438 * RDPID causes #UD if disabled through secondary execution controls.
7439 * Because it is marked as EmulateOnUD, we need to intercept it here.
7441 case x86_intercept_rdtscp:
7442 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7443 exception->vector = UD_VECTOR;
7444 exception->error_code_valid = false;
7445 return X86EMUL_PROPAGATE_FAULT;
7449 case x86_intercept_in:
7450 case x86_intercept_ins:
7451 case x86_intercept_out:
7452 case x86_intercept_outs:
7453 return vmx_check_intercept_io(vcpu, info);
7455 case x86_intercept_lgdt:
7456 case x86_intercept_lidt:
7457 case x86_intercept_lldt:
7458 case x86_intercept_ltr:
7459 case x86_intercept_sgdt:
7460 case x86_intercept_sidt:
7461 case x86_intercept_sldt:
7462 case x86_intercept_str:
7463 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7464 return X86EMUL_CONTINUE;
7466 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7469 /* TODO: check more intercepts... */
7474 return X86EMUL_UNHANDLEABLE;
7477 #ifdef CONFIG_X86_64
7478 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7479 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7480 u64 divisor, u64 *result)
7482 u64 low = a << shift, high = a >> (64 - shift);
7484 /* To avoid the overflow on divq */
7485 if (high >= divisor)
7488 /* Low hold the result, high hold rem which is discarded */
7489 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7490 "rm" (divisor), "0" (low), "1" (high));
7496 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7499 struct vcpu_vmx *vmx;
7500 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7501 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7505 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7506 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7507 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7508 ktimer->timer_advance_ns);
7510 if (delta_tsc > lapic_timer_advance_cycles)
7511 delta_tsc -= lapic_timer_advance_cycles;
7515 /* Convert to host delta tsc if tsc scaling is enabled */
7516 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7517 delta_tsc && u64_shl_div_u64(delta_tsc,
7518 kvm_tsc_scaling_ratio_frac_bits,
7519 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7523 * If the delta tsc can't fit in the 32 bit after the multi shift,
7524 * we can't use the preemption timer.
7525 * It's possible that it fits on later vmentries, but checking
7526 * on every vmentry is costly so we just use an hrtimer.
7528 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7531 vmx->hv_deadline_tsc = tscl + delta_tsc;
7532 *expired = !delta_tsc;
7536 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7538 to_vmx(vcpu)->hv_deadline_tsc = -1;
7542 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7544 if (!kvm_pause_in_guest(vcpu->kvm))
7545 shrink_ple_window(vcpu);
7548 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
7550 struct vcpu_vmx *vmx = to_vmx(vcpu);
7552 if (is_guest_mode(vcpu)) {
7553 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
7558 * Note, cpu_dirty_logging_count can be changed concurrent with this
7559 * code, but in that case another update request will be made and so
7560 * the guest will never run with a stale PML value.
7562 if (vcpu->kvm->arch.cpu_dirty_logging_count)
7563 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7565 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7568 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7570 if (pi_pre_block(vcpu))
7573 if (kvm_lapic_hv_timer_in_use(vcpu))
7574 kvm_lapic_switch_to_sw_timer(vcpu);
7579 static void vmx_post_block(struct kvm_vcpu *vcpu)
7581 if (kvm_x86_ops.set_hv_timer)
7582 kvm_lapic_switch_to_hv_timer(vcpu);
7584 pi_post_block(vcpu);
7587 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7589 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7590 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7591 FEAT_CTL_LMCE_ENABLED;
7593 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7594 ~FEAT_CTL_LMCE_ENABLED;
7597 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7599 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7600 if (to_vmx(vcpu)->nested.nested_run_pending)
7602 return !is_smm(vcpu);
7605 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7607 struct vcpu_vmx *vmx = to_vmx(vcpu);
7609 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7610 if (vmx->nested.smm.guest_mode)
7611 nested_vmx_vmexit(vcpu, -1, 0, 0);
7613 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7614 vmx->nested.vmxon = false;
7615 vmx_clear_hlt(vcpu);
7619 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7621 struct vcpu_vmx *vmx = to_vmx(vcpu);
7624 if (vmx->nested.smm.vmxon) {
7625 vmx->nested.vmxon = true;
7626 vmx->nested.smm.vmxon = false;
7629 if (vmx->nested.smm.guest_mode) {
7630 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7634 vmx->nested.smm.guest_mode = false;
7639 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
7641 /* RSM will cause a vmexit anyway. */
7644 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7646 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
7649 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7651 if (is_guest_mode(vcpu)) {
7652 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7654 if (hrtimer_try_to_cancel(timer) == 1)
7655 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7659 static void hardware_unsetup(void)
7662 nested_vmx_hardware_unsetup();
7667 static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7669 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7670 BIT(APICV_INHIBIT_REASON_HYPERV);
7672 return supported & BIT(bit);
7675 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7676 .hardware_unsetup = hardware_unsetup,
7678 .hardware_enable = hardware_enable,
7679 .hardware_disable = hardware_disable,
7680 .cpu_has_accelerated_tpr = report_flexpriority,
7681 .has_emulated_msr = vmx_has_emulated_msr,
7683 .vm_size = sizeof(struct kvm_vmx),
7684 .vm_init = vmx_vm_init,
7686 .vcpu_create = vmx_create_vcpu,
7687 .vcpu_free = vmx_free_vcpu,
7688 .vcpu_reset = vmx_vcpu_reset,
7690 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7691 .vcpu_load = vmx_vcpu_load,
7692 .vcpu_put = vmx_vcpu_put,
7694 .update_exception_bitmap = vmx_update_exception_bitmap,
7695 .get_msr_feature = vmx_get_msr_feature,
7696 .get_msr = vmx_get_msr,
7697 .set_msr = vmx_set_msr,
7698 .get_segment_base = vmx_get_segment_base,
7699 .get_segment = vmx_get_segment,
7700 .set_segment = vmx_set_segment,
7701 .get_cpl = vmx_get_cpl,
7702 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7703 .set_cr0 = vmx_set_cr0,
7704 .is_valid_cr4 = vmx_is_valid_cr4,
7705 .set_cr4 = vmx_set_cr4,
7706 .set_efer = vmx_set_efer,
7707 .get_idt = vmx_get_idt,
7708 .set_idt = vmx_set_idt,
7709 .get_gdt = vmx_get_gdt,
7710 .set_gdt = vmx_set_gdt,
7711 .set_dr7 = vmx_set_dr7,
7712 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7713 .cache_reg = vmx_cache_reg,
7714 .get_rflags = vmx_get_rflags,
7715 .set_rflags = vmx_set_rflags,
7717 .tlb_flush_all = vmx_flush_tlb_all,
7718 .tlb_flush_current = vmx_flush_tlb_current,
7719 .tlb_flush_gva = vmx_flush_tlb_gva,
7720 .tlb_flush_guest = vmx_flush_tlb_guest,
7722 .run = vmx_vcpu_run,
7723 .handle_exit = vmx_handle_exit,
7724 .skip_emulated_instruction = vmx_skip_emulated_instruction,
7725 .update_emulated_instruction = vmx_update_emulated_instruction,
7726 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7727 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7728 .patch_hypercall = vmx_patch_hypercall,
7729 .set_irq = vmx_inject_irq,
7730 .set_nmi = vmx_inject_nmi,
7731 .queue_exception = vmx_queue_exception,
7732 .cancel_injection = vmx_cancel_injection,
7733 .interrupt_allowed = vmx_interrupt_allowed,
7734 .nmi_allowed = vmx_nmi_allowed,
7735 .get_nmi_mask = vmx_get_nmi_mask,
7736 .set_nmi_mask = vmx_set_nmi_mask,
7737 .enable_nmi_window = vmx_enable_nmi_window,
7738 .enable_irq_window = vmx_enable_irq_window,
7739 .update_cr8_intercept = vmx_update_cr8_intercept,
7740 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7741 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7742 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7743 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7744 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7745 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7746 .hwapic_irr_update = vmx_hwapic_irr_update,
7747 .hwapic_isr_update = vmx_hwapic_isr_update,
7748 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7749 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7750 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7751 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
7753 .set_tss_addr = vmx_set_tss_addr,
7754 .set_identity_map_addr = vmx_set_identity_map_addr,
7755 .get_mt_mask = vmx_get_mt_mask,
7757 .get_exit_info = vmx_get_exit_info,
7759 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
7761 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7763 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7765 .load_mmu_pgd = vmx_load_mmu_pgd,
7767 .check_intercept = vmx_check_intercept,
7768 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7770 .request_immediate_exit = vmx_request_immediate_exit,
7772 .sched_in = vmx_sched_in,
7774 .cpu_dirty_log_size = PML_ENTITY_NUM,
7775 .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
7777 .pre_block = vmx_pre_block,
7778 .post_block = vmx_post_block,
7780 .pmu_ops = &intel_pmu_ops,
7781 .nested_ops = &vmx_nested_ops,
7783 .update_pi_irte = pi_update_irte,
7785 #ifdef CONFIG_X86_64
7786 .set_hv_timer = vmx_set_hv_timer,
7787 .cancel_hv_timer = vmx_cancel_hv_timer,
7790 .setup_mce = vmx_setup_mce,
7792 .smi_allowed = vmx_smi_allowed,
7793 .pre_enter_smm = vmx_pre_enter_smm,
7794 .pre_leave_smm = vmx_pre_leave_smm,
7795 .enable_smi_window = vmx_enable_smi_window,
7797 .can_emulate_instruction = vmx_can_emulate_instruction,
7798 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7799 .migrate_timers = vmx_migrate_timers,
7801 .msr_filter_changed = vmx_msr_filter_changed,
7802 .complete_emulated_msr = kvm_complete_insn_gp,
7804 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
7807 static __init int hardware_setup(void)
7809 unsigned long host_bndcfgs;
7811 int r, i, ept_lpage_level;
7814 host_idt_base = dt.address;
7816 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
7817 kvm_define_user_return_msr(i, vmx_uret_msrs_list[i]);
7819 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7822 if (boot_cpu_has(X86_FEATURE_NX))
7823 kvm_enable_efer_bits(EFER_NX);
7825 if (boot_cpu_has(X86_FEATURE_MPX)) {
7826 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7827 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7830 if (!cpu_has_vmx_mpx())
7831 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
7832 XFEATURE_MASK_BNDCSR);
7834 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7835 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7838 if (!cpu_has_vmx_ept() ||
7839 !cpu_has_vmx_ept_4levels() ||
7840 !cpu_has_vmx_ept_mt_wb() ||
7841 !cpu_has_vmx_invept_global())
7844 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7845 enable_ept_ad_bits = 0;
7847 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7848 enable_unrestricted_guest = 0;
7850 if (!cpu_has_vmx_flexpriority())
7851 flexpriority_enabled = 0;
7853 if (!cpu_has_virtual_nmis())
7857 * set_apic_access_page_addr() is used to reload apic access
7858 * page upon invalidation. No need to do anything if not
7859 * using the APIC_ACCESS_ADDR VMCS field.
7861 if (!flexpriority_enabled)
7862 vmx_x86_ops.set_apic_access_page_addr = NULL;
7864 if (!cpu_has_vmx_tpr_shadow())
7865 vmx_x86_ops.update_cr8_intercept = NULL;
7867 #if IS_ENABLED(CONFIG_HYPERV)
7868 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7870 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
7871 vmx_x86_ops.tlb_remote_flush_with_range =
7872 hv_remote_flush_tlb_with_range;
7876 if (!cpu_has_vmx_ple()) {
7879 ple_window_grow = 0;
7881 ple_window_shrink = 0;
7884 if (!cpu_has_vmx_apicv()) {
7886 vmx_x86_ops.sync_pir_to_irr = NULL;
7889 if (cpu_has_vmx_tsc_scaling()) {
7890 kvm_has_tsc_control = true;
7891 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7892 kvm_tsc_scaling_ratio_frac_bits = 48;
7895 kvm_has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
7897 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7900 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
7901 cpu_has_vmx_ept_execute_only());
7904 ept_lpage_level = 0;
7905 else if (cpu_has_vmx_ept_1g_page())
7906 ept_lpage_level = PG_LEVEL_1G;
7907 else if (cpu_has_vmx_ept_2m_page())
7908 ept_lpage_level = PG_LEVEL_2M;
7910 ept_lpage_level = PG_LEVEL_4K;
7911 kvm_configure_mmu(enable_ept, vmx_get_max_tdp_level(), ept_lpage_level);
7914 * Only enable PML when hardware supports PML feature, and both EPT
7915 * and EPT A/D bit features are enabled -- PML depends on them to work.
7917 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7921 vmx_x86_ops.cpu_dirty_log_size = 0;
7923 if (!cpu_has_vmx_preemption_timer())
7924 enable_preemption_timer = false;
7926 if (enable_preemption_timer) {
7927 u64 use_timer_freq = 5000ULL * 1000 * 1000;
7930 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7931 cpu_preemption_timer_multi =
7932 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7935 use_timer_freq = (u64)tsc_khz * 1000;
7936 use_timer_freq >>= cpu_preemption_timer_multi;
7939 * KVM "disables" the preemption timer by setting it to its max
7940 * value. Don't use the timer if it might cause spurious exits
7941 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
7943 if (use_timer_freq > 0xffffffffu / 10)
7944 enable_preemption_timer = false;
7947 if (!enable_preemption_timer) {
7948 vmx_x86_ops.set_hv_timer = NULL;
7949 vmx_x86_ops.cancel_hv_timer = NULL;
7950 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
7953 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
7955 kvm_mce_cap_supported |= MCG_LMCE_P;
7957 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7959 if (!enable_ept || !cpu_has_vmx_intel_pt())
7960 pt_mode = PT_MODE_SYSTEM;
7962 setup_default_sgx_lepubkeyhash();
7965 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7966 vmx_capability.ept);
7968 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7975 r = alloc_kvm_area();
7977 nested_vmx_hardware_unsetup();
7981 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
7982 .cpu_has_kvm_support = cpu_has_kvm_support,
7983 .disabled_by_bios = vmx_disabled_by_bios,
7984 .check_processor_compatibility = vmx_check_processor_compat,
7985 .hardware_setup = hardware_setup,
7987 .runtime_ops = &vmx_x86_ops,
7990 static void vmx_cleanup_l1d_flush(void)
7992 if (vmx_l1d_flush_pages) {
7993 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7994 vmx_l1d_flush_pages = NULL;
7996 /* Restore state so sysfs ignores VMX */
7997 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8000 static void vmx_exit(void)
8002 #ifdef CONFIG_KEXEC_CORE
8003 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8009 #if IS_ENABLED(CONFIG_HYPERV)
8010 if (static_branch_unlikely(&enable_evmcs)) {
8012 struct hv_vp_assist_page *vp_ap;
8014 * Reset everything to support using non-enlightened VMCS
8015 * access later (e.g. when we reload the module with
8016 * enlightened_vmcs=0)
8018 for_each_online_cpu(cpu) {
8019 vp_ap = hv_get_vp_assist_page(cpu);
8024 vp_ap->nested_control.features.directhypercall = 0;
8025 vp_ap->current_nested_vmcs = 0;
8026 vp_ap->enlighten_vmentry = 0;
8029 static_branch_disable(&enable_evmcs);
8032 vmx_cleanup_l1d_flush();
8034 module_exit(vmx_exit);
8036 static int __init vmx_init(void)
8040 #if IS_ENABLED(CONFIG_HYPERV)
8042 * Enlightened VMCS usage should be recommended and the host needs
8043 * to support eVMCS v1 or above. We can also disable eVMCS support
8044 * with module parameter.
8046 if (enlightened_vmcs &&
8047 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8048 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8049 KVM_EVMCS_VERSION) {
8052 /* Check that we have assist pages on all online CPUs */
8053 for_each_online_cpu(cpu) {
8054 if (!hv_get_vp_assist_page(cpu)) {
8055 enlightened_vmcs = false;
8060 if (enlightened_vmcs) {
8061 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8062 static_branch_enable(&enable_evmcs);
8065 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8066 vmx_x86_ops.enable_direct_tlbflush
8067 = hv_enable_direct_tlbflush;
8070 enlightened_vmcs = false;
8074 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8075 __alignof__(struct vcpu_vmx), THIS_MODULE);
8080 * Must be called after kvm_init() so enable_ept is properly set
8081 * up. Hand the parameter mitigation value in which was stored in
8082 * the pre module init parser. If no parameter was given, it will
8083 * contain 'auto' which will be turned into the default 'cond'
8086 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8092 for_each_possible_cpu(cpu) {
8093 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8098 #ifdef CONFIG_KEXEC_CORE
8099 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8100 crash_vmclear_local_loaded_vmcss);
8102 vmx_check_vmcs12_offsets();
8105 * Shadow paging doesn't have a (further) performance penalty
8106 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8110 allow_smaller_maxphyaddr = true;
8114 module_init(vmx_init);