drm/panthor: Don't add write fences to the shared BOs
[drm/drm-misc.git] / arch / x86 / kvm / vmx / vmx.c
blob1a4438358c5e38ef09d5d306f026d887c14331cd
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
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.
11 * Authors:
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17 #include <linux/highmem.h>
18 #include <linux/hrtimer.h>
19 #include <linux/kernel.h>
20 #include <linux/kvm_host.h>
21 #include <linux/module.h>
22 #include <linux/moduleparam.h>
23 #include <linux/mod_devicetable.h>
24 #include <linux/mm.h>
25 #include <linux/objtool.h>
26 #include <linux/sched.h>
27 #include <linux/sched/smt.h>
28 #include <linux/slab.h>
29 #include <linux/tboot.h>
30 #include <linux/trace_events.h>
31 #include <linux/entry-kvm.h>
33 #include <asm/apic.h>
34 #include <asm/asm.h>
35 #include <asm/cpu.h>
36 #include <asm/cpu_device_id.h>
37 #include <asm/debugreg.h>
38 #include <asm/desc.h>
39 #include <asm/fpu/api.h>
40 #include <asm/fpu/xstate.h>
41 #include <asm/fred.h>
42 #include <asm/idtentry.h>
43 #include <asm/io.h>
44 #include <asm/irq_remapping.h>
45 #include <asm/reboot.h>
46 #include <asm/perf_event.h>
47 #include <asm/mmu_context.h>
48 #include <asm/mshyperv.h>
49 #include <asm/mwait.h>
50 #include <asm/spec-ctrl.h>
51 #include <asm/vmx.h>
53 #include <trace/events/ipi.h>
55 #include "capabilities.h"
56 #include "cpuid.h"
57 #include "hyperv.h"
58 #include "kvm_onhyperv.h"
59 #include "irq.h"
60 #include "kvm_cache_regs.h"
61 #include "lapic.h"
62 #include "mmu.h"
63 #include "nested.h"
64 #include "pmu.h"
65 #include "sgx.h"
66 #include "trace.h"
67 #include "vmcs.h"
68 #include "vmcs12.h"
69 #include "vmx.h"
70 #include "x86.h"
71 #include "x86_ops.h"
72 #include "smm.h"
73 #include "vmx_onhyperv.h"
74 #include "posted_intr.h"
76 MODULE_AUTHOR("Qumranet");
77 MODULE_DESCRIPTION("KVM support for VMX (Intel VT-x) extensions");
78 MODULE_LICENSE("GPL");
80 #ifdef MODULE
81 static const struct x86_cpu_id vmx_cpu_id[] = {
82 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
85 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
86 #endif
88 bool __read_mostly enable_vpid = 1;
89 module_param_named(vpid, enable_vpid, bool, 0444);
91 static bool __read_mostly enable_vnmi = 1;
92 module_param_named(vnmi, enable_vnmi, bool, 0444);
94 bool __read_mostly flexpriority_enabled = 1;
95 module_param_named(flexpriority, flexpriority_enabled, bool, 0444);
97 bool __read_mostly enable_ept = 1;
98 module_param_named(ept, enable_ept, bool, 0444);
100 bool __read_mostly enable_unrestricted_guest = 1;
101 module_param_named(unrestricted_guest,
102 enable_unrestricted_guest, bool, 0444);
104 bool __read_mostly enable_ept_ad_bits = 1;
105 module_param_named(eptad, enable_ept_ad_bits, bool, 0444);
107 static bool __read_mostly emulate_invalid_guest_state = true;
108 module_param(emulate_invalid_guest_state, bool, 0444);
110 static bool __read_mostly fasteoi = 1;
111 module_param(fasteoi, bool, 0444);
113 module_param(enable_apicv, bool, 0444);
115 bool __read_mostly enable_ipiv = true;
116 module_param(enable_ipiv, bool, 0444);
119 * If nested=1, nested virtualization is supported, i.e., guests may use
120 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
121 * use VMX instructions.
123 static bool __read_mostly nested = 1;
124 module_param(nested, bool, 0444);
126 bool __read_mostly enable_pml = 1;
127 module_param_named(pml, enable_pml, bool, 0444);
129 static bool __read_mostly error_on_inconsistent_vmcs_config = true;
130 module_param(error_on_inconsistent_vmcs_config, bool, 0444);
132 static bool __read_mostly dump_invalid_vmcs = 0;
133 module_param(dump_invalid_vmcs, bool, 0644);
135 #define MSR_BITMAP_MODE_X2APIC 1
136 #define MSR_BITMAP_MODE_X2APIC_APICV 2
138 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
140 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
141 static int __read_mostly cpu_preemption_timer_multi;
142 static bool __read_mostly enable_preemption_timer = 1;
143 #ifdef CONFIG_X86_64
144 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
145 #endif
147 extern bool __read_mostly allow_smaller_maxphyaddr;
148 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
150 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
151 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
152 #define KVM_VM_CR0_ALWAYS_ON \
153 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
155 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
156 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
157 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
159 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
161 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
162 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
163 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
164 RTIT_STATUS_BYTECNT))
167 * List of MSRs that can be directly passed to the guest.
168 * In addition to these x2apic, PT and LBR MSRs are handled specially.
170 static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
171 MSR_IA32_SPEC_CTRL,
172 MSR_IA32_PRED_CMD,
173 MSR_IA32_FLUSH_CMD,
174 MSR_IA32_TSC,
175 #ifdef CONFIG_X86_64
176 MSR_FS_BASE,
177 MSR_GS_BASE,
178 MSR_KERNEL_GS_BASE,
179 MSR_IA32_XFD,
180 MSR_IA32_XFD_ERR,
181 #endif
182 MSR_IA32_SYSENTER_CS,
183 MSR_IA32_SYSENTER_ESP,
184 MSR_IA32_SYSENTER_EIP,
185 MSR_CORE_C1_RES,
186 MSR_CORE_C3_RESIDENCY,
187 MSR_CORE_C6_RESIDENCY,
188 MSR_CORE_C7_RESIDENCY,
192 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
193 * ple_gap: upper bound on the amount of time between two successive
194 * executions of PAUSE in a loop. Also indicate if ple enabled.
195 * According to test, this time is usually smaller than 128 cycles.
196 * ple_window: upper bound on the amount of time a guest is allowed to execute
197 * in a PAUSE loop. Tests indicate that most spinlocks are held for
198 * less than 2^12 cycles
199 * Time is measured based on a counter that runs at the same rate as the TSC,
200 * refer SDM volume 3b section 21.6.13 & 22.1.3.
202 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
203 module_param(ple_gap, uint, 0444);
205 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
206 module_param(ple_window, uint, 0444);
208 /* Default doubles per-vcpu window every exit. */
209 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
210 module_param(ple_window_grow, uint, 0444);
212 /* Default resets per-vcpu window every exit to ple_window. */
213 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
214 module_param(ple_window_shrink, uint, 0444);
216 /* Default is to compute the maximum so we can never overflow. */
217 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
218 module_param(ple_window_max, uint, 0444);
220 /* Default is SYSTEM mode, 1 for host-guest mode */
221 int __read_mostly pt_mode = PT_MODE_SYSTEM;
222 module_param(pt_mode, int, S_IRUGO);
224 struct x86_pmu_lbr __ro_after_init vmx_lbr_caps;
226 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
227 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
228 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
230 /* Storage for pre module init parameter parsing */
231 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
233 static const struct {
234 const char *option;
235 bool for_parse;
236 } vmentry_l1d_param[] = {
237 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
238 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
239 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
240 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
241 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
242 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
245 #define L1D_CACHE_ORDER 4
246 static void *vmx_l1d_flush_pages;
248 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
250 struct page *page;
251 unsigned int i;
253 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
254 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
255 return 0;
258 if (!enable_ept) {
259 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
260 return 0;
263 if (kvm_host.arch_capabilities & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
264 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
265 return 0;
268 /* If set to auto use the default l1tf mitigation method */
269 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
270 switch (l1tf_mitigation) {
271 case L1TF_MITIGATION_OFF:
272 l1tf = VMENTER_L1D_FLUSH_NEVER;
273 break;
274 case L1TF_MITIGATION_FLUSH_NOWARN:
275 case L1TF_MITIGATION_FLUSH:
276 case L1TF_MITIGATION_FLUSH_NOSMT:
277 l1tf = VMENTER_L1D_FLUSH_COND;
278 break;
279 case L1TF_MITIGATION_FULL:
280 case L1TF_MITIGATION_FULL_FORCE:
281 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
282 break;
284 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
285 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
288 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
289 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
291 * This allocation for vmx_l1d_flush_pages is not tied to a VM
292 * lifetime and so should not be charged to a memcg.
294 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
295 if (!page)
296 return -ENOMEM;
297 vmx_l1d_flush_pages = page_address(page);
300 * Initialize each page with a different pattern in
301 * order to protect against KSM in the nested
302 * virtualization case.
304 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
305 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
306 PAGE_SIZE);
310 l1tf_vmx_mitigation = l1tf;
312 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
313 static_branch_enable(&vmx_l1d_should_flush);
314 else
315 static_branch_disable(&vmx_l1d_should_flush);
317 if (l1tf == VMENTER_L1D_FLUSH_COND)
318 static_branch_enable(&vmx_l1d_flush_cond);
319 else
320 static_branch_disable(&vmx_l1d_flush_cond);
321 return 0;
324 static int vmentry_l1d_flush_parse(const char *s)
326 unsigned int i;
328 if (s) {
329 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
330 if (vmentry_l1d_param[i].for_parse &&
331 sysfs_streq(s, vmentry_l1d_param[i].option))
332 return i;
335 return -EINVAL;
338 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
340 int l1tf, ret;
342 l1tf = vmentry_l1d_flush_parse(s);
343 if (l1tf < 0)
344 return l1tf;
346 if (!boot_cpu_has(X86_BUG_L1TF))
347 return 0;
350 * Has vmx_init() run already? If not then this is the pre init
351 * parameter parsing. In that case just store the value and let
352 * vmx_init() do the proper setup after enable_ept has been
353 * established.
355 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
356 vmentry_l1d_flush_param = l1tf;
357 return 0;
360 mutex_lock(&vmx_l1d_flush_mutex);
361 ret = vmx_setup_l1d_flush(l1tf);
362 mutex_unlock(&vmx_l1d_flush_mutex);
363 return ret;
366 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
368 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
369 return sysfs_emit(s, "???\n");
371 return sysfs_emit(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
374 static __always_inline void vmx_disable_fb_clear(struct vcpu_vmx *vmx)
376 u64 msr;
378 if (!vmx->disable_fb_clear)
379 return;
381 msr = __rdmsr(MSR_IA32_MCU_OPT_CTRL);
382 msr |= FB_CLEAR_DIS;
383 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, msr);
384 /* Cache the MSR value to avoid reading it later */
385 vmx->msr_ia32_mcu_opt_ctrl = msr;
388 static __always_inline void vmx_enable_fb_clear(struct vcpu_vmx *vmx)
390 if (!vmx->disable_fb_clear)
391 return;
393 vmx->msr_ia32_mcu_opt_ctrl &= ~FB_CLEAR_DIS;
394 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, vmx->msr_ia32_mcu_opt_ctrl);
397 static void vmx_update_fb_clear_dis(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx)
400 * Disable VERW's behavior of clearing CPU buffers for the guest if the
401 * CPU isn't affected by MDS/TAA, and the host hasn't forcefully enabled
402 * the mitigation. Disabling the clearing behavior provides a
403 * performance boost for guests that aren't aware that manually clearing
404 * CPU buffers is unnecessary, at the cost of MSR accesses on VM-Entry
405 * and VM-Exit.
407 vmx->disable_fb_clear = !cpu_feature_enabled(X86_FEATURE_CLEAR_CPU_BUF) &&
408 (kvm_host.arch_capabilities & ARCH_CAP_FB_CLEAR_CTRL) &&
409 !boot_cpu_has_bug(X86_BUG_MDS) &&
410 !boot_cpu_has_bug(X86_BUG_TAA);
413 * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS
414 * at VMEntry. Skip the MSR read/write when a guest has no use case to
415 * execute VERW.
417 if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) ||
418 ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) &&
419 (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) &&
420 (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) &&
421 (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) &&
422 (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO)))
423 vmx->disable_fb_clear = false;
426 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
427 .set = vmentry_l1d_flush_set,
428 .get = vmentry_l1d_flush_get,
430 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
432 static u32 vmx_segment_access_rights(struct kvm_segment *var);
434 void vmx_vmexit(void);
436 #define vmx_insn_failed(fmt...) \
437 do { \
438 WARN_ONCE(1, fmt); \
439 pr_warn_ratelimited(fmt); \
440 } while (0)
442 noinline void vmread_error(unsigned long field)
444 vmx_insn_failed("vmread failed: field=%lx\n", field);
447 #ifndef CONFIG_CC_HAS_ASM_GOTO_OUTPUT
448 noinstr void vmread_error_trampoline2(unsigned long field, bool fault)
450 if (fault) {
451 kvm_spurious_fault();
452 } else {
453 instrumentation_begin();
454 vmread_error(field);
455 instrumentation_end();
458 #endif
460 noinline void vmwrite_error(unsigned long field, unsigned long value)
462 vmx_insn_failed("vmwrite failed: field=%lx val=%lx err=%u\n",
463 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
466 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
468 vmx_insn_failed("vmclear failed: %p/%llx err=%u\n",
469 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
472 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
474 vmx_insn_failed("vmptrld failed: %p/%llx err=%u\n",
475 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
478 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
480 vmx_insn_failed("invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
481 ext, vpid, gva);
484 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
486 vmx_insn_failed("invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
487 ext, eptp, gpa);
490 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
491 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
493 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
494 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
496 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
498 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
499 static DEFINE_SPINLOCK(vmx_vpid_lock);
501 struct vmcs_config vmcs_config __ro_after_init;
502 struct vmx_capability vmx_capability __ro_after_init;
504 #define VMX_SEGMENT_FIELD(seg) \
505 [VCPU_SREG_##seg] = { \
506 .selector = GUEST_##seg##_SELECTOR, \
507 .base = GUEST_##seg##_BASE, \
508 .limit = GUEST_##seg##_LIMIT, \
509 .ar_bytes = GUEST_##seg##_AR_BYTES, \
512 static const struct kvm_vmx_segment_field {
513 unsigned selector;
514 unsigned base;
515 unsigned limit;
516 unsigned ar_bytes;
517 } kvm_vmx_segment_fields[] = {
518 VMX_SEGMENT_FIELD(CS),
519 VMX_SEGMENT_FIELD(DS),
520 VMX_SEGMENT_FIELD(ES),
521 VMX_SEGMENT_FIELD(FS),
522 VMX_SEGMENT_FIELD(GS),
523 VMX_SEGMENT_FIELD(SS),
524 VMX_SEGMENT_FIELD(TR),
525 VMX_SEGMENT_FIELD(LDTR),
529 static unsigned long host_idt_base;
531 #if IS_ENABLED(CONFIG_HYPERV)
532 static bool __read_mostly enlightened_vmcs = true;
533 module_param(enlightened_vmcs, bool, 0444);
535 static int hv_enable_l2_tlb_flush(struct kvm_vcpu *vcpu)
537 struct hv_enlightened_vmcs *evmcs;
538 hpa_t partition_assist_page = hv_get_partition_assist_page(vcpu);
540 if (partition_assist_page == INVALID_PAGE)
541 return -ENOMEM;
543 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
545 evmcs->partition_assist_page = partition_assist_page;
546 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
547 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
549 return 0;
552 static __init void hv_init_evmcs(void)
554 int cpu;
556 if (!enlightened_vmcs)
557 return;
560 * Enlightened VMCS usage should be recommended and the host needs
561 * to support eVMCS v1 or above.
563 if (ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
564 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
565 KVM_EVMCS_VERSION) {
567 /* Check that we have assist pages on all online CPUs */
568 for_each_online_cpu(cpu) {
569 if (!hv_get_vp_assist_page(cpu)) {
570 enlightened_vmcs = false;
571 break;
575 if (enlightened_vmcs) {
576 pr_info("Using Hyper-V Enlightened VMCS\n");
577 static_branch_enable(&__kvm_is_using_evmcs);
580 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
581 vt_x86_ops.enable_l2_tlb_flush
582 = hv_enable_l2_tlb_flush;
583 } else {
584 enlightened_vmcs = false;
588 static void hv_reset_evmcs(void)
590 struct hv_vp_assist_page *vp_ap;
592 if (!kvm_is_using_evmcs())
593 return;
596 * KVM should enable eVMCS if and only if all CPUs have a VP assist
597 * page, and should reject CPU onlining if eVMCS is enabled the CPU
598 * doesn't have a VP assist page allocated.
600 vp_ap = hv_get_vp_assist_page(smp_processor_id());
601 if (WARN_ON_ONCE(!vp_ap))
602 return;
605 * Reset everything to support using non-enlightened VMCS access later
606 * (e.g. when we reload the module with enlightened_vmcs=0)
608 vp_ap->nested_control.features.directhypercall = 0;
609 vp_ap->current_nested_vmcs = 0;
610 vp_ap->enlighten_vmentry = 0;
613 #else /* IS_ENABLED(CONFIG_HYPERV) */
614 static void hv_init_evmcs(void) {}
615 static void hv_reset_evmcs(void) {}
616 #endif /* IS_ENABLED(CONFIG_HYPERV) */
619 * Comment's format: document - errata name - stepping - processor name.
620 * Refer from
621 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
623 static u32 vmx_preemption_cpu_tfms[] = {
624 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
625 0x000206E6,
626 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
627 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
628 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
629 0x00020652,
630 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
631 0x00020655,
632 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
633 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
635 * 320767.pdf - AAP86 - B1 -
636 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
638 0x000106E5,
639 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
640 0x000106A0,
641 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
642 0x000106A1,
643 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
644 0x000106A4,
645 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
646 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
647 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
648 0x000106A5,
649 /* Xeon E3-1220 V2 */
650 0x000306A8,
653 static inline bool cpu_has_broken_vmx_preemption_timer(void)
655 u32 eax = cpuid_eax(0x00000001), i;
657 /* Clear the reserved bits */
658 eax &= ~(0x3U << 14 | 0xfU << 28);
659 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
660 if (eax == vmx_preemption_cpu_tfms[i])
661 return true;
663 return false;
666 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
668 return flexpriority_enabled && lapic_in_kernel(vcpu);
671 static int vmx_get_passthrough_msr_slot(u32 msr)
673 int i;
675 switch (msr) {
676 case 0x800 ... 0x8ff:
677 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
678 return -ENOENT;
679 case MSR_IA32_RTIT_STATUS:
680 case MSR_IA32_RTIT_OUTPUT_BASE:
681 case MSR_IA32_RTIT_OUTPUT_MASK:
682 case MSR_IA32_RTIT_CR3_MATCH:
683 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
684 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
685 case MSR_LBR_SELECT:
686 case MSR_LBR_TOS:
687 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
688 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
689 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
690 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
691 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
692 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
693 return -ENOENT;
696 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
697 if (vmx_possible_passthrough_msrs[i] == msr)
698 return i;
701 WARN(1, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
702 return -ENOENT;
705 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
707 int i;
709 i = kvm_find_user_return_msr(msr);
710 if (i >= 0)
711 return &vmx->guest_uret_msrs[i];
712 return NULL;
715 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
716 struct vmx_uret_msr *msr, u64 data)
718 unsigned int slot = msr - vmx->guest_uret_msrs;
719 int ret = 0;
721 if (msr->load_into_hardware) {
722 preempt_disable();
723 ret = kvm_set_user_return_msr(slot, data, msr->mask);
724 preempt_enable();
726 if (!ret)
727 msr->data = data;
728 return ret;
732 * Disable VMX and clear CR4.VMXE (even if VMXOFF faults)
734 * Note, VMXOFF causes a #UD if the CPU is !post-VMXON, but it's impossible to
735 * atomically track post-VMXON state, e.g. this may be called in NMI context.
736 * Eat all faults as all other faults on VMXOFF faults are mode related, i.e.
737 * faults are guaranteed to be due to the !post-VMXON check unless the CPU is
738 * magically in RM, VM86, compat mode, or at CPL>0.
740 static int kvm_cpu_vmxoff(void)
742 asm goto("1: vmxoff\n\t"
743 _ASM_EXTABLE(1b, %l[fault])
744 ::: "cc", "memory" : fault);
746 cr4_clear_bits(X86_CR4_VMXE);
747 return 0;
749 fault:
750 cr4_clear_bits(X86_CR4_VMXE);
751 return -EIO;
754 void vmx_emergency_disable_virtualization_cpu(void)
756 int cpu = raw_smp_processor_id();
757 struct loaded_vmcs *v;
759 kvm_rebooting = true;
762 * Note, CR4.VMXE can be _cleared_ in NMI context, but it can only be
763 * set in task context. If this races with VMX is disabled by an NMI,
764 * VMCLEAR and VMXOFF may #UD, but KVM will eat those faults due to
765 * kvm_rebooting set.
767 if (!(__read_cr4() & X86_CR4_VMXE))
768 return;
770 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
771 loaded_vmcss_on_cpu_link)
772 vmcs_clear(v->vmcs);
774 kvm_cpu_vmxoff();
777 static void __loaded_vmcs_clear(void *arg)
779 struct loaded_vmcs *loaded_vmcs = arg;
780 int cpu = raw_smp_processor_id();
782 if (loaded_vmcs->cpu != cpu)
783 return; /* vcpu migration can race with cpu offline */
784 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
785 per_cpu(current_vmcs, cpu) = NULL;
787 vmcs_clear(loaded_vmcs->vmcs);
788 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
789 vmcs_clear(loaded_vmcs->shadow_vmcs);
791 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
794 * Ensure all writes to loaded_vmcs, including deleting it from its
795 * current percpu list, complete before setting loaded_vmcs->cpu to
796 * -1, otherwise a different cpu can see loaded_vmcs->cpu == -1 first
797 * and add loaded_vmcs to its percpu list before it's deleted from this
798 * cpu's list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
800 smp_wmb();
802 loaded_vmcs->cpu = -1;
803 loaded_vmcs->launched = 0;
806 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
808 int cpu = loaded_vmcs->cpu;
810 if (cpu != -1)
811 smp_call_function_single(cpu,
812 __loaded_vmcs_clear, loaded_vmcs, 1);
815 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
816 unsigned field)
818 bool ret;
819 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
821 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
822 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
823 vmx->segment_cache.bitmask = 0;
825 ret = vmx->segment_cache.bitmask & mask;
826 vmx->segment_cache.bitmask |= mask;
827 return ret;
830 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
832 u16 *p = &vmx->segment_cache.seg[seg].selector;
834 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
835 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
836 return *p;
839 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
841 ulong *p = &vmx->segment_cache.seg[seg].base;
843 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
844 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
845 return *p;
848 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
850 u32 *p = &vmx->segment_cache.seg[seg].limit;
852 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
853 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
854 return *p;
857 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
859 u32 *p = &vmx->segment_cache.seg[seg].ar;
861 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
862 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
863 return *p;
866 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
868 u32 eb;
870 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
871 (1u << DB_VECTOR) | (1u << AC_VECTOR);
873 * #VE isn't used for VMX. To test against unexpected changes
874 * related to #VE for VMX, intercept unexpected #VE and warn on it.
876 if (IS_ENABLED(CONFIG_KVM_INTEL_PROVE_VE))
877 eb |= 1u << VE_VECTOR;
879 * Guest access to VMware backdoor ports could legitimately
880 * trigger #GP because of TSS I/O permission bitmap.
881 * We intercept those #GP and allow access to them anyway
882 * as VMware does.
884 if (enable_vmware_backdoor)
885 eb |= (1u << GP_VECTOR);
886 if ((vcpu->guest_debug &
887 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
888 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
889 eb |= 1u << BP_VECTOR;
890 if (to_vmx(vcpu)->rmode.vm86_active)
891 eb = ~0;
892 if (!vmx_need_pf_intercept(vcpu))
893 eb &= ~(1u << PF_VECTOR);
895 /* When we are running a nested L2 guest and L1 specified for it a
896 * certain exception bitmap, we must trap the same exceptions and pass
897 * them to L1. When running L2, we will only handle the exceptions
898 * specified above if L1 did not want them.
900 if (is_guest_mode(vcpu))
901 eb |= get_vmcs12(vcpu)->exception_bitmap;
902 else {
903 int mask = 0, match = 0;
905 if (enable_ept && (eb & (1u << PF_VECTOR))) {
907 * If EPT is enabled, #PF is currently only intercepted
908 * if MAXPHYADDR is smaller on the guest than on the
909 * host. In that case we only care about present,
910 * non-reserved faults. For vmcs02, however, PFEC_MASK
911 * and PFEC_MATCH are set in prepare_vmcs02_rare.
913 mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK;
914 match = PFERR_PRESENT_MASK;
916 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
917 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match);
921 * Disabling xfd interception indicates that dynamic xfeatures
922 * might be used in the guest. Always trap #NM in this case
923 * to save guest xfd_err timely.
925 if (vcpu->arch.xfd_no_write_intercept)
926 eb |= (1u << NM_VECTOR);
928 vmcs_write32(EXCEPTION_BITMAP, eb);
932 * Check if MSR is intercepted for currently loaded MSR bitmap.
934 static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr)
936 if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS))
937 return true;
939 return vmx_test_msr_bitmap_write(vmx->loaded_vmcs->msr_bitmap, msr);
942 unsigned int __vmx_vcpu_run_flags(struct vcpu_vmx *vmx)
944 unsigned int flags = 0;
946 if (vmx->loaded_vmcs->launched)
947 flags |= VMX_RUN_VMRESUME;
950 * If writes to the SPEC_CTRL MSR aren't intercepted, the guest is free
951 * to change it directly without causing a vmexit. In that case read
952 * it after vmexit and store it in vmx->spec_ctrl.
954 if (!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL))
955 flags |= VMX_RUN_SAVE_SPEC_CTRL;
957 return flags;
960 static __always_inline void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
961 unsigned long entry, unsigned long exit)
963 vm_entry_controls_clearbit(vmx, entry);
964 vm_exit_controls_clearbit(vmx, exit);
967 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
969 unsigned int i;
971 for (i = 0; i < m->nr; ++i) {
972 if (m->val[i].index == msr)
973 return i;
975 return -ENOENT;
978 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
980 int i;
981 struct msr_autoload *m = &vmx->msr_autoload;
983 switch (msr) {
984 case MSR_EFER:
985 if (cpu_has_load_ia32_efer()) {
986 clear_atomic_switch_msr_special(vmx,
987 VM_ENTRY_LOAD_IA32_EFER,
988 VM_EXIT_LOAD_IA32_EFER);
989 return;
991 break;
992 case MSR_CORE_PERF_GLOBAL_CTRL:
993 if (cpu_has_load_perf_global_ctrl()) {
994 clear_atomic_switch_msr_special(vmx,
995 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
996 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
997 return;
999 break;
1001 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
1002 if (i < 0)
1003 goto skip_guest;
1004 --m->guest.nr;
1005 m->guest.val[i] = m->guest.val[m->guest.nr];
1006 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1008 skip_guest:
1009 i = vmx_find_loadstore_msr_slot(&m->host, msr);
1010 if (i < 0)
1011 return;
1013 --m->host.nr;
1014 m->host.val[i] = m->host.val[m->host.nr];
1015 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1018 static __always_inline void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1019 unsigned long entry, unsigned long exit,
1020 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
1021 u64 guest_val, u64 host_val)
1023 vmcs_write64(guest_val_vmcs, guest_val);
1024 if (host_val_vmcs != HOST_IA32_EFER)
1025 vmcs_write64(host_val_vmcs, host_val);
1026 vm_entry_controls_setbit(vmx, entry);
1027 vm_exit_controls_setbit(vmx, exit);
1030 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1031 u64 guest_val, u64 host_val, bool entry_only)
1033 int i, j = 0;
1034 struct msr_autoload *m = &vmx->msr_autoload;
1036 switch (msr) {
1037 case MSR_EFER:
1038 if (cpu_has_load_ia32_efer()) {
1039 add_atomic_switch_msr_special(vmx,
1040 VM_ENTRY_LOAD_IA32_EFER,
1041 VM_EXIT_LOAD_IA32_EFER,
1042 GUEST_IA32_EFER,
1043 HOST_IA32_EFER,
1044 guest_val, host_val);
1045 return;
1047 break;
1048 case MSR_CORE_PERF_GLOBAL_CTRL:
1049 if (cpu_has_load_perf_global_ctrl()) {
1050 add_atomic_switch_msr_special(vmx,
1051 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1052 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1053 GUEST_IA32_PERF_GLOBAL_CTRL,
1054 HOST_IA32_PERF_GLOBAL_CTRL,
1055 guest_val, host_val);
1056 return;
1058 break;
1059 case MSR_IA32_PEBS_ENABLE:
1060 /* PEBS needs a quiescent period after being disabled (to write
1061 * a record). Disabling PEBS through VMX MSR swapping doesn't
1062 * provide that period, so a CPU could write host's record into
1063 * guest's memory.
1065 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
1068 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
1069 if (!entry_only)
1070 j = vmx_find_loadstore_msr_slot(&m->host, msr);
1072 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
1073 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
1074 printk_once(KERN_WARNING "Not enough msr switch entries. "
1075 "Can't add msr %x\n", msr);
1076 return;
1078 if (i < 0) {
1079 i = m->guest.nr++;
1080 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1082 m->guest.val[i].index = msr;
1083 m->guest.val[i].value = guest_val;
1085 if (entry_only)
1086 return;
1088 if (j < 0) {
1089 j = m->host.nr++;
1090 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1092 m->host.val[j].index = msr;
1093 m->host.val[j].value = host_val;
1096 static bool update_transition_efer(struct vcpu_vmx *vmx)
1098 u64 guest_efer = vmx->vcpu.arch.efer;
1099 u64 ignore_bits = 0;
1100 int i;
1102 /* Shadow paging assumes NX to be available. */
1103 if (!enable_ept)
1104 guest_efer |= EFER_NX;
1107 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1109 ignore_bits |= EFER_SCE;
1110 #ifdef CONFIG_X86_64
1111 ignore_bits |= EFER_LMA | EFER_LME;
1112 /* SCE is meaningful only in long mode on Intel */
1113 if (guest_efer & EFER_LMA)
1114 ignore_bits &= ~(u64)EFER_SCE;
1115 #endif
1118 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1119 * On CPUs that support "load IA32_EFER", always switch EFER
1120 * atomically, since it's faster than switching it manually.
1122 if (cpu_has_load_ia32_efer() ||
1123 (enable_ept && ((vmx->vcpu.arch.efer ^ kvm_host.efer) & EFER_NX))) {
1124 if (!(guest_efer & EFER_LMA))
1125 guest_efer &= ~EFER_LME;
1126 if (guest_efer != kvm_host.efer)
1127 add_atomic_switch_msr(vmx, MSR_EFER,
1128 guest_efer, kvm_host.efer, false);
1129 else
1130 clear_atomic_switch_msr(vmx, MSR_EFER);
1131 return false;
1134 i = kvm_find_user_return_msr(MSR_EFER);
1135 if (i < 0)
1136 return false;
1138 clear_atomic_switch_msr(vmx, MSR_EFER);
1140 guest_efer &= ~ignore_bits;
1141 guest_efer |= kvm_host.efer & ignore_bits;
1143 vmx->guest_uret_msrs[i].data = guest_efer;
1144 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1146 return true;
1149 #ifdef CONFIG_X86_32
1151 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1152 * VMCS rather than the segment table. KVM uses this helper to figure
1153 * out the current bases to poke them into the VMCS before entry.
1155 static unsigned long segment_base(u16 selector)
1157 struct desc_struct *table;
1158 unsigned long v;
1160 if (!(selector & ~SEGMENT_RPL_MASK))
1161 return 0;
1163 table = get_current_gdt_ro();
1165 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1166 u16 ldt_selector = kvm_read_ldt();
1168 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1169 return 0;
1171 table = (struct desc_struct *)segment_base(ldt_selector);
1173 v = get_desc_base(&table[selector >> 3]);
1174 return v;
1176 #endif
1178 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1180 return vmx_pt_mode_is_host_guest() &&
1181 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1184 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1186 /* The base must be 128-byte aligned and a legal physical address. */
1187 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1190 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1192 u32 i;
1194 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1195 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1196 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1197 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1198 for (i = 0; i < addr_range; i++) {
1199 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1200 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1204 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1206 u32 i;
1208 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1209 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1210 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1211 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1212 for (i = 0; i < addr_range; i++) {
1213 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1214 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1218 static void pt_guest_enter(struct vcpu_vmx *vmx)
1220 if (vmx_pt_mode_is_system())
1221 return;
1224 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1225 * Save host state before VM entry.
1227 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1228 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1229 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1230 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1231 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1235 static void pt_guest_exit(struct vcpu_vmx *vmx)
1237 if (vmx_pt_mode_is_system())
1238 return;
1240 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1241 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1242 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1246 * KVM requires VM_EXIT_CLEAR_IA32_RTIT_CTL to expose PT to the guest,
1247 * i.e. RTIT_CTL is always cleared on VM-Exit. Restore it if necessary.
1249 if (vmx->pt_desc.host.ctl)
1250 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1253 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1254 unsigned long fs_base, unsigned long gs_base)
1256 if (unlikely(fs_sel != host->fs_sel)) {
1257 if (!(fs_sel & 7))
1258 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1259 else
1260 vmcs_write16(HOST_FS_SELECTOR, 0);
1261 host->fs_sel = fs_sel;
1263 if (unlikely(gs_sel != host->gs_sel)) {
1264 if (!(gs_sel & 7))
1265 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1266 else
1267 vmcs_write16(HOST_GS_SELECTOR, 0);
1268 host->gs_sel = gs_sel;
1270 if (unlikely(fs_base != host->fs_base)) {
1271 vmcs_writel(HOST_FS_BASE, fs_base);
1272 host->fs_base = fs_base;
1274 if (unlikely(gs_base != host->gs_base)) {
1275 vmcs_writel(HOST_GS_BASE, gs_base);
1276 host->gs_base = gs_base;
1280 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1282 struct vcpu_vmx *vmx = to_vmx(vcpu);
1283 struct vmcs_host_state *host_state;
1284 #ifdef CONFIG_X86_64
1285 int cpu = raw_smp_processor_id();
1286 #endif
1287 unsigned long fs_base, gs_base;
1288 u16 fs_sel, gs_sel;
1289 int i;
1292 * Note that guest MSRs to be saved/restored can also be changed
1293 * when guest state is loaded. This happens when guest transitions
1294 * to/from long-mode by setting MSR_EFER.LMA.
1296 if (!vmx->guest_uret_msrs_loaded) {
1297 vmx->guest_uret_msrs_loaded = true;
1298 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
1299 if (!vmx->guest_uret_msrs[i].load_into_hardware)
1300 continue;
1302 kvm_set_user_return_msr(i,
1303 vmx->guest_uret_msrs[i].data,
1304 vmx->guest_uret_msrs[i].mask);
1308 if (vmx->nested.need_vmcs12_to_shadow_sync)
1309 nested_sync_vmcs12_to_shadow(vcpu);
1311 if (vmx->guest_state_loaded)
1312 return;
1314 host_state = &vmx->loaded_vmcs->host_state;
1317 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1318 * allow segment selectors with cpl > 0 or ti == 1.
1320 host_state->ldt_sel = kvm_read_ldt();
1322 #ifdef CONFIG_X86_64
1323 savesegment(ds, host_state->ds_sel);
1324 savesegment(es, host_state->es_sel);
1326 gs_base = cpu_kernelmode_gs_base(cpu);
1327 if (likely(is_64bit_mm(current->mm))) {
1328 current_save_fsgs();
1329 fs_sel = current->thread.fsindex;
1330 gs_sel = current->thread.gsindex;
1331 fs_base = current->thread.fsbase;
1332 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1333 } else {
1334 savesegment(fs, fs_sel);
1335 savesegment(gs, gs_sel);
1336 fs_base = read_msr(MSR_FS_BASE);
1337 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1340 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1341 #else
1342 savesegment(fs, fs_sel);
1343 savesegment(gs, gs_sel);
1344 fs_base = segment_base(fs_sel);
1345 gs_base = segment_base(gs_sel);
1346 #endif
1348 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1349 vmx->guest_state_loaded = true;
1352 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1354 struct vmcs_host_state *host_state;
1356 if (!vmx->guest_state_loaded)
1357 return;
1359 host_state = &vmx->loaded_vmcs->host_state;
1361 ++vmx->vcpu.stat.host_state_reload;
1363 #ifdef CONFIG_X86_64
1364 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1365 #endif
1366 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1367 kvm_load_ldt(host_state->ldt_sel);
1368 #ifdef CONFIG_X86_64
1369 load_gs_index(host_state->gs_sel);
1370 #else
1371 loadsegment(gs, host_state->gs_sel);
1372 #endif
1374 if (host_state->fs_sel & 7)
1375 loadsegment(fs, host_state->fs_sel);
1376 #ifdef CONFIG_X86_64
1377 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1378 loadsegment(ds, host_state->ds_sel);
1379 loadsegment(es, host_state->es_sel);
1381 #endif
1382 invalidate_tss_limit();
1383 #ifdef CONFIG_X86_64
1384 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1385 #endif
1386 load_fixmap_gdt(raw_smp_processor_id());
1387 vmx->guest_state_loaded = false;
1388 vmx->guest_uret_msrs_loaded = false;
1391 #ifdef CONFIG_X86_64
1392 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1394 preempt_disable();
1395 if (vmx->guest_state_loaded)
1396 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1397 preempt_enable();
1398 return vmx->msr_guest_kernel_gs_base;
1401 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1403 preempt_disable();
1404 if (vmx->guest_state_loaded)
1405 wrmsrl(MSR_KERNEL_GS_BASE, data);
1406 preempt_enable();
1407 vmx->msr_guest_kernel_gs_base = data;
1409 #endif
1411 static void grow_ple_window(struct kvm_vcpu *vcpu)
1413 struct vcpu_vmx *vmx = to_vmx(vcpu);
1414 unsigned int old = vmx->ple_window;
1416 vmx->ple_window = __grow_ple_window(old, ple_window,
1417 ple_window_grow,
1418 ple_window_max);
1420 if (vmx->ple_window != old) {
1421 vmx->ple_window_dirty = true;
1422 trace_kvm_ple_window_update(vcpu->vcpu_id,
1423 vmx->ple_window, old);
1427 static void shrink_ple_window(struct kvm_vcpu *vcpu)
1429 struct vcpu_vmx *vmx = to_vmx(vcpu);
1430 unsigned int old = vmx->ple_window;
1432 vmx->ple_window = __shrink_ple_window(old, ple_window,
1433 ple_window_shrink,
1434 ple_window);
1436 if (vmx->ple_window != old) {
1437 vmx->ple_window_dirty = true;
1438 trace_kvm_ple_window_update(vcpu->vcpu_id,
1439 vmx->ple_window, old);
1443 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1444 struct loaded_vmcs *buddy)
1446 struct vcpu_vmx *vmx = to_vmx(vcpu);
1447 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1448 struct vmcs *prev;
1450 if (!already_loaded) {
1451 loaded_vmcs_clear(vmx->loaded_vmcs);
1452 local_irq_disable();
1455 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1456 * this cpu's percpu list, otherwise it may not yet be deleted
1457 * from its previous cpu's percpu list. Pairs with the
1458 * smb_wmb() in __loaded_vmcs_clear().
1460 smp_rmb();
1462 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1463 &per_cpu(loaded_vmcss_on_cpu, cpu));
1464 local_irq_enable();
1467 prev = per_cpu(current_vmcs, cpu);
1468 if (prev != vmx->loaded_vmcs->vmcs) {
1469 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1470 vmcs_load(vmx->loaded_vmcs->vmcs);
1473 * No indirect branch prediction barrier needed when switching
1474 * the active VMCS within a vCPU, unless IBRS is advertised to
1475 * the vCPU. To minimize the number of IBPBs executed, KVM
1476 * performs IBPB on nested VM-Exit (a single nested transition
1477 * may switch the active VMCS multiple times).
1479 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1480 indirect_branch_prediction_barrier();
1483 if (!already_loaded) {
1484 void *gdt = get_current_gdt_ro();
1487 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1488 * TLB entries from its previous association with the vCPU.
1490 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1493 * Linux uses per-cpu TSS and GDT, so set these when switching
1494 * processors. See 22.2.4.
1496 vmcs_writel(HOST_TR_BASE,
1497 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1498 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1500 if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) {
1501 /* 22.2.3 */
1502 vmcs_writel(HOST_IA32_SYSENTER_ESP,
1503 (unsigned long)(cpu_entry_stack(cpu) + 1));
1506 vmx->loaded_vmcs->cpu = cpu;
1511 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1512 * vcpu mutex is already taken.
1514 void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1516 struct vcpu_vmx *vmx = to_vmx(vcpu);
1518 if (vcpu->scheduled_out && !kvm_pause_in_guest(vcpu->kvm))
1519 shrink_ple_window(vcpu);
1521 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1523 vmx_vcpu_pi_load(vcpu, cpu);
1525 vmx->host_debugctlmsr = get_debugctlmsr();
1528 void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1530 vmx_vcpu_pi_put(vcpu);
1532 vmx_prepare_switch_to_host(to_vmx(vcpu));
1535 bool vmx_emulation_required(struct kvm_vcpu *vcpu)
1537 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1540 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1542 struct vcpu_vmx *vmx = to_vmx(vcpu);
1543 unsigned long rflags, save_rflags;
1545 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1546 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1547 rflags = vmcs_readl(GUEST_RFLAGS);
1548 if (vmx->rmode.vm86_active) {
1549 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1550 save_rflags = vmx->rmode.save_rflags;
1551 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1553 vmx->rflags = rflags;
1555 return vmx->rflags;
1558 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1560 struct vcpu_vmx *vmx = to_vmx(vcpu);
1561 unsigned long old_rflags;
1564 * Unlike CR0 and CR4, RFLAGS handling requires checking if the vCPU
1565 * is an unrestricted guest in order to mark L2 as needing emulation
1566 * if L1 runs L2 as a restricted guest.
1568 if (is_unrestricted_guest(vcpu)) {
1569 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1570 vmx->rflags = rflags;
1571 vmcs_writel(GUEST_RFLAGS, rflags);
1572 return;
1575 old_rflags = vmx_get_rflags(vcpu);
1576 vmx->rflags = rflags;
1577 if (vmx->rmode.vm86_active) {
1578 vmx->rmode.save_rflags = rflags;
1579 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1581 vmcs_writel(GUEST_RFLAGS, rflags);
1583 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1584 vmx->emulation_required = vmx_emulation_required(vcpu);
1587 bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
1589 return vmx_get_rflags(vcpu) & X86_EFLAGS_IF;
1592 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1594 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1595 int ret = 0;
1597 if (interruptibility & GUEST_INTR_STATE_STI)
1598 ret |= KVM_X86_SHADOW_INT_STI;
1599 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1600 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1602 return ret;
1605 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1607 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1608 u32 interruptibility = interruptibility_old;
1610 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1612 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1613 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1614 else if (mask & KVM_X86_SHADOW_INT_STI)
1615 interruptibility |= GUEST_INTR_STATE_STI;
1617 if ((interruptibility != interruptibility_old))
1618 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1621 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1623 struct vcpu_vmx *vmx = to_vmx(vcpu);
1624 unsigned long value;
1627 * Any MSR write that attempts to change bits marked reserved will
1628 * case a #GP fault.
1630 if (data & vmx->pt_desc.ctl_bitmask)
1631 return 1;
1634 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1635 * result in a #GP unless the same write also clears TraceEn.
1637 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1638 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1639 return 1;
1642 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1643 * and FabricEn would cause #GP, if
1644 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1646 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1647 !(data & RTIT_CTL_FABRIC_EN) &&
1648 !intel_pt_validate_cap(vmx->pt_desc.caps,
1649 PT_CAP_single_range_output))
1650 return 1;
1653 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1654 * utilize encodings marked reserved will cause a #GP fault.
1656 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1657 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1658 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1659 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1660 return 1;
1661 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1662 PT_CAP_cycle_thresholds);
1663 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1664 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1665 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1666 return 1;
1667 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1668 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1669 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1670 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1671 return 1;
1674 * If ADDRx_CFG is reserved or the encodings is >2 will
1675 * cause a #GP fault.
1677 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1678 if ((value && (vmx->pt_desc.num_address_ranges < 1)) || (value > 2))
1679 return 1;
1680 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1681 if ((value && (vmx->pt_desc.num_address_ranges < 2)) || (value > 2))
1682 return 1;
1683 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1684 if ((value && (vmx->pt_desc.num_address_ranges < 3)) || (value > 2))
1685 return 1;
1686 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1687 if ((value && (vmx->pt_desc.num_address_ranges < 4)) || (value > 2))
1688 return 1;
1690 return 0;
1693 int vmx_check_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
1694 void *insn, int insn_len)
1697 * Emulation of instructions in SGX enclaves is impossible as RIP does
1698 * not point at the failing instruction, and even if it did, the code
1699 * stream is inaccessible. Inject #UD instead of exiting to userspace
1700 * so that guest userspace can't DoS the guest simply by triggering
1701 * emulation (enclaves are CPL3 only).
1703 if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1704 kvm_queue_exception(vcpu, UD_VECTOR);
1705 return X86EMUL_PROPAGATE_FAULT;
1707 return X86EMUL_CONTINUE;
1710 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1712 union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1713 unsigned long rip, orig_rip;
1714 u32 instr_len;
1717 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1718 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1719 * set when EPT misconfig occurs. In practice, real hardware updates
1720 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1721 * (namely Hyper-V) don't set it due to it being undefined behavior,
1722 * i.e. we end up advancing IP with some random value.
1724 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1725 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1726 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1729 * Emulating an enclave's instructions isn't supported as KVM
1730 * cannot access the enclave's memory or its true RIP, e.g. the
1731 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1732 * the RIP that actually triggered the VM-Exit. But, because
1733 * most instructions that cause VM-Exit will #UD in an enclave,
1734 * most instruction-based VM-Exits simply do not occur.
1736 * There are a few exceptions, notably the debug instructions
1737 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1738 * and generate #DB/#BP as expected, which KVM might intercept.
1739 * But again, the CPU does the dirty work and saves an instr
1740 * length of zero so VMMs don't shoot themselves in the foot.
1741 * WARN if KVM tries to skip a non-zero length instruction on
1742 * a VM-Exit from an enclave.
1744 if (!instr_len)
1745 goto rip_updated;
1747 WARN_ONCE(exit_reason.enclave_mode,
1748 "skipping instruction after SGX enclave VM-Exit");
1750 orig_rip = kvm_rip_read(vcpu);
1751 rip = orig_rip + instr_len;
1752 #ifdef CONFIG_X86_64
1754 * We need to mask out the high 32 bits of RIP if not in 64-bit
1755 * mode, but just finding out that we are in 64-bit mode is
1756 * quite expensive. Only do it if there was a carry.
1758 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1759 rip = (u32)rip;
1760 #endif
1761 kvm_rip_write(vcpu, rip);
1762 } else {
1763 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1764 return 0;
1767 rip_updated:
1768 /* skipping an emulated instruction also counts */
1769 vmx_set_interrupt_shadow(vcpu, 0);
1771 return 1;
1775 * Recognizes a pending MTF VM-exit and records the nested state for later
1776 * delivery.
1778 void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1780 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1781 struct vcpu_vmx *vmx = to_vmx(vcpu);
1783 if (!is_guest_mode(vcpu))
1784 return;
1787 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1788 * TSS T-bit traps and ICEBP (INT1). KVM doesn't emulate T-bit traps
1789 * or ICEBP (in the emulator proper), and skipping of ICEBP after an
1790 * intercepted #DB deliberately avoids single-step #DB and MTF updates
1791 * as ICEBP is higher priority than both. As instruction emulation is
1792 * completed at this point (i.e. KVM is at the instruction boundary),
1793 * any #DB exception pending delivery must be a debug-trap of lower
1794 * priority than MTF. Record the pending MTF state to be delivered in
1795 * vmx_check_nested_events().
1797 if (nested_cpu_has_mtf(vmcs12) &&
1798 (!vcpu->arch.exception.pending ||
1799 vcpu->arch.exception.vector == DB_VECTOR) &&
1800 (!vcpu->arch.exception_vmexit.pending ||
1801 vcpu->arch.exception_vmexit.vector == DB_VECTOR)) {
1802 vmx->nested.mtf_pending = true;
1803 kvm_make_request(KVM_REQ_EVENT, vcpu);
1804 } else {
1805 vmx->nested.mtf_pending = false;
1809 int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1811 vmx_update_emulated_instruction(vcpu);
1812 return skip_emulated_instruction(vcpu);
1815 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1818 * Ensure that we clear the HLT state in the VMCS. We don't need to
1819 * explicitly skip the instruction because if the HLT state is set,
1820 * then the instruction is already executing and RIP has already been
1821 * advanced.
1823 if (kvm_hlt_in_guest(vcpu->kvm) &&
1824 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1825 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1828 void vmx_inject_exception(struct kvm_vcpu *vcpu)
1830 struct kvm_queued_exception *ex = &vcpu->arch.exception;
1831 u32 intr_info = ex->vector | INTR_INFO_VALID_MASK;
1832 struct vcpu_vmx *vmx = to_vmx(vcpu);
1834 kvm_deliver_exception_payload(vcpu, ex);
1836 if (ex->has_error_code) {
1838 * Despite the error code being architecturally defined as 32
1839 * bits, and the VMCS field being 32 bits, Intel CPUs and thus
1840 * VMX don't actually supporting setting bits 31:16. Hardware
1841 * will (should) never provide a bogus error code, but AMD CPUs
1842 * do generate error codes with bits 31:16 set, and so KVM's
1843 * ABI lets userspace shove in arbitrary 32-bit values. Drop
1844 * the upper bits to avoid VM-Fail, losing information that
1845 * doesn't really exist is preferable to killing the VM.
1847 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)ex->error_code);
1848 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1851 if (vmx->rmode.vm86_active) {
1852 int inc_eip = 0;
1853 if (kvm_exception_is_soft(ex->vector))
1854 inc_eip = vcpu->arch.event_exit_inst_len;
1855 kvm_inject_realmode_interrupt(vcpu, ex->vector, inc_eip);
1856 return;
1859 WARN_ON_ONCE(vmx->emulation_required);
1861 if (kvm_exception_is_soft(ex->vector)) {
1862 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1863 vmx->vcpu.arch.event_exit_inst_len);
1864 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1865 } else
1866 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1868 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1870 vmx_clear_hlt(vcpu);
1873 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
1874 bool load_into_hardware)
1876 struct vmx_uret_msr *uret_msr;
1878 uret_msr = vmx_find_uret_msr(vmx, msr);
1879 if (!uret_msr)
1880 return;
1882 uret_msr->load_into_hardware = load_into_hardware;
1886 * Configuring user return MSRs to automatically save, load, and restore MSRs
1887 * that need to be shoved into hardware when running the guest. Note, omitting
1888 * an MSR here does _NOT_ mean it's not emulated, only that it will not be
1889 * loaded into hardware when running the guest.
1891 static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx)
1893 #ifdef CONFIG_X86_64
1894 bool load_syscall_msrs;
1897 * The SYSCALL MSRs are only needed on long mode guests, and only
1898 * when EFER.SCE is set.
1900 load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
1901 (vmx->vcpu.arch.efer & EFER_SCE);
1903 vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
1904 vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
1905 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
1906 #endif
1907 vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
1909 vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
1910 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
1911 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
1914 * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
1915 * kernel and old userspace. If those guests run on a tsx=off host, do
1916 * allow guests to use TSX_CTRL, but don't change the value in hardware
1917 * so that TSX remains always disabled.
1919 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
1922 * The set of MSRs to load may have changed, reload MSRs before the
1923 * next VM-Enter.
1925 vmx->guest_uret_msrs_loaded = false;
1928 u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1930 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1932 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING))
1933 return vmcs12->tsc_offset;
1935 return 0;
1938 u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1940 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1942 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) &&
1943 nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
1944 return vmcs12->tsc_multiplier;
1946 return kvm_caps.default_tsc_scaling_ratio;
1949 void vmx_write_tsc_offset(struct kvm_vcpu *vcpu)
1951 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
1954 void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu)
1956 vmcs_write64(TSC_MULTIPLIER, vcpu->arch.tsc_scaling_ratio);
1960 * Userspace is allowed to set any supported IA32_FEATURE_CONTROL regardless of
1961 * guest CPUID. Note, KVM allows userspace to set "VMX in SMX" to maintain
1962 * backwards compatibility even though KVM doesn't support emulating SMX. And
1963 * because userspace set "VMX in SMX", the guest must also be allowed to set it,
1964 * e.g. if the MSR is left unlocked and the guest does a RMW operation.
1966 #define KVM_SUPPORTED_FEATURE_CONTROL (FEAT_CTL_LOCKED | \
1967 FEAT_CTL_VMX_ENABLED_INSIDE_SMX | \
1968 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX | \
1969 FEAT_CTL_SGX_LC_ENABLED | \
1970 FEAT_CTL_SGX_ENABLED | \
1971 FEAT_CTL_LMCE_ENABLED)
1973 static inline bool is_vmx_feature_control_msr_valid(struct vcpu_vmx *vmx,
1974 struct msr_data *msr)
1976 uint64_t valid_bits;
1979 * Ensure KVM_SUPPORTED_FEATURE_CONTROL is updated when new bits are
1980 * exposed to the guest.
1982 WARN_ON_ONCE(vmx->msr_ia32_feature_control_valid_bits &
1983 ~KVM_SUPPORTED_FEATURE_CONTROL);
1985 if (!msr->host_initiated &&
1986 (vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED))
1987 return false;
1989 if (msr->host_initiated)
1990 valid_bits = KVM_SUPPORTED_FEATURE_CONTROL;
1991 else
1992 valid_bits = vmx->msr_ia32_feature_control_valid_bits;
1994 return !(msr->data & ~valid_bits);
1997 int vmx_get_feature_msr(u32 msr, u64 *data)
1999 switch (msr) {
2000 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR:
2001 if (!nested)
2002 return 1;
2003 return vmx_get_vmx_msr(&vmcs_config.nested, msr, data);
2004 default:
2005 return KVM_MSR_RET_UNSUPPORTED;
2010 * Reads an msr value (of 'msr_info->index') into 'msr_info->data'.
2011 * Returns 0 on success, non-0 otherwise.
2012 * Assumes vcpu_load() was already called.
2014 int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2016 struct vcpu_vmx *vmx = to_vmx(vcpu);
2017 struct vmx_uret_msr *msr;
2018 u32 index;
2020 switch (msr_info->index) {
2021 #ifdef CONFIG_X86_64
2022 case MSR_FS_BASE:
2023 msr_info->data = vmcs_readl(GUEST_FS_BASE);
2024 break;
2025 case MSR_GS_BASE:
2026 msr_info->data = vmcs_readl(GUEST_GS_BASE);
2027 break;
2028 case MSR_KERNEL_GS_BASE:
2029 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
2030 break;
2031 #endif
2032 case MSR_EFER:
2033 return kvm_get_msr_common(vcpu, msr_info);
2034 case MSR_IA32_TSX_CTRL:
2035 if (!msr_info->host_initiated &&
2036 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2037 return 1;
2038 goto find_uret_msr;
2039 case MSR_IA32_UMWAIT_CONTROL:
2040 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2041 return 1;
2043 msr_info->data = vmx->msr_ia32_umwait_control;
2044 break;
2045 case MSR_IA32_SPEC_CTRL:
2046 if (!msr_info->host_initiated &&
2047 !guest_has_spec_ctrl_msr(vcpu))
2048 return 1;
2050 msr_info->data = to_vmx(vcpu)->spec_ctrl;
2051 break;
2052 case MSR_IA32_SYSENTER_CS:
2053 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
2054 break;
2055 case MSR_IA32_SYSENTER_EIP:
2056 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
2057 break;
2058 case MSR_IA32_SYSENTER_ESP:
2059 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
2060 break;
2061 case MSR_IA32_BNDCFGS:
2062 if (!kvm_mpx_supported() ||
2063 (!msr_info->host_initiated &&
2064 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2065 return 1;
2066 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
2067 break;
2068 case MSR_IA32_MCG_EXT_CTL:
2069 if (!msr_info->host_initiated &&
2070 !(vmx->msr_ia32_feature_control &
2071 FEAT_CTL_LMCE_ENABLED))
2072 return 1;
2073 msr_info->data = vcpu->arch.mcg_ext_ctl;
2074 break;
2075 case MSR_IA32_FEAT_CTL:
2076 msr_info->data = vmx->msr_ia32_feature_control;
2077 break;
2078 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2079 if (!msr_info->host_initiated &&
2080 !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
2081 return 1;
2082 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
2083 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
2084 break;
2085 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR:
2086 if (!guest_can_use(vcpu, X86_FEATURE_VMX))
2087 return 1;
2088 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
2089 &msr_info->data))
2090 return 1;
2091 #ifdef CONFIG_KVM_HYPERV
2093 * Enlightened VMCS v1 doesn't have certain VMCS fields but
2094 * instead of just ignoring the features, different Hyper-V
2095 * versions are either trying to use them and fail or do some
2096 * sanity checking and refuse to boot. Filter all unsupported
2097 * features out.
2099 if (!msr_info->host_initiated && guest_cpuid_has_evmcs(vcpu))
2100 nested_evmcs_filter_control_msr(vcpu, msr_info->index,
2101 &msr_info->data);
2102 #endif
2103 break;
2104 case MSR_IA32_RTIT_CTL:
2105 if (!vmx_pt_mode_is_host_guest())
2106 return 1;
2107 msr_info->data = vmx->pt_desc.guest.ctl;
2108 break;
2109 case MSR_IA32_RTIT_STATUS:
2110 if (!vmx_pt_mode_is_host_guest())
2111 return 1;
2112 msr_info->data = vmx->pt_desc.guest.status;
2113 break;
2114 case MSR_IA32_RTIT_CR3_MATCH:
2115 if (!vmx_pt_mode_is_host_guest() ||
2116 !intel_pt_validate_cap(vmx->pt_desc.caps,
2117 PT_CAP_cr3_filtering))
2118 return 1;
2119 msr_info->data = vmx->pt_desc.guest.cr3_match;
2120 break;
2121 case MSR_IA32_RTIT_OUTPUT_BASE:
2122 if (!vmx_pt_mode_is_host_guest() ||
2123 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2124 PT_CAP_topa_output) &&
2125 !intel_pt_validate_cap(vmx->pt_desc.caps,
2126 PT_CAP_single_range_output)))
2127 return 1;
2128 msr_info->data = vmx->pt_desc.guest.output_base;
2129 break;
2130 case MSR_IA32_RTIT_OUTPUT_MASK:
2131 if (!vmx_pt_mode_is_host_guest() ||
2132 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2133 PT_CAP_topa_output) &&
2134 !intel_pt_validate_cap(vmx->pt_desc.caps,
2135 PT_CAP_single_range_output)))
2136 return 1;
2137 msr_info->data = vmx->pt_desc.guest.output_mask;
2138 break;
2139 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2140 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2141 if (!vmx_pt_mode_is_host_guest() ||
2142 (index >= 2 * vmx->pt_desc.num_address_ranges))
2143 return 1;
2144 if (index % 2)
2145 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
2146 else
2147 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
2148 break;
2149 case MSR_IA32_DEBUGCTLMSR:
2150 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
2151 break;
2152 default:
2153 find_uret_msr:
2154 msr = vmx_find_uret_msr(vmx, msr_info->index);
2155 if (msr) {
2156 msr_info->data = msr->data;
2157 break;
2159 return kvm_get_msr_common(vcpu, msr_info);
2162 return 0;
2165 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
2166 u64 data)
2168 #ifdef CONFIG_X86_64
2169 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
2170 return (u32)data;
2171 #endif
2172 return (unsigned long)data;
2175 static u64 vmx_get_supported_debugctl(struct kvm_vcpu *vcpu, bool host_initiated)
2177 u64 debugctl = 0;
2179 if (boot_cpu_has(X86_FEATURE_BUS_LOCK_DETECT) &&
2180 (host_initiated || guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT)))
2181 debugctl |= DEBUGCTLMSR_BUS_LOCK_DETECT;
2183 if ((kvm_caps.supported_perf_cap & PMU_CAP_LBR_FMT) &&
2184 (host_initiated || intel_pmu_lbr_is_enabled(vcpu)))
2185 debugctl |= DEBUGCTLMSR_LBR | DEBUGCTLMSR_FREEZE_LBRS_ON_PMI;
2187 return debugctl;
2191 * Writes msr value into the appropriate "register".
2192 * Returns 0 on success, non-0 otherwise.
2193 * Assumes vcpu_load() was already called.
2195 int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2197 struct vcpu_vmx *vmx = to_vmx(vcpu);
2198 struct vmx_uret_msr *msr;
2199 int ret = 0;
2200 u32 msr_index = msr_info->index;
2201 u64 data = msr_info->data;
2202 u32 index;
2204 switch (msr_index) {
2205 case MSR_EFER:
2206 ret = kvm_set_msr_common(vcpu, msr_info);
2207 break;
2208 #ifdef CONFIG_X86_64
2209 case MSR_FS_BASE:
2210 vmx_segment_cache_clear(vmx);
2211 vmcs_writel(GUEST_FS_BASE, data);
2212 break;
2213 case MSR_GS_BASE:
2214 vmx_segment_cache_clear(vmx);
2215 vmcs_writel(GUEST_GS_BASE, data);
2216 break;
2217 case MSR_KERNEL_GS_BASE:
2218 vmx_write_guest_kernel_gs_base(vmx, data);
2219 break;
2220 case MSR_IA32_XFD:
2221 ret = kvm_set_msr_common(vcpu, msr_info);
2223 * Always intercepting WRMSR could incur non-negligible
2224 * overhead given xfd might be changed frequently in
2225 * guest context switch. Disable write interception
2226 * upon the first write with a non-zero value (indicating
2227 * potential usage on dynamic xfeatures). Also update
2228 * exception bitmap to trap #NM for proper virtualization
2229 * of guest xfd_err.
2231 if (!ret && data) {
2232 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_XFD,
2233 MSR_TYPE_RW);
2234 vcpu->arch.xfd_no_write_intercept = true;
2235 vmx_update_exception_bitmap(vcpu);
2237 break;
2238 #endif
2239 case MSR_IA32_SYSENTER_CS:
2240 if (is_guest_mode(vcpu))
2241 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2242 vmcs_write32(GUEST_SYSENTER_CS, data);
2243 break;
2244 case MSR_IA32_SYSENTER_EIP:
2245 if (is_guest_mode(vcpu)) {
2246 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2247 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2249 vmcs_writel(GUEST_SYSENTER_EIP, data);
2250 break;
2251 case MSR_IA32_SYSENTER_ESP:
2252 if (is_guest_mode(vcpu)) {
2253 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2254 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2256 vmcs_writel(GUEST_SYSENTER_ESP, data);
2257 break;
2258 case MSR_IA32_DEBUGCTLMSR: {
2259 u64 invalid;
2261 invalid = data & ~vmx_get_supported_debugctl(vcpu, msr_info->host_initiated);
2262 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2263 kvm_pr_unimpl_wrmsr(vcpu, msr_index, data);
2264 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2265 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2268 if (invalid)
2269 return 1;
2271 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2272 VM_EXIT_SAVE_DEBUG_CONTROLS)
2273 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2275 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2276 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2277 (data & DEBUGCTLMSR_LBR))
2278 intel_pmu_create_guest_lbr_event(vcpu);
2279 return 0;
2281 case MSR_IA32_BNDCFGS:
2282 if (!kvm_mpx_supported() ||
2283 (!msr_info->host_initiated &&
2284 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2285 return 1;
2286 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2287 (data & MSR_IA32_BNDCFGS_RSVD))
2288 return 1;
2290 if (is_guest_mode(vcpu) &&
2291 ((vmx->nested.msrs.entry_ctls_high & VM_ENTRY_LOAD_BNDCFGS) ||
2292 (vmx->nested.msrs.exit_ctls_high & VM_EXIT_CLEAR_BNDCFGS)))
2293 get_vmcs12(vcpu)->guest_bndcfgs = data;
2295 vmcs_write64(GUEST_BNDCFGS, data);
2296 break;
2297 case MSR_IA32_UMWAIT_CONTROL:
2298 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2299 return 1;
2301 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2302 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2303 return 1;
2305 vmx->msr_ia32_umwait_control = data;
2306 break;
2307 case MSR_IA32_SPEC_CTRL:
2308 if (!msr_info->host_initiated &&
2309 !guest_has_spec_ctrl_msr(vcpu))
2310 return 1;
2312 if (kvm_spec_ctrl_test_value(data))
2313 return 1;
2315 vmx->spec_ctrl = data;
2316 if (!data)
2317 break;
2320 * For non-nested:
2321 * When it's written (to non-zero) for the first time, pass
2322 * it through.
2324 * For nested:
2325 * The handling of the MSR bitmap for L2 guests is done in
2326 * nested_vmx_prepare_msr_bitmap. We should not touch the
2327 * vmcs02.msr_bitmap here since it gets completely overwritten
2328 * in the merging. We update the vmcs01 here for L1 as well
2329 * since it will end up touching the MSR anyway now.
2331 vmx_disable_intercept_for_msr(vcpu,
2332 MSR_IA32_SPEC_CTRL,
2333 MSR_TYPE_RW);
2334 break;
2335 case MSR_IA32_TSX_CTRL:
2336 if (!msr_info->host_initiated &&
2337 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2338 return 1;
2339 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2340 return 1;
2341 goto find_uret_msr;
2342 case MSR_IA32_CR_PAT:
2343 ret = kvm_set_msr_common(vcpu, msr_info);
2344 if (ret)
2345 break;
2347 if (is_guest_mode(vcpu) &&
2348 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2349 get_vmcs12(vcpu)->guest_ia32_pat = data;
2351 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
2352 vmcs_write64(GUEST_IA32_PAT, data);
2353 break;
2354 case MSR_IA32_MCG_EXT_CTL:
2355 if ((!msr_info->host_initiated &&
2356 !(to_vmx(vcpu)->msr_ia32_feature_control &
2357 FEAT_CTL_LMCE_ENABLED)) ||
2358 (data & ~MCG_EXT_CTL_LMCE_EN))
2359 return 1;
2360 vcpu->arch.mcg_ext_ctl = data;
2361 break;
2362 case MSR_IA32_FEAT_CTL:
2363 if (!is_vmx_feature_control_msr_valid(vmx, msr_info))
2364 return 1;
2366 vmx->msr_ia32_feature_control = data;
2367 if (msr_info->host_initiated && data == 0)
2368 vmx_leave_nested(vcpu);
2370 /* SGX may be enabled/disabled by guest's firmware */
2371 vmx_write_encls_bitmap(vcpu, NULL);
2372 break;
2373 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2375 * On real hardware, the LE hash MSRs are writable before
2376 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2377 * at which point SGX related bits in IA32_FEATURE_CONTROL
2378 * become writable.
2380 * KVM does not emulate SGX activation for simplicity, so
2381 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2382 * is unlocked. This is technically not architectural
2383 * behavior, but it's close enough.
2385 if (!msr_info->host_initiated &&
2386 (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2387 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2388 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2389 return 1;
2390 vmx->msr_ia32_sgxlepubkeyhash
2391 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2392 break;
2393 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR:
2394 if (!msr_info->host_initiated)
2395 return 1; /* they are read-only */
2396 if (!guest_can_use(vcpu, X86_FEATURE_VMX))
2397 return 1;
2398 return vmx_set_vmx_msr(vcpu, msr_index, data);
2399 case MSR_IA32_RTIT_CTL:
2400 if (!vmx_pt_mode_is_host_guest() ||
2401 vmx_rtit_ctl_check(vcpu, data) ||
2402 vmx->nested.vmxon)
2403 return 1;
2404 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2405 vmx->pt_desc.guest.ctl = data;
2406 pt_update_intercept_for_msr(vcpu);
2407 break;
2408 case MSR_IA32_RTIT_STATUS:
2409 if (!pt_can_write_msr(vmx))
2410 return 1;
2411 if (data & MSR_IA32_RTIT_STATUS_MASK)
2412 return 1;
2413 vmx->pt_desc.guest.status = data;
2414 break;
2415 case MSR_IA32_RTIT_CR3_MATCH:
2416 if (!pt_can_write_msr(vmx))
2417 return 1;
2418 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2419 PT_CAP_cr3_filtering))
2420 return 1;
2421 vmx->pt_desc.guest.cr3_match = data;
2422 break;
2423 case MSR_IA32_RTIT_OUTPUT_BASE:
2424 if (!pt_can_write_msr(vmx))
2425 return 1;
2426 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2427 PT_CAP_topa_output) &&
2428 !intel_pt_validate_cap(vmx->pt_desc.caps,
2429 PT_CAP_single_range_output))
2430 return 1;
2431 if (!pt_output_base_valid(vcpu, data))
2432 return 1;
2433 vmx->pt_desc.guest.output_base = data;
2434 break;
2435 case MSR_IA32_RTIT_OUTPUT_MASK:
2436 if (!pt_can_write_msr(vmx))
2437 return 1;
2438 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2439 PT_CAP_topa_output) &&
2440 !intel_pt_validate_cap(vmx->pt_desc.caps,
2441 PT_CAP_single_range_output))
2442 return 1;
2443 vmx->pt_desc.guest.output_mask = data;
2444 break;
2445 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2446 if (!pt_can_write_msr(vmx))
2447 return 1;
2448 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2449 if (index >= 2 * vmx->pt_desc.num_address_ranges)
2450 return 1;
2451 if (is_noncanonical_address(data, vcpu))
2452 return 1;
2453 if (index % 2)
2454 vmx->pt_desc.guest.addr_b[index / 2] = data;
2455 else
2456 vmx->pt_desc.guest.addr_a[index / 2] = data;
2457 break;
2458 case MSR_IA32_PERF_CAPABILITIES:
2459 if (data && !vcpu_to_pmu(vcpu)->version)
2460 return 1;
2461 if (data & PMU_CAP_LBR_FMT) {
2462 if ((data & PMU_CAP_LBR_FMT) !=
2463 (kvm_caps.supported_perf_cap & PMU_CAP_LBR_FMT))
2464 return 1;
2465 if (!cpuid_model_is_consistent(vcpu))
2466 return 1;
2468 if (data & PERF_CAP_PEBS_FORMAT) {
2469 if ((data & PERF_CAP_PEBS_MASK) !=
2470 (kvm_caps.supported_perf_cap & PERF_CAP_PEBS_MASK))
2471 return 1;
2472 if (!guest_cpuid_has(vcpu, X86_FEATURE_DS))
2473 return 1;
2474 if (!guest_cpuid_has(vcpu, X86_FEATURE_DTES64))
2475 return 1;
2476 if (!cpuid_model_is_consistent(vcpu))
2477 return 1;
2479 ret = kvm_set_msr_common(vcpu, msr_info);
2480 break;
2482 default:
2483 find_uret_msr:
2484 msr = vmx_find_uret_msr(vmx, msr_index);
2485 if (msr)
2486 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2487 else
2488 ret = kvm_set_msr_common(vcpu, msr_info);
2491 /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */
2492 if (msr_index == MSR_IA32_ARCH_CAPABILITIES)
2493 vmx_update_fb_clear_dis(vcpu, vmx);
2495 return ret;
2498 void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2500 unsigned long guest_owned_bits;
2502 kvm_register_mark_available(vcpu, reg);
2504 switch (reg) {
2505 case VCPU_REGS_RSP:
2506 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2507 break;
2508 case VCPU_REGS_RIP:
2509 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2510 break;
2511 case VCPU_EXREG_PDPTR:
2512 if (enable_ept)
2513 ept_save_pdptrs(vcpu);
2514 break;
2515 case VCPU_EXREG_CR0:
2516 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2518 vcpu->arch.cr0 &= ~guest_owned_bits;
2519 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2520 break;
2521 case VCPU_EXREG_CR3:
2523 * When intercepting CR3 loads, e.g. for shadowing paging, KVM's
2524 * CR3 is loaded into hardware, not the guest's CR3.
2526 if (!(exec_controls_get(to_vmx(vcpu)) & CPU_BASED_CR3_LOAD_EXITING))
2527 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2528 break;
2529 case VCPU_EXREG_CR4:
2530 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2532 vcpu->arch.cr4 &= ~guest_owned_bits;
2533 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2534 break;
2535 default:
2536 KVM_BUG_ON(1, vcpu->kvm);
2537 break;
2542 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2543 * directly instead of going through cpu_has(), to ensure KVM is trapping
2544 * ENCLS whenever it's supported in hardware. It does not matter whether
2545 * the host OS supports or has enabled SGX.
2547 static bool cpu_has_sgx(void)
2549 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2553 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2554 * can't be used due to errata where VM Exit may incorrectly clear
2555 * IA32_PERF_GLOBAL_CTRL[34:32]. Work around the errata by using the
2556 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2558 static bool cpu_has_perf_global_ctrl_bug(void)
2560 switch (boot_cpu_data.x86_vfm) {
2561 case INTEL_NEHALEM_EP: /* AAK155 */
2562 case INTEL_NEHALEM: /* AAP115 */
2563 case INTEL_WESTMERE: /* AAT100 */
2564 case INTEL_WESTMERE_EP: /* BC86,AAY89,BD102 */
2565 case INTEL_NEHALEM_EX: /* BA97 */
2566 return true;
2567 default:
2568 break;
2571 return false;
2574 static int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt, u32 msr, u32 *result)
2576 u32 vmx_msr_low, vmx_msr_high;
2577 u32 ctl = ctl_min | ctl_opt;
2579 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2581 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2582 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2584 /* Ensure minimum (required) set of control bits are supported. */
2585 if (ctl_min & ~ctl)
2586 return -EIO;
2588 *result = ctl;
2589 return 0;
2592 static u64 adjust_vmx_controls64(u64 ctl_opt, u32 msr)
2594 u64 allowed;
2596 rdmsrl(msr, allowed);
2598 return ctl_opt & allowed;
2601 static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2602 struct vmx_capability *vmx_cap)
2604 u32 _pin_based_exec_control = 0;
2605 u32 _cpu_based_exec_control = 0;
2606 u32 _cpu_based_2nd_exec_control = 0;
2607 u64 _cpu_based_3rd_exec_control = 0;
2608 u32 _vmexit_control = 0;
2609 u32 _vmentry_control = 0;
2610 u64 basic_msr;
2611 u64 misc_msr;
2612 int i;
2615 * LOAD/SAVE_DEBUG_CONTROLS are absent because both are mandatory.
2616 * SAVE_IA32_PAT and SAVE_IA32_EFER are absent because KVM always
2617 * intercepts writes to PAT and EFER, i.e. never enables those controls.
2619 struct {
2620 u32 entry_control;
2621 u32 exit_control;
2622 } const vmcs_entry_exit_pairs[] = {
2623 { VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL },
2624 { VM_ENTRY_LOAD_IA32_PAT, VM_EXIT_LOAD_IA32_PAT },
2625 { VM_ENTRY_LOAD_IA32_EFER, VM_EXIT_LOAD_IA32_EFER },
2626 { VM_ENTRY_LOAD_BNDCFGS, VM_EXIT_CLEAR_BNDCFGS },
2627 { VM_ENTRY_LOAD_IA32_RTIT_CTL, VM_EXIT_CLEAR_IA32_RTIT_CTL },
2630 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2632 if (adjust_vmx_controls(KVM_REQUIRED_VMX_CPU_BASED_VM_EXEC_CONTROL,
2633 KVM_OPTIONAL_VMX_CPU_BASED_VM_EXEC_CONTROL,
2634 MSR_IA32_VMX_PROCBASED_CTLS,
2635 &_cpu_based_exec_control))
2636 return -EIO;
2637 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2638 if (adjust_vmx_controls(KVM_REQUIRED_VMX_SECONDARY_VM_EXEC_CONTROL,
2639 KVM_OPTIONAL_VMX_SECONDARY_VM_EXEC_CONTROL,
2640 MSR_IA32_VMX_PROCBASED_CTLS2,
2641 &_cpu_based_2nd_exec_control))
2642 return -EIO;
2644 if (!IS_ENABLED(CONFIG_KVM_INTEL_PROVE_VE))
2645 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_EPT_VIOLATION_VE;
2647 #ifndef CONFIG_X86_64
2648 if (!(_cpu_based_2nd_exec_control &
2649 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2650 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2651 #endif
2653 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2654 _cpu_based_2nd_exec_control &= ~(
2655 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2656 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2657 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2659 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2660 &vmx_cap->ept, &vmx_cap->vpid);
2662 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
2663 vmx_cap->ept) {
2664 pr_warn_once("EPT CAP should not exist if not support "
2665 "1-setting enable EPT VM-execution control\n");
2667 if (error_on_inconsistent_vmcs_config)
2668 return -EIO;
2670 vmx_cap->ept = 0;
2671 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_EPT_VIOLATION_VE;
2673 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2674 vmx_cap->vpid) {
2675 pr_warn_once("VPID CAP should not exist if not support "
2676 "1-setting enable VPID VM-execution control\n");
2678 if (error_on_inconsistent_vmcs_config)
2679 return -EIO;
2681 vmx_cap->vpid = 0;
2684 if (!cpu_has_sgx())
2685 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_ENCLS_EXITING;
2687 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_TERTIARY_CONTROLS)
2688 _cpu_based_3rd_exec_control =
2689 adjust_vmx_controls64(KVM_OPTIONAL_VMX_TERTIARY_VM_EXEC_CONTROL,
2690 MSR_IA32_VMX_PROCBASED_CTLS3);
2692 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_EXIT_CONTROLS,
2693 KVM_OPTIONAL_VMX_VM_EXIT_CONTROLS,
2694 MSR_IA32_VMX_EXIT_CTLS,
2695 &_vmexit_control))
2696 return -EIO;
2698 if (adjust_vmx_controls(KVM_REQUIRED_VMX_PIN_BASED_VM_EXEC_CONTROL,
2699 KVM_OPTIONAL_VMX_PIN_BASED_VM_EXEC_CONTROL,
2700 MSR_IA32_VMX_PINBASED_CTLS,
2701 &_pin_based_exec_control))
2702 return -EIO;
2704 if (cpu_has_broken_vmx_preemption_timer())
2705 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2706 if (!(_cpu_based_2nd_exec_control &
2707 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2708 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2710 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_ENTRY_CONTROLS,
2711 KVM_OPTIONAL_VMX_VM_ENTRY_CONTROLS,
2712 MSR_IA32_VMX_ENTRY_CTLS,
2713 &_vmentry_control))
2714 return -EIO;
2716 for (i = 0; i < ARRAY_SIZE(vmcs_entry_exit_pairs); i++) {
2717 u32 n_ctrl = vmcs_entry_exit_pairs[i].entry_control;
2718 u32 x_ctrl = vmcs_entry_exit_pairs[i].exit_control;
2720 if (!(_vmentry_control & n_ctrl) == !(_vmexit_control & x_ctrl))
2721 continue;
2723 pr_warn_once("Inconsistent VM-Entry/VM-Exit pair, entry = %x, exit = %x\n",
2724 _vmentry_control & n_ctrl, _vmexit_control & x_ctrl);
2726 if (error_on_inconsistent_vmcs_config)
2727 return -EIO;
2729 _vmentry_control &= ~n_ctrl;
2730 _vmexit_control &= ~x_ctrl;
2733 rdmsrl(MSR_IA32_VMX_BASIC, basic_msr);
2735 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2736 if (vmx_basic_vmcs_size(basic_msr) > PAGE_SIZE)
2737 return -EIO;
2739 #ifdef CONFIG_X86_64
2741 * KVM expects to be able to shove all legal physical addresses into
2742 * VMCS fields for 64-bit kernels, and per the SDM, "This bit is always
2743 * 0 for processors that support Intel 64 architecture".
2745 if (basic_msr & VMX_BASIC_32BIT_PHYS_ADDR_ONLY)
2746 return -EIO;
2747 #endif
2749 /* Require Write-Back (WB) memory type for VMCS accesses. */
2750 if (vmx_basic_vmcs_mem_type(basic_msr) != X86_MEMTYPE_WB)
2751 return -EIO;
2753 rdmsrl(MSR_IA32_VMX_MISC, misc_msr);
2755 vmcs_conf->basic = basic_msr;
2756 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2757 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2758 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2759 vmcs_conf->cpu_based_3rd_exec_ctrl = _cpu_based_3rd_exec_control;
2760 vmcs_conf->vmexit_ctrl = _vmexit_control;
2761 vmcs_conf->vmentry_ctrl = _vmentry_control;
2762 vmcs_conf->misc = misc_msr;
2764 #if IS_ENABLED(CONFIG_HYPERV)
2765 if (enlightened_vmcs)
2766 evmcs_sanitize_exec_ctrls(vmcs_conf);
2767 #endif
2769 return 0;
2772 static bool __kvm_is_vmx_supported(void)
2774 int cpu = smp_processor_id();
2776 if (!(cpuid_ecx(1) & feature_bit(VMX))) {
2777 pr_err("VMX not supported by CPU %d\n", cpu);
2778 return false;
2781 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2782 !this_cpu_has(X86_FEATURE_VMX)) {
2783 pr_err("VMX not enabled (by BIOS) in MSR_IA32_FEAT_CTL on CPU %d\n", cpu);
2784 return false;
2787 return true;
2790 static bool kvm_is_vmx_supported(void)
2792 bool supported;
2794 migrate_disable();
2795 supported = __kvm_is_vmx_supported();
2796 migrate_enable();
2798 return supported;
2801 int vmx_check_processor_compat(void)
2803 int cpu = raw_smp_processor_id();
2804 struct vmcs_config vmcs_conf;
2805 struct vmx_capability vmx_cap;
2807 if (!__kvm_is_vmx_supported())
2808 return -EIO;
2810 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0) {
2811 pr_err("Failed to setup VMCS config on CPU %d\n", cpu);
2812 return -EIO;
2814 if (nested)
2815 nested_vmx_setup_ctls_msrs(&vmcs_conf, vmx_cap.ept);
2816 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config))) {
2817 pr_err("Inconsistent VMCS config on CPU %d\n", cpu);
2818 return -EIO;
2820 return 0;
2823 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2825 u64 msr;
2827 cr4_set_bits(X86_CR4_VMXE);
2829 asm goto("1: vmxon %[vmxon_pointer]\n\t"
2830 _ASM_EXTABLE(1b, %l[fault])
2831 : : [vmxon_pointer] "m"(vmxon_pointer)
2832 : : fault);
2833 return 0;
2835 fault:
2836 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2837 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2838 cr4_clear_bits(X86_CR4_VMXE);
2840 return -EFAULT;
2843 int vmx_enable_virtualization_cpu(void)
2845 int cpu = raw_smp_processor_id();
2846 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2847 int r;
2849 if (cr4_read_shadow() & X86_CR4_VMXE)
2850 return -EBUSY;
2853 * This can happen if we hot-added a CPU but failed to allocate
2854 * VP assist page for it.
2856 if (kvm_is_using_evmcs() && !hv_get_vp_assist_page(cpu))
2857 return -EFAULT;
2859 intel_pt_handle_vmx(1);
2861 r = kvm_cpu_vmxon(phys_addr);
2862 if (r) {
2863 intel_pt_handle_vmx(0);
2864 return r;
2867 return 0;
2870 static void vmclear_local_loaded_vmcss(void)
2872 int cpu = raw_smp_processor_id();
2873 struct loaded_vmcs *v, *n;
2875 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2876 loaded_vmcss_on_cpu_link)
2877 __loaded_vmcs_clear(v);
2880 void vmx_disable_virtualization_cpu(void)
2882 vmclear_local_loaded_vmcss();
2884 if (kvm_cpu_vmxoff())
2885 kvm_spurious_fault();
2887 hv_reset_evmcs();
2889 intel_pt_handle_vmx(0);
2892 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2894 int node = cpu_to_node(cpu);
2895 struct page *pages;
2896 struct vmcs *vmcs;
2898 pages = __alloc_pages_node(node, flags, 0);
2899 if (!pages)
2900 return NULL;
2901 vmcs = page_address(pages);
2902 memset(vmcs, 0, vmx_basic_vmcs_size(vmcs_config.basic));
2904 /* KVM supports Enlightened VMCS v1 only */
2905 if (kvm_is_using_evmcs())
2906 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2907 else
2908 vmcs->hdr.revision_id = vmx_basic_vmcs_revision_id(vmcs_config.basic);
2910 if (shadow)
2911 vmcs->hdr.shadow_vmcs = 1;
2912 return vmcs;
2915 void free_vmcs(struct vmcs *vmcs)
2917 free_page((unsigned long)vmcs);
2921 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2923 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2925 if (!loaded_vmcs->vmcs)
2926 return;
2927 loaded_vmcs_clear(loaded_vmcs);
2928 free_vmcs(loaded_vmcs->vmcs);
2929 loaded_vmcs->vmcs = NULL;
2930 if (loaded_vmcs->msr_bitmap)
2931 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2932 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2935 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2937 loaded_vmcs->vmcs = alloc_vmcs(false);
2938 if (!loaded_vmcs->vmcs)
2939 return -ENOMEM;
2941 vmcs_clear(loaded_vmcs->vmcs);
2943 loaded_vmcs->shadow_vmcs = NULL;
2944 loaded_vmcs->hv_timer_soft_disabled = false;
2945 loaded_vmcs->cpu = -1;
2946 loaded_vmcs->launched = 0;
2948 if (cpu_has_vmx_msr_bitmap()) {
2949 loaded_vmcs->msr_bitmap = (unsigned long *)
2950 __get_free_page(GFP_KERNEL_ACCOUNT);
2951 if (!loaded_vmcs->msr_bitmap)
2952 goto out_vmcs;
2953 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2956 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2957 memset(&loaded_vmcs->controls_shadow, 0,
2958 sizeof(struct vmcs_controls_shadow));
2960 return 0;
2962 out_vmcs:
2963 free_loaded_vmcs(loaded_vmcs);
2964 return -ENOMEM;
2967 static void free_kvm_area(void)
2969 int cpu;
2971 for_each_possible_cpu(cpu) {
2972 free_vmcs(per_cpu(vmxarea, cpu));
2973 per_cpu(vmxarea, cpu) = NULL;
2977 static __init int alloc_kvm_area(void)
2979 int cpu;
2981 for_each_possible_cpu(cpu) {
2982 struct vmcs *vmcs;
2984 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2985 if (!vmcs) {
2986 free_kvm_area();
2987 return -ENOMEM;
2991 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2992 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2993 * revision_id reported by MSR_IA32_VMX_BASIC.
2995 * However, even though not explicitly documented by
2996 * TLFS, VMXArea passed as VMXON argument should
2997 * still be marked with revision_id reported by
2998 * physical CPU.
3000 if (kvm_is_using_evmcs())
3001 vmcs->hdr.revision_id = vmx_basic_vmcs_revision_id(vmcs_config.basic);
3003 per_cpu(vmxarea, cpu) = vmcs;
3005 return 0;
3008 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
3009 struct kvm_segment *save)
3011 if (!emulate_invalid_guest_state) {
3013 * CS and SS RPL should be equal during guest entry according
3014 * to VMX spec, but in reality it is not always so. Since vcpu
3015 * is in the middle of the transition from real mode to
3016 * protected mode it is safe to assume that RPL 0 is a good
3017 * default value.
3019 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
3020 save->selector &= ~SEGMENT_RPL_MASK;
3021 save->dpl = save->selector & SEGMENT_RPL_MASK;
3022 save->s = 1;
3024 __vmx_set_segment(vcpu, save, seg);
3027 static void enter_pmode(struct kvm_vcpu *vcpu)
3029 unsigned long flags;
3030 struct vcpu_vmx *vmx = to_vmx(vcpu);
3033 * Update real mode segment cache. It may be not up-to-date if segment
3034 * register was written while vcpu was in a guest mode.
3036 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3037 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3038 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3039 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3040 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3041 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3043 vmx->rmode.vm86_active = 0;
3045 __vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3047 flags = vmcs_readl(GUEST_RFLAGS);
3048 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3049 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3050 vmcs_writel(GUEST_RFLAGS, flags);
3052 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
3053 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
3055 vmx_update_exception_bitmap(vcpu);
3057 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3058 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3059 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3060 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3061 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3062 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3065 static void fix_rmode_seg(int seg, struct kvm_segment *save)
3067 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3068 struct kvm_segment var = *save;
3070 var.dpl = 0x3;
3071 if (seg == VCPU_SREG_CS)
3072 var.type = 0x3;
3074 if (!emulate_invalid_guest_state) {
3075 var.selector = var.base >> 4;
3076 var.base = var.base & 0xffff0;
3077 var.limit = 0xffff;
3078 var.g = 0;
3079 var.db = 0;
3080 var.present = 1;
3081 var.s = 1;
3082 var.l = 0;
3083 var.unusable = 0;
3084 var.type = 0x3;
3085 var.avl = 0;
3086 if (save->base & 0xf)
3087 pr_warn_once("segment base is not paragraph aligned "
3088 "when entering protected mode (seg=%d)", seg);
3091 vmcs_write16(sf->selector, var.selector);
3092 vmcs_writel(sf->base, var.base);
3093 vmcs_write32(sf->limit, var.limit);
3094 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
3097 static void enter_rmode(struct kvm_vcpu *vcpu)
3099 unsigned long flags;
3100 struct vcpu_vmx *vmx = to_vmx(vcpu);
3101 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
3104 * KVM should never use VM86 to virtualize Real Mode when L2 is active,
3105 * as using VM86 is unnecessary if unrestricted guest is enabled, and
3106 * if unrestricted guest is disabled, VM-Enter (from L1) with CR0.PG=0
3107 * should VM-Fail and KVM should reject userspace attempts to stuff
3108 * CR0.PG=0 when L2 is active.
3110 WARN_ON_ONCE(is_guest_mode(vcpu));
3112 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3113 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3114 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3115 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3116 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3117 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3118 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3120 vmx->rmode.vm86_active = 1;
3122 vmx_segment_cache_clear(vmx);
3124 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
3125 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
3126 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3128 flags = vmcs_readl(GUEST_RFLAGS);
3129 vmx->rmode.save_rflags = flags;
3131 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3133 vmcs_writel(GUEST_RFLAGS, flags);
3134 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
3135 vmx_update_exception_bitmap(vcpu);
3137 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3138 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3139 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3140 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3141 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3142 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3145 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
3147 struct vcpu_vmx *vmx = to_vmx(vcpu);
3149 /* Nothing to do if hardware doesn't support EFER. */
3150 if (!vmx_find_uret_msr(vmx, MSR_EFER))
3151 return 0;
3153 vcpu->arch.efer = efer;
3154 #ifdef CONFIG_X86_64
3155 if (efer & EFER_LMA)
3156 vm_entry_controls_setbit(vmx, VM_ENTRY_IA32E_MODE);
3157 else
3158 vm_entry_controls_clearbit(vmx, VM_ENTRY_IA32E_MODE);
3159 #else
3160 if (KVM_BUG_ON(efer & EFER_LMA, vcpu->kvm))
3161 return 1;
3162 #endif
3164 vmx_setup_uret_msrs(vmx);
3165 return 0;
3168 #ifdef CONFIG_X86_64
3170 static void enter_lmode(struct kvm_vcpu *vcpu)
3172 u32 guest_tr_ar;
3174 vmx_segment_cache_clear(to_vmx(vcpu));
3176 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3177 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
3178 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3179 __func__);
3180 vmcs_write32(GUEST_TR_AR_BYTES,
3181 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
3182 | VMX_AR_TYPE_BUSY_64_TSS);
3184 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3187 static void exit_lmode(struct kvm_vcpu *vcpu)
3189 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3192 #endif
3194 void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
3196 struct vcpu_vmx *vmx = to_vmx(vcpu);
3199 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
3200 * the CPU is not required to invalidate guest-physical mappings on
3201 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
3202 * associated with the root EPT structure and not any particular VPID
3203 * (INVVPID also isn't required to invalidate guest-physical mappings).
3205 if (enable_ept) {
3206 ept_sync_global();
3207 } else if (enable_vpid) {
3208 if (cpu_has_vmx_invvpid_global()) {
3209 vpid_sync_vcpu_global();
3210 } else {
3211 vpid_sync_vcpu_single(vmx->vpid);
3212 vpid_sync_vcpu_single(vmx->nested.vpid02);
3217 static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu)
3219 if (is_guest_mode(vcpu))
3220 return nested_get_vpid02(vcpu);
3221 return to_vmx(vcpu)->vpid;
3224 void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
3226 struct kvm_mmu *mmu = vcpu->arch.mmu;
3227 u64 root_hpa = mmu->root.hpa;
3229 /* No flush required if the current context is invalid. */
3230 if (!VALID_PAGE(root_hpa))
3231 return;
3233 if (enable_ept)
3234 ept_sync_context(construct_eptp(vcpu, root_hpa,
3235 mmu->root_role.level));
3236 else
3237 vpid_sync_context(vmx_get_current_vpid(vcpu));
3240 void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3243 * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in
3244 * vmx_flush_tlb_guest() for an explanation of why this is ok.
3246 vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
3249 void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3252 * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
3253 * vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit are
3254 * required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3255 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3256 * i.e. no explicit INVVPID is necessary.
3258 vpid_sync_context(vmx_get_current_vpid(vcpu));
3261 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3263 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3265 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3266 return;
3268 if (is_pae_paging(vcpu)) {
3269 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3270 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3271 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3272 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3276 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3278 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3280 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3281 return;
3283 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3284 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3285 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3286 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3288 kvm_register_mark_available(vcpu, VCPU_EXREG_PDPTR);
3291 #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \
3292 CPU_BASED_CR3_STORE_EXITING)
3294 bool vmx_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3296 if (is_guest_mode(vcpu))
3297 return nested_guest_cr0_valid(vcpu, cr0);
3299 if (to_vmx(vcpu)->nested.vmxon)
3300 return nested_host_cr0_valid(vcpu, cr0);
3302 return true;
3305 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3307 struct vcpu_vmx *vmx = to_vmx(vcpu);
3308 unsigned long hw_cr0, old_cr0_pg;
3309 u32 tmp;
3311 old_cr0_pg = kvm_read_cr0_bits(vcpu, X86_CR0_PG);
3313 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3314 if (enable_unrestricted_guest)
3315 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3316 else {
3317 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3318 if (!enable_ept)
3319 hw_cr0 |= X86_CR0_WP;
3321 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3322 enter_pmode(vcpu);
3324 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3325 enter_rmode(vcpu);
3328 vmcs_writel(CR0_READ_SHADOW, cr0);
3329 vmcs_writel(GUEST_CR0, hw_cr0);
3330 vcpu->arch.cr0 = cr0;
3331 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3333 #ifdef CONFIG_X86_64
3334 if (vcpu->arch.efer & EFER_LME) {
3335 if (!old_cr0_pg && (cr0 & X86_CR0_PG))
3336 enter_lmode(vcpu);
3337 else if (old_cr0_pg && !(cr0 & X86_CR0_PG))
3338 exit_lmode(vcpu);
3340 #endif
3342 if (enable_ept && !enable_unrestricted_guest) {
3344 * Ensure KVM has an up-to-date snapshot of the guest's CR3. If
3345 * the below code _enables_ CR3 exiting, vmx_cache_reg() will
3346 * (correctly) stop reading vmcs.GUEST_CR3 because it thinks
3347 * KVM's CR3 is installed.
3349 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3350 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3353 * When running with EPT but not unrestricted guest, KVM must
3354 * intercept CR3 accesses when paging is _disabled_. This is
3355 * necessary because restricted guests can't actually run with
3356 * paging disabled, and so KVM stuffs its own CR3 in order to
3357 * run the guest when identity mapped page tables.
3359 * Do _NOT_ check the old CR0.PG, e.g. to optimize away the
3360 * update, it may be stale with respect to CR3 interception,
3361 * e.g. after nested VM-Enter.
3363 * Lastly, honor L1's desires, i.e. intercept CR3 loads and/or
3364 * stores to forward them to L1, even if KVM does not need to
3365 * intercept them to preserve its identity mapped page tables.
3367 if (!(cr0 & X86_CR0_PG)) {
3368 exec_controls_setbit(vmx, CR3_EXITING_BITS);
3369 } else if (!is_guest_mode(vcpu)) {
3370 exec_controls_clearbit(vmx, CR3_EXITING_BITS);
3371 } else {
3372 tmp = exec_controls_get(vmx);
3373 tmp &= ~CR3_EXITING_BITS;
3374 tmp |= get_vmcs12(vcpu)->cpu_based_vm_exec_control & CR3_EXITING_BITS;
3375 exec_controls_set(vmx, tmp);
3378 /* Note, vmx_set_cr4() consumes the new vcpu->arch.cr0. */
3379 if ((old_cr0_pg ^ cr0) & X86_CR0_PG)
3380 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3383 * When !CR0_PG -> CR0_PG, vcpu->arch.cr3 becomes active, but
3384 * GUEST_CR3 is still vmx->ept_identity_map_addr if EPT + !URG.
3386 if (!(old_cr0_pg & X86_CR0_PG) && (cr0 & X86_CR0_PG))
3387 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
3390 /* depends on vcpu->arch.cr0 to be set to a new value */
3391 vmx->emulation_required = vmx_emulation_required(vcpu);
3394 static int vmx_get_max_ept_level(void)
3396 if (cpu_has_vmx_ept_5levels())
3397 return 5;
3398 return 4;
3401 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3403 u64 eptp = VMX_EPTP_MT_WB;
3405 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3407 if (enable_ept_ad_bits &&
3408 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3409 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3410 eptp |= root_hpa;
3412 return eptp;
3415 void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3417 struct kvm *kvm = vcpu->kvm;
3418 bool update_guest_cr3 = true;
3419 unsigned long guest_cr3;
3420 u64 eptp;
3422 if (enable_ept) {
3423 eptp = construct_eptp(vcpu, root_hpa, root_level);
3424 vmcs_write64(EPT_POINTER, eptp);
3426 hv_track_root_tdp(vcpu, root_hpa);
3428 if (!enable_unrestricted_guest && !is_paging(vcpu))
3429 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3430 else if (kvm_register_is_dirty(vcpu, VCPU_EXREG_CR3))
3431 guest_cr3 = vcpu->arch.cr3;
3432 else /* vmcs.GUEST_CR3 is already up-to-date. */
3433 update_guest_cr3 = false;
3434 vmx_ept_load_pdptrs(vcpu);
3435 } else {
3436 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu) |
3437 kvm_get_active_cr3_lam_bits(vcpu);
3440 if (update_guest_cr3)
3441 vmcs_writel(GUEST_CR3, guest_cr3);
3444 bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3447 * We operate under the default treatment of SMM, so VMX cannot be
3448 * enabled under SMM. Note, whether or not VMXE is allowed at all,
3449 * i.e. is a reserved bit, is handled by common x86 code.
3451 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3452 return false;
3454 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3455 return false;
3457 return true;
3460 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3462 unsigned long old_cr4 = kvm_read_cr4(vcpu);
3463 struct vcpu_vmx *vmx = to_vmx(vcpu);
3464 unsigned long hw_cr4;
3467 * Pass through host's Machine Check Enable value to hw_cr4, which
3468 * is in force while we are in guest mode. Do not let guests control
3469 * this bit, even if host CR4.MCE == 0.
3471 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3472 if (enable_unrestricted_guest)
3473 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3474 else if (vmx->rmode.vm86_active)
3475 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3476 else
3477 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3479 if (vmx_umip_emulated()) {
3480 if (cr4 & X86_CR4_UMIP) {
3481 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3482 hw_cr4 &= ~X86_CR4_UMIP;
3483 } else if (!is_guest_mode(vcpu) ||
3484 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3485 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3489 vcpu->arch.cr4 = cr4;
3490 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3492 if (!enable_unrestricted_guest) {
3493 if (enable_ept) {
3494 if (!is_paging(vcpu)) {
3495 hw_cr4 &= ~X86_CR4_PAE;
3496 hw_cr4 |= X86_CR4_PSE;
3497 } else if (!(cr4 & X86_CR4_PAE)) {
3498 hw_cr4 &= ~X86_CR4_PAE;
3503 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3504 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3505 * to be manually disabled when guest switches to non-paging
3506 * mode.
3508 * If !enable_unrestricted_guest, the CPU is always running
3509 * with CR0.PG=1 and CR4 needs to be modified.
3510 * If enable_unrestricted_guest, the CPU automatically
3511 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3513 if (!is_paging(vcpu))
3514 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3517 vmcs_writel(CR4_READ_SHADOW, cr4);
3518 vmcs_writel(GUEST_CR4, hw_cr4);
3520 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3521 kvm_update_cpuid_runtime(vcpu);
3524 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3526 struct vcpu_vmx *vmx = to_vmx(vcpu);
3527 u32 ar;
3529 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3530 *var = vmx->rmode.segs[seg];
3531 if (seg == VCPU_SREG_TR
3532 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3533 return;
3534 var->base = vmx_read_guest_seg_base(vmx, seg);
3535 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3536 return;
3538 var->base = vmx_read_guest_seg_base(vmx, seg);
3539 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3540 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3541 ar = vmx_read_guest_seg_ar(vmx, seg);
3542 var->unusable = (ar >> 16) & 1;
3543 var->type = ar & 15;
3544 var->s = (ar >> 4) & 1;
3545 var->dpl = (ar >> 5) & 3;
3547 * Some userspaces do not preserve unusable property. Since usable
3548 * segment has to be present according to VMX spec we can use present
3549 * property to amend userspace bug by making unusable segment always
3550 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3551 * segment as unusable.
3553 var->present = !var->unusable;
3554 var->avl = (ar >> 12) & 1;
3555 var->l = (ar >> 13) & 1;
3556 var->db = (ar >> 14) & 1;
3557 var->g = (ar >> 15) & 1;
3560 u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3562 struct kvm_segment s;
3564 if (to_vmx(vcpu)->rmode.vm86_active) {
3565 vmx_get_segment(vcpu, &s, seg);
3566 return s.base;
3568 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3571 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3573 struct vcpu_vmx *vmx = to_vmx(vcpu);
3575 if (unlikely(vmx->rmode.vm86_active))
3576 return 0;
3577 else {
3578 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3579 return VMX_AR_DPL(ar);
3583 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3585 u32 ar;
3587 ar = var->type & 15;
3588 ar |= (var->s & 1) << 4;
3589 ar |= (var->dpl & 3) << 5;
3590 ar |= (var->present & 1) << 7;
3591 ar |= (var->avl & 1) << 12;
3592 ar |= (var->l & 1) << 13;
3593 ar |= (var->db & 1) << 14;
3594 ar |= (var->g & 1) << 15;
3595 ar |= (var->unusable || !var->present) << 16;
3597 return ar;
3600 void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3602 struct vcpu_vmx *vmx = to_vmx(vcpu);
3603 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3605 vmx_segment_cache_clear(vmx);
3607 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3608 vmx->rmode.segs[seg] = *var;
3609 if (seg == VCPU_SREG_TR)
3610 vmcs_write16(sf->selector, var->selector);
3611 else if (var->s)
3612 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3613 return;
3616 vmcs_writel(sf->base, var->base);
3617 vmcs_write32(sf->limit, var->limit);
3618 vmcs_write16(sf->selector, var->selector);
3621 * Fix the "Accessed" bit in AR field of segment registers for older
3622 * qemu binaries.
3623 * IA32 arch specifies that at the time of processor reset the
3624 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3625 * is setting it to 0 in the userland code. This causes invalid guest
3626 * state vmexit when "unrestricted guest" mode is turned on.
3627 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3628 * tree. Newer qemu binaries with that qemu fix would not need this
3629 * kvm hack.
3631 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3632 var->type |= 0x1; /* Accessed */
3634 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3637 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3639 __vmx_set_segment(vcpu, var, seg);
3641 to_vmx(vcpu)->emulation_required = vmx_emulation_required(vcpu);
3644 void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3646 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3648 *db = (ar >> 14) & 1;
3649 *l = (ar >> 13) & 1;
3652 void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3654 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3655 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3658 void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3660 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3661 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3664 void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3666 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3667 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3670 void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3672 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3673 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3676 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3678 struct kvm_segment var;
3679 u32 ar;
3681 vmx_get_segment(vcpu, &var, seg);
3682 var.dpl = 0x3;
3683 if (seg == VCPU_SREG_CS)
3684 var.type = 0x3;
3685 ar = vmx_segment_access_rights(&var);
3687 if (var.base != (var.selector << 4))
3688 return false;
3689 if (var.limit != 0xffff)
3690 return false;
3691 if (ar != 0xf3)
3692 return false;
3694 return true;
3697 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3699 struct kvm_segment cs;
3700 unsigned int cs_rpl;
3702 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3703 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3705 if (cs.unusable)
3706 return false;
3707 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3708 return false;
3709 if (!cs.s)
3710 return false;
3711 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3712 if (cs.dpl > cs_rpl)
3713 return false;
3714 } else {
3715 if (cs.dpl != cs_rpl)
3716 return false;
3718 if (!cs.present)
3719 return false;
3721 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3722 return true;
3725 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3727 struct kvm_segment ss;
3728 unsigned int ss_rpl;
3730 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3731 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3733 if (ss.unusable)
3734 return true;
3735 if (ss.type != 3 && ss.type != 7)
3736 return false;
3737 if (!ss.s)
3738 return false;
3739 if (ss.dpl != ss_rpl) /* DPL != RPL */
3740 return false;
3741 if (!ss.present)
3742 return false;
3744 return true;
3747 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3749 struct kvm_segment var;
3750 unsigned int rpl;
3752 vmx_get_segment(vcpu, &var, seg);
3753 rpl = var.selector & SEGMENT_RPL_MASK;
3755 if (var.unusable)
3756 return true;
3757 if (!var.s)
3758 return false;
3759 if (!var.present)
3760 return false;
3761 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3762 if (var.dpl < rpl) /* DPL < RPL */
3763 return false;
3766 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3767 * rights flags
3769 return true;
3772 static bool tr_valid(struct kvm_vcpu *vcpu)
3774 struct kvm_segment tr;
3776 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3778 if (tr.unusable)
3779 return false;
3780 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3781 return false;
3782 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3783 return false;
3784 if (!tr.present)
3785 return false;
3787 return true;
3790 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3792 struct kvm_segment ldtr;
3794 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3796 if (ldtr.unusable)
3797 return true;
3798 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3799 return false;
3800 if (ldtr.type != 2)
3801 return false;
3802 if (!ldtr.present)
3803 return false;
3805 return true;
3808 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3810 struct kvm_segment cs, ss;
3812 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3813 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3815 return ((cs.selector & SEGMENT_RPL_MASK) ==
3816 (ss.selector & SEGMENT_RPL_MASK));
3820 * Check if guest state is valid. Returns true if valid, false if
3821 * not.
3822 * We assume that registers are always usable
3824 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3826 /* real mode guest state checks */
3827 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3828 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3829 return false;
3830 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3831 return false;
3832 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3833 return false;
3834 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3835 return false;
3836 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3837 return false;
3838 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3839 return false;
3840 } else {
3841 /* protected mode guest state checks */
3842 if (!cs_ss_rpl_check(vcpu))
3843 return false;
3844 if (!code_segment_valid(vcpu))
3845 return false;
3846 if (!stack_segment_valid(vcpu))
3847 return false;
3848 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3849 return false;
3850 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3851 return false;
3852 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3853 return false;
3854 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3855 return false;
3856 if (!tr_valid(vcpu))
3857 return false;
3858 if (!ldtr_valid(vcpu))
3859 return false;
3861 /* TODO:
3862 * - Add checks on RIP
3863 * - Add checks on RFLAGS
3866 return true;
3869 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3871 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3872 u16 data;
3873 int i;
3875 for (i = 0; i < 3; i++) {
3876 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3877 return -EFAULT;
3880 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3881 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3882 return -EFAULT;
3884 data = ~0;
3885 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3886 return -EFAULT;
3888 return 0;
3891 static int init_rmode_identity_map(struct kvm *kvm)
3893 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3894 int i, r = 0;
3895 void __user *uaddr;
3896 u32 tmp;
3898 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3899 mutex_lock(&kvm->slots_lock);
3901 if (likely(kvm_vmx->ept_identity_pagetable_done))
3902 goto out;
3904 if (!kvm_vmx->ept_identity_map_addr)
3905 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3907 uaddr = __x86_set_memory_region(kvm,
3908 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3909 kvm_vmx->ept_identity_map_addr,
3910 PAGE_SIZE);
3911 if (IS_ERR(uaddr)) {
3912 r = PTR_ERR(uaddr);
3913 goto out;
3916 /* Set up identity-mapping pagetable for EPT in real mode */
3917 for (i = 0; i < (PAGE_SIZE / sizeof(tmp)); i++) {
3918 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3919 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3920 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3921 r = -EFAULT;
3922 goto out;
3925 kvm_vmx->ept_identity_pagetable_done = true;
3927 out:
3928 mutex_unlock(&kvm->slots_lock);
3929 return r;
3932 static void seg_setup(int seg)
3934 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3935 unsigned int ar;
3937 vmcs_write16(sf->selector, 0);
3938 vmcs_writel(sf->base, 0);
3939 vmcs_write32(sf->limit, 0xffff);
3940 ar = 0x93;
3941 if (seg == VCPU_SREG_CS)
3942 ar |= 0x08; /* code segment */
3944 vmcs_write32(sf->ar_bytes, ar);
3947 int allocate_vpid(void)
3949 int vpid;
3951 if (!enable_vpid)
3952 return 0;
3953 spin_lock(&vmx_vpid_lock);
3954 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3955 if (vpid < VMX_NR_VPIDS)
3956 __set_bit(vpid, vmx_vpid_bitmap);
3957 else
3958 vpid = 0;
3959 spin_unlock(&vmx_vpid_lock);
3960 return vpid;
3963 void free_vpid(int vpid)
3965 if (!enable_vpid || vpid == 0)
3966 return;
3967 spin_lock(&vmx_vpid_lock);
3968 __clear_bit(vpid, vmx_vpid_bitmap);
3969 spin_unlock(&vmx_vpid_lock);
3972 static void vmx_msr_bitmap_l01_changed(struct vcpu_vmx *vmx)
3975 * When KVM is a nested hypervisor on top of Hyper-V and uses
3976 * 'Enlightened MSR Bitmap' feature L0 needs to know that MSR
3977 * bitmap has changed.
3979 if (kvm_is_using_evmcs()) {
3980 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
3982 if (evmcs->hv_enlightenments_control.msr_bitmap)
3983 evmcs->hv_clean_fields &=
3984 ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
3987 vmx->nested.force_msr_bitmap_recalc = true;
3990 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3992 struct vcpu_vmx *vmx = to_vmx(vcpu);
3993 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3994 int idx;
3996 if (!cpu_has_vmx_msr_bitmap())
3997 return;
3999 vmx_msr_bitmap_l01_changed(vmx);
4002 * Mark the desired intercept state in shadow bitmap, this is needed
4003 * for resync when the MSR filters change.
4005 idx = vmx_get_passthrough_msr_slot(msr);
4006 if (idx >= 0) {
4007 if (type & MSR_TYPE_R)
4008 clear_bit(idx, vmx->shadow_msr_intercept.read);
4009 if (type & MSR_TYPE_W)
4010 clear_bit(idx, vmx->shadow_msr_intercept.write);
4013 if ((type & MSR_TYPE_R) &&
4014 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
4015 vmx_set_msr_bitmap_read(msr_bitmap, msr);
4016 type &= ~MSR_TYPE_R;
4019 if ((type & MSR_TYPE_W) &&
4020 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
4021 vmx_set_msr_bitmap_write(msr_bitmap, msr);
4022 type &= ~MSR_TYPE_W;
4025 if (type & MSR_TYPE_R)
4026 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
4028 if (type & MSR_TYPE_W)
4029 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
4032 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
4034 struct vcpu_vmx *vmx = to_vmx(vcpu);
4035 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
4036 int idx;
4038 if (!cpu_has_vmx_msr_bitmap())
4039 return;
4041 vmx_msr_bitmap_l01_changed(vmx);
4044 * Mark the desired intercept state in shadow bitmap, this is needed
4045 * for resync when the MSR filter changes.
4047 idx = vmx_get_passthrough_msr_slot(msr);
4048 if (idx >= 0) {
4049 if (type & MSR_TYPE_R)
4050 set_bit(idx, vmx->shadow_msr_intercept.read);
4051 if (type & MSR_TYPE_W)
4052 set_bit(idx, vmx->shadow_msr_intercept.write);
4055 if (type & MSR_TYPE_R)
4056 vmx_set_msr_bitmap_read(msr_bitmap, msr);
4058 if (type & MSR_TYPE_W)
4059 vmx_set_msr_bitmap_write(msr_bitmap, msr);
4062 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu)
4065 * x2APIC indices for 64-bit accesses into the RDMSR and WRMSR halves
4066 * of the MSR bitmap. KVM emulates APIC registers up through 0x3f0,
4067 * i.e. MSR 0x83f, and so only needs to dynamically manipulate 64 bits.
4069 const int read_idx = APIC_BASE_MSR / BITS_PER_LONG_LONG;
4070 const int write_idx = read_idx + (0x800 / sizeof(u64));
4071 struct vcpu_vmx *vmx = to_vmx(vcpu);
4072 u64 *msr_bitmap = (u64 *)vmx->vmcs01.msr_bitmap;
4073 u8 mode;
4075 if (!cpu_has_vmx_msr_bitmap() || WARN_ON_ONCE(!lapic_in_kernel(vcpu)))
4076 return;
4078 if (cpu_has_secondary_exec_ctrls() &&
4079 (secondary_exec_controls_get(vmx) &
4080 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
4081 mode = MSR_BITMAP_MODE_X2APIC;
4082 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
4083 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
4084 } else {
4085 mode = 0;
4088 if (mode == vmx->x2apic_msr_bitmap_mode)
4089 return;
4091 vmx->x2apic_msr_bitmap_mode = mode;
4094 * Reset the bitmap for MSRs 0x800 - 0x83f. Leave AMD's uber-extended
4095 * registers (0x840 and above) intercepted, KVM doesn't support them.
4096 * Intercept all writes by default and poke holes as needed. Pass
4097 * through reads for all valid registers by default in x2APIC+APICv
4098 * mode, only the current timer count needs on-demand emulation by KVM.
4100 if (mode & MSR_BITMAP_MODE_X2APIC_APICV)
4101 msr_bitmap[read_idx] = ~kvm_lapic_readable_reg_mask(vcpu->arch.apic);
4102 else
4103 msr_bitmap[read_idx] = ~0ull;
4104 msr_bitmap[write_idx] = ~0ull;
4107 * TPR reads and writes can be virtualized even if virtual interrupt
4108 * delivery is not in use.
4110 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
4111 !(mode & MSR_BITMAP_MODE_X2APIC));
4113 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
4114 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
4115 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
4116 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
4117 if (enable_ipiv)
4118 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_ICR), MSR_TYPE_RW);
4122 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
4124 struct vcpu_vmx *vmx = to_vmx(vcpu);
4125 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
4126 u32 i;
4128 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
4129 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
4130 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
4131 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
4132 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++) {
4133 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
4134 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
4138 void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
4140 struct vcpu_vmx *vmx = to_vmx(vcpu);
4141 u32 i;
4143 if (!cpu_has_vmx_msr_bitmap())
4144 return;
4147 * Redo intercept permissions for MSRs that KVM is passing through to
4148 * the guest. Disabling interception will check the new MSR filter and
4149 * ensure that KVM enables interception if usersepace wants to filter
4150 * the MSR. MSRs that KVM is already intercepting don't need to be
4151 * refreshed since KVM is going to intercept them regardless of what
4152 * userspace wants.
4154 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
4155 u32 msr = vmx_possible_passthrough_msrs[i];
4157 if (!test_bit(i, vmx->shadow_msr_intercept.read))
4158 vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_R);
4160 if (!test_bit(i, vmx->shadow_msr_intercept.write))
4161 vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_W);
4164 /* PT MSRs can be passed through iff PT is exposed to the guest. */
4165 if (vmx_pt_mode_is_host_guest())
4166 pt_update_intercept_for_msr(vcpu);
4169 static inline void kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
4170 int pi_vec)
4172 #ifdef CONFIG_SMP
4173 if (vcpu->mode == IN_GUEST_MODE) {
4175 * The vector of the virtual has already been set in the PIR.
4176 * Send a notification event to deliver the virtual interrupt
4177 * unless the vCPU is the currently running vCPU, i.e. the
4178 * event is being sent from a fastpath VM-Exit handler, in
4179 * which case the PIR will be synced to the vIRR before
4180 * re-entering the guest.
4182 * When the target is not the running vCPU, the following
4183 * possibilities emerge:
4185 * Case 1: vCPU stays in non-root mode. Sending a notification
4186 * event posts the interrupt to the vCPU.
4188 * Case 2: vCPU exits to root mode and is still runnable. The
4189 * PIR will be synced to the vIRR before re-entering the guest.
4190 * Sending a notification event is ok as the host IRQ handler
4191 * will ignore the spurious event.
4193 * Case 3: vCPU exits to root mode and is blocked. vcpu_block()
4194 * has already synced PIR to vIRR and never blocks the vCPU if
4195 * the vIRR is not empty. Therefore, a blocked vCPU here does
4196 * not wait for any requested interrupts in PIR, and sending a
4197 * notification event also results in a benign, spurious event.
4200 if (vcpu != kvm_get_running_vcpu())
4201 __apic_send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
4202 return;
4204 #endif
4206 * The vCPU isn't in the guest; wake the vCPU in case it is blocking,
4207 * otherwise do nothing as KVM will grab the highest priority pending
4208 * IRQ via ->sync_pir_to_irr() in vcpu_enter_guest().
4210 kvm_vcpu_wake_up(vcpu);
4213 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4214 int vector)
4216 struct vcpu_vmx *vmx = to_vmx(vcpu);
4219 * DO NOT query the vCPU's vmcs12, as vmcs12 is dynamically allocated
4220 * and freed, and must not be accessed outside of vcpu->mutex. The
4221 * vCPU's cached PI NV is valid if and only if posted interrupts
4222 * enabled in its vmcs12, i.e. checking the vector also checks that
4223 * L1 has enabled posted interrupts for L2.
4225 if (is_guest_mode(vcpu) &&
4226 vector == vmx->nested.posted_intr_nv) {
4228 * If a posted intr is not recognized by hardware,
4229 * we will accomplish it in the next vmentry.
4231 vmx->nested.pi_pending = true;
4232 kvm_make_request(KVM_REQ_EVENT, vcpu);
4235 * This pairs with the smp_mb_*() after setting vcpu->mode in
4236 * vcpu_enter_guest() to guarantee the vCPU sees the event
4237 * request if triggering a posted interrupt "fails" because
4238 * vcpu->mode != IN_GUEST_MODE. The extra barrier is needed as
4239 * the smb_wmb() in kvm_make_request() only ensures everything
4240 * done before making the request is visible when the request
4241 * is visible, it doesn't ensure ordering between the store to
4242 * vcpu->requests and the load from vcpu->mode.
4244 smp_mb__after_atomic();
4246 /* the PIR and ON have been set by L1. */
4247 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_NESTED_VECTOR);
4248 return 0;
4250 return -1;
4253 * Send interrupt to vcpu via posted interrupt way.
4254 * 1. If target vcpu is running(non-root mode), send posted interrupt
4255 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4256 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4257 * interrupt from PIR in next vmentry.
4259 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4261 struct vcpu_vmx *vmx = to_vmx(vcpu);
4262 int r;
4264 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4265 if (!r)
4266 return 0;
4268 /* Note, this is called iff the local APIC is in-kernel. */
4269 if (!vcpu->arch.apic->apicv_active)
4270 return -1;
4272 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4273 return 0;
4275 /* If a previous notification has sent the IPI, nothing to do. */
4276 if (pi_test_and_set_on(&vmx->pi_desc))
4277 return 0;
4280 * The implied barrier in pi_test_and_set_on() pairs with the smp_mb_*()
4281 * after setting vcpu->mode in vcpu_enter_guest(), thus the vCPU is
4282 * guaranteed to see PID.ON=1 and sync the PIR to IRR if triggering a
4283 * posted interrupt "fails" because vcpu->mode != IN_GUEST_MODE.
4285 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_VECTOR);
4286 return 0;
4289 void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
4290 int trig_mode, int vector)
4292 struct kvm_vcpu *vcpu = apic->vcpu;
4294 if (vmx_deliver_posted_interrupt(vcpu, vector)) {
4295 kvm_lapic_set_irr(vector, apic);
4296 kvm_make_request(KVM_REQ_EVENT, vcpu);
4297 kvm_vcpu_kick(vcpu);
4298 } else {
4299 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode,
4300 trig_mode, vector);
4305 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4306 * will not change in the lifetime of the guest.
4307 * Note that host-state that does change is set elsewhere. E.g., host-state
4308 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4310 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4312 u32 low32, high32;
4313 unsigned long tmpl;
4314 unsigned long cr0, cr3, cr4;
4316 cr0 = read_cr0();
4317 WARN_ON(cr0 & X86_CR0_TS);
4318 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4321 * Save the most likely value for this task's CR3 in the VMCS.
4322 * We can't use __get_current_cr3_fast() because we're not atomic.
4324 cr3 = __read_cr3();
4325 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4326 vmx->loaded_vmcs->host_state.cr3 = cr3;
4328 /* Save the most likely value for this task's CR4 in the VMCS. */
4329 cr4 = cr4_read_shadow();
4330 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4331 vmx->loaded_vmcs->host_state.cr4 = cr4;
4333 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4334 #ifdef CONFIG_X86_64
4336 * Load null selectors, so we can avoid reloading them in
4337 * vmx_prepare_switch_to_host(), in case userspace uses
4338 * the null selectors too (the expected case).
4340 vmcs_write16(HOST_DS_SELECTOR, 0);
4341 vmcs_write16(HOST_ES_SELECTOR, 0);
4342 #else
4343 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4344 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4345 #endif
4346 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4347 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4349 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4351 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4353 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4354 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4357 * SYSENTER is used for 32-bit system calls on either 32-bit or
4358 * 64-bit kernels. It is always zero If neither is allowed, otherwise
4359 * vmx_vcpu_load_vmcs loads it with the per-CPU entry stack (and may
4360 * have already done so!).
4362 if (!IS_ENABLED(CONFIG_IA32_EMULATION) && !IS_ENABLED(CONFIG_X86_32))
4363 vmcs_writel(HOST_IA32_SYSENTER_ESP, 0);
4365 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4366 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4368 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4369 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4370 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4373 if (cpu_has_load_ia32_efer())
4374 vmcs_write64(HOST_IA32_EFER, kvm_host.efer);
4377 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4379 struct kvm_vcpu *vcpu = &vmx->vcpu;
4381 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4382 ~vcpu->arch.cr4_guest_rsvd_bits;
4383 if (!enable_ept) {
4384 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_TLBFLUSH_BITS;
4385 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PDPTR_BITS;
4387 if (is_guest_mode(&vmx->vcpu))
4388 vcpu->arch.cr4_guest_owned_bits &=
4389 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4390 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4393 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4395 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4397 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4398 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4400 if (!enable_vnmi)
4401 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4403 if (!enable_preemption_timer)
4404 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4406 return pin_based_exec_ctrl;
4409 static u32 vmx_vmentry_ctrl(void)
4411 u32 vmentry_ctrl = vmcs_config.vmentry_ctrl;
4413 if (vmx_pt_mode_is_system())
4414 vmentry_ctrl &= ~(VM_ENTRY_PT_CONCEAL_PIP |
4415 VM_ENTRY_LOAD_IA32_RTIT_CTL);
4417 * IA32e mode, and loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically.
4419 vmentry_ctrl &= ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
4420 VM_ENTRY_LOAD_IA32_EFER |
4421 VM_ENTRY_IA32E_MODE);
4423 if (cpu_has_perf_global_ctrl_bug())
4424 vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4426 return vmentry_ctrl;
4429 static u32 vmx_vmexit_ctrl(void)
4431 u32 vmexit_ctrl = vmcs_config.vmexit_ctrl;
4434 * Not used by KVM and never set in vmcs01 or vmcs02, but emulated for
4435 * nested virtualization and thus allowed to be set in vmcs12.
4437 vmexit_ctrl &= ~(VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER |
4438 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER);
4440 if (vmx_pt_mode_is_system())
4441 vmexit_ctrl &= ~(VM_EXIT_PT_CONCEAL_PIP |
4442 VM_EXIT_CLEAR_IA32_RTIT_CTL);
4444 if (cpu_has_perf_global_ctrl_bug())
4445 vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
4447 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
4448 return vmexit_ctrl &
4449 ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
4452 void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4454 struct vcpu_vmx *vmx = to_vmx(vcpu);
4456 if (is_guest_mode(vcpu)) {
4457 vmx->nested.update_vmcs01_apicv_status = true;
4458 return;
4461 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4463 if (kvm_vcpu_apicv_active(vcpu)) {
4464 secondary_exec_controls_setbit(vmx,
4465 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4466 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4467 if (enable_ipiv)
4468 tertiary_exec_controls_setbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4469 } else {
4470 secondary_exec_controls_clearbit(vmx,
4471 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4472 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4473 if (enable_ipiv)
4474 tertiary_exec_controls_clearbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4477 vmx_update_msr_bitmap_x2apic(vcpu);
4480 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4482 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4485 * Not used by KVM, but fully supported for nesting, i.e. are allowed in
4486 * vmcs12 and propagated to vmcs02 when set in vmcs12.
4488 exec_control &= ~(CPU_BASED_RDTSC_EXITING |
4489 CPU_BASED_USE_IO_BITMAPS |
4490 CPU_BASED_MONITOR_TRAP_FLAG |
4491 CPU_BASED_PAUSE_EXITING);
4493 /* INTR_WINDOW_EXITING and NMI_WINDOW_EXITING are toggled dynamically */
4494 exec_control &= ~(CPU_BASED_INTR_WINDOW_EXITING |
4495 CPU_BASED_NMI_WINDOW_EXITING);
4497 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4498 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4500 if (!cpu_need_tpr_shadow(&vmx->vcpu))
4501 exec_control &= ~CPU_BASED_TPR_SHADOW;
4503 #ifdef CONFIG_X86_64
4504 if (exec_control & CPU_BASED_TPR_SHADOW)
4505 exec_control &= ~(CPU_BASED_CR8_LOAD_EXITING |
4506 CPU_BASED_CR8_STORE_EXITING);
4507 else
4508 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4509 CPU_BASED_CR8_LOAD_EXITING;
4510 #endif
4511 /* No need to intercept CR3 access or INVPLG when using EPT. */
4512 if (enable_ept)
4513 exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4514 CPU_BASED_CR3_STORE_EXITING |
4515 CPU_BASED_INVLPG_EXITING);
4516 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4517 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4518 CPU_BASED_MONITOR_EXITING);
4519 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4520 exec_control &= ~CPU_BASED_HLT_EXITING;
4521 return exec_control;
4524 static u64 vmx_tertiary_exec_control(struct vcpu_vmx *vmx)
4526 u64 exec_control = vmcs_config.cpu_based_3rd_exec_ctrl;
4529 * IPI virtualization relies on APICv. Disable IPI virtualization if
4530 * APICv is inhibited.
4532 if (!enable_ipiv || !kvm_vcpu_apicv_active(&vmx->vcpu))
4533 exec_control &= ~TERTIARY_EXEC_IPI_VIRT;
4535 return exec_control;
4539 * Adjust a single secondary execution control bit to intercept/allow an
4540 * instruction in the guest. This is usually done based on whether or not a
4541 * feature has been exposed to the guest in order to correctly emulate faults.
4543 static inline void
4544 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4545 u32 control, bool enabled, bool exiting)
4548 * If the control is for an opt-in feature, clear the control if the
4549 * feature is not exposed to the guest, i.e. not enabled. If the
4550 * control is opt-out, i.e. an exiting control, clear the control if
4551 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4552 * disabled for the associated instruction. Note, the caller is
4553 * responsible presetting exec_control to set all supported bits.
4555 if (enabled == exiting)
4556 *exec_control &= ~control;
4559 * Update the nested MSR settings so that a nested VMM can/can't set
4560 * controls for features that are/aren't exposed to the guest.
4562 if (nested) {
4564 * All features that can be added or removed to VMX MSRs must
4565 * be supported in the first place for nested virtualization.
4567 if (WARN_ON_ONCE(!(vmcs_config.nested.secondary_ctls_high & control)))
4568 enabled = false;
4570 if (enabled)
4571 vmx->nested.msrs.secondary_ctls_high |= control;
4572 else
4573 vmx->nested.msrs.secondary_ctls_high &= ~control;
4578 * Wrapper macro for the common case of adjusting a secondary execution control
4579 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4580 * verifies that the control is actually supported by KVM and hardware.
4582 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4583 ({ \
4584 struct kvm_vcpu *__vcpu = &(vmx)->vcpu; \
4585 bool __enabled; \
4587 if (cpu_has_vmx_##name()) { \
4588 if (kvm_is_governed_feature(X86_FEATURE_##feat_name)) \
4589 __enabled = guest_can_use(__vcpu, X86_FEATURE_##feat_name); \
4590 else \
4591 __enabled = guest_cpuid_has(__vcpu, X86_FEATURE_##feat_name); \
4592 vmx_adjust_secondary_exec_control(vmx, exec_control, SECONDARY_EXEC_##ctrl_name,\
4593 __enabled, exiting); \
4597 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4598 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4599 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4601 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4602 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4604 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4606 struct kvm_vcpu *vcpu = &vmx->vcpu;
4608 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4610 if (vmx_pt_mode_is_system())
4611 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4612 if (!cpu_need_virtualize_apic_accesses(vcpu))
4613 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4614 if (vmx->vpid == 0)
4615 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4616 if (!enable_ept) {
4617 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4618 exec_control &= ~SECONDARY_EXEC_EPT_VIOLATION_VE;
4619 enable_unrestricted_guest = 0;
4621 if (!enable_unrestricted_guest)
4622 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4623 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4624 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4625 if (!kvm_vcpu_apicv_active(vcpu))
4626 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4627 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4628 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4631 * KVM doesn't support VMFUNC for L1, but the control is set in KVM's
4632 * base configuration as KVM emulates VMFUNC[EPTP_SWITCHING] for L2.
4634 exec_control &= ~SECONDARY_EXEC_ENABLE_VMFUNC;
4636 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4637 * in vmx_set_cr4. */
4638 exec_control &= ~SECONDARY_EXEC_DESC;
4640 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4641 (handle_vmptrld).
4642 We can NOT enable shadow_vmcs here because we don't have yet
4643 a current VMCS12
4645 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4648 * PML is enabled/disabled when dirty logging of memsmlots changes, but
4649 * it needs to be set here when dirty logging is already active, e.g.
4650 * if this vCPU was created after dirty logging was enabled.
4652 if (!enable_pml || !atomic_read(&vcpu->kvm->nr_memslots_dirty_logging))
4653 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4655 vmx_adjust_sec_exec_feature(vmx, &exec_control, xsaves, XSAVES);
4658 * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
4659 * feature is exposed to the guest. This creates a virtualization hole
4660 * if both are supported in hardware but only one is exposed to the
4661 * guest, but letting the guest execute RDTSCP or RDPID when either one
4662 * is advertised is preferable to emulating the advertised instruction
4663 * in KVM on #UD, and obviously better than incorrectly injecting #UD.
4665 if (cpu_has_vmx_rdtscp()) {
4666 bool rdpid_or_rdtscp_enabled =
4667 guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
4668 guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
4670 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4671 SECONDARY_EXEC_ENABLE_RDTSCP,
4672 rdpid_or_rdtscp_enabled, false);
4675 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4677 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4678 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4680 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4681 ENABLE_USR_WAIT_PAUSE, false);
4683 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4684 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4686 if (!kvm_notify_vmexit_enabled(vcpu->kvm))
4687 exec_control &= ~SECONDARY_EXEC_NOTIFY_VM_EXITING;
4689 return exec_control;
4692 static inline int vmx_get_pid_table_order(struct kvm *kvm)
4694 return get_order(kvm->arch.max_vcpu_ids * sizeof(*to_kvm_vmx(kvm)->pid_table));
4697 static int vmx_alloc_ipiv_pid_table(struct kvm *kvm)
4699 struct page *pages;
4700 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4702 if (!irqchip_in_kernel(kvm) || !enable_ipiv)
4703 return 0;
4705 if (kvm_vmx->pid_table)
4706 return 0;
4708 pages = alloc_pages(GFP_KERNEL_ACCOUNT | __GFP_ZERO,
4709 vmx_get_pid_table_order(kvm));
4710 if (!pages)
4711 return -ENOMEM;
4713 kvm_vmx->pid_table = (void *)page_address(pages);
4714 return 0;
4717 int vmx_vcpu_precreate(struct kvm *kvm)
4719 return vmx_alloc_ipiv_pid_table(kvm);
4722 #define VMX_XSS_EXIT_BITMAP 0
4724 static void init_vmcs(struct vcpu_vmx *vmx)
4726 struct kvm *kvm = vmx->vcpu.kvm;
4727 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4729 if (nested)
4730 nested_vmx_set_vmcs_shadowing_bitmap();
4732 if (cpu_has_vmx_msr_bitmap())
4733 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4735 vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA); /* 22.3.1.5 */
4737 /* Control */
4738 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4740 exec_controls_set(vmx, vmx_exec_control(vmx));
4742 if (cpu_has_secondary_exec_ctrls()) {
4743 secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx));
4744 if (vmx->ve_info)
4745 vmcs_write64(VE_INFORMATION_ADDRESS,
4746 __pa(vmx->ve_info));
4749 if (cpu_has_tertiary_exec_ctrls())
4750 tertiary_exec_controls_set(vmx, vmx_tertiary_exec_control(vmx));
4752 if (enable_apicv && lapic_in_kernel(&vmx->vcpu)) {
4753 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4754 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4755 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4756 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4758 vmcs_write16(GUEST_INTR_STATUS, 0);
4760 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4761 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4764 if (vmx_can_use_ipiv(&vmx->vcpu)) {
4765 vmcs_write64(PID_POINTER_TABLE, __pa(kvm_vmx->pid_table));
4766 vmcs_write16(LAST_PID_POINTER_INDEX, kvm->arch.max_vcpu_ids - 1);
4769 if (!kvm_pause_in_guest(kvm)) {
4770 vmcs_write32(PLE_GAP, ple_gap);
4771 vmx->ple_window = ple_window;
4772 vmx->ple_window_dirty = true;
4775 if (kvm_notify_vmexit_enabled(kvm))
4776 vmcs_write32(NOTIFY_WINDOW, kvm->arch.notify_window);
4778 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4779 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4780 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4782 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4783 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4784 vmx_set_constant_host_state(vmx);
4785 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4786 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4788 if (cpu_has_vmx_vmfunc())
4789 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4791 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4792 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4793 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4794 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4795 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4797 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4798 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4800 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4802 /* 22.2.1, 20.8.1 */
4803 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4805 vmx->vcpu.arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
4806 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4808 set_cr4_guest_host_mask(vmx);
4810 if (vmx->vpid != 0)
4811 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4813 if (cpu_has_vmx_xsaves())
4814 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4816 if (enable_pml) {
4817 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4818 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4821 vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4823 if (vmx_pt_mode_is_host_guest()) {
4824 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4825 /* Bit[6~0] are forced to 1, writes are ignored. */
4826 vmx->pt_desc.guest.output_mask = 0x7F;
4827 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4830 vmcs_write32(GUEST_SYSENTER_CS, 0);
4831 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4832 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4833 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4835 if (cpu_has_vmx_tpr_shadow()) {
4836 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4837 if (cpu_need_tpr_shadow(&vmx->vcpu))
4838 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4839 __pa(vmx->vcpu.arch.apic->regs));
4840 vmcs_write32(TPR_THRESHOLD, 0);
4843 vmx_setup_uret_msrs(vmx);
4846 static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4848 struct vcpu_vmx *vmx = to_vmx(vcpu);
4850 init_vmcs(vmx);
4852 if (nested)
4853 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
4855 vcpu_setup_sgx_lepubkeyhash(vcpu);
4857 vmx->nested.posted_intr_nv = -1;
4858 vmx->nested.vmxon_ptr = INVALID_GPA;
4859 vmx->nested.current_vmptr = INVALID_GPA;
4861 #ifdef CONFIG_KVM_HYPERV
4862 vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
4863 #endif
4865 vcpu->arch.microcode_version = 0x100000000ULL;
4866 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
4869 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
4870 * or POSTED_INTR_WAKEUP_VECTOR.
4872 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
4873 __pi_set_sn(&vmx->pi_desc);
4876 void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4878 struct vcpu_vmx *vmx = to_vmx(vcpu);
4880 if (!init_event)
4881 __vmx_vcpu_reset(vcpu);
4883 vmx->rmode.vm86_active = 0;
4884 vmx->spec_ctrl = 0;
4886 vmx->msr_ia32_umwait_control = 0;
4888 vmx->hv_deadline_tsc = -1;
4889 kvm_set_cr8(vcpu, 0);
4891 vmx_segment_cache_clear(vmx);
4892 kvm_register_mark_available(vcpu, VCPU_EXREG_SEGMENTS);
4894 seg_setup(VCPU_SREG_CS);
4895 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4896 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4898 seg_setup(VCPU_SREG_DS);
4899 seg_setup(VCPU_SREG_ES);
4900 seg_setup(VCPU_SREG_FS);
4901 seg_setup(VCPU_SREG_GS);
4902 seg_setup(VCPU_SREG_SS);
4904 vmcs_write16(GUEST_TR_SELECTOR, 0);
4905 vmcs_writel(GUEST_TR_BASE, 0);
4906 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4907 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4909 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4910 vmcs_writel(GUEST_LDTR_BASE, 0);
4911 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4912 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4914 vmcs_writel(GUEST_GDTR_BASE, 0);
4915 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4917 vmcs_writel(GUEST_IDTR_BASE, 0);
4918 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4920 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4921 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4922 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4923 if (kvm_mpx_supported())
4924 vmcs_write64(GUEST_BNDCFGS, 0);
4926 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4928 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4930 vpid_sync_context(vmx->vpid);
4932 vmx_update_fb_clear_dis(vcpu, vmx);
4935 void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4937 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4940 void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4942 if (!enable_vnmi ||
4943 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4944 vmx_enable_irq_window(vcpu);
4945 return;
4948 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4951 void vmx_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
4953 struct vcpu_vmx *vmx = to_vmx(vcpu);
4954 uint32_t intr;
4955 int irq = vcpu->arch.interrupt.nr;
4957 trace_kvm_inj_virq(irq, vcpu->arch.interrupt.soft, reinjected);
4959 ++vcpu->stat.irq_injections;
4960 if (vmx->rmode.vm86_active) {
4961 int inc_eip = 0;
4962 if (vcpu->arch.interrupt.soft)
4963 inc_eip = vcpu->arch.event_exit_inst_len;
4964 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4965 return;
4967 intr = irq | INTR_INFO_VALID_MASK;
4968 if (vcpu->arch.interrupt.soft) {
4969 intr |= INTR_TYPE_SOFT_INTR;
4970 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4971 vmx->vcpu.arch.event_exit_inst_len);
4972 } else
4973 intr |= INTR_TYPE_EXT_INTR;
4974 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4976 vmx_clear_hlt(vcpu);
4979 void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4981 struct vcpu_vmx *vmx = to_vmx(vcpu);
4983 if (!enable_vnmi) {
4985 * Tracking the NMI-blocked state in software is built upon
4986 * finding the next open IRQ window. This, in turn, depends on
4987 * well-behaving guests: They have to keep IRQs disabled at
4988 * least as long as the NMI handler runs. Otherwise we may
4989 * cause NMI nesting, maybe breaking the guest. But as this is
4990 * highly unlikely, we can live with the residual risk.
4992 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4993 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4996 ++vcpu->stat.nmi_injections;
4997 vmx->loaded_vmcs->nmi_known_unmasked = false;
4999 if (vmx->rmode.vm86_active) {
5000 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
5001 return;
5004 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
5005 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
5007 vmx_clear_hlt(vcpu);
5010 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
5012 struct vcpu_vmx *vmx = to_vmx(vcpu);
5013 bool masked;
5015 if (!enable_vnmi)
5016 return vmx->loaded_vmcs->soft_vnmi_blocked;
5017 if (vmx->loaded_vmcs->nmi_known_unmasked)
5018 return false;
5019 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
5020 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5021 return masked;
5024 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5026 struct vcpu_vmx *vmx = to_vmx(vcpu);
5028 if (!enable_vnmi) {
5029 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
5030 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
5031 vmx->loaded_vmcs->vnmi_blocked_time = 0;
5033 } else {
5034 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5035 if (masked)
5036 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5037 GUEST_INTR_STATE_NMI);
5038 else
5039 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
5040 GUEST_INTR_STATE_NMI);
5044 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
5046 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
5047 return false;
5049 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
5050 return true;
5052 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5053 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
5054 GUEST_INTR_STATE_NMI));
5057 int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
5059 if (to_vmx(vcpu)->nested.nested_run_pending)
5060 return -EBUSY;
5062 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
5063 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
5064 return -EBUSY;
5066 return !vmx_nmi_blocked(vcpu);
5069 bool __vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
5071 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
5072 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5073 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
5076 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
5078 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
5079 return false;
5081 return __vmx_interrupt_blocked(vcpu);
5084 int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
5086 if (to_vmx(vcpu)->nested.nested_run_pending)
5087 return -EBUSY;
5090 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
5091 * e.g. if the IRQ arrived asynchronously after checking nested events.
5093 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
5094 return -EBUSY;
5096 return !vmx_interrupt_blocked(vcpu);
5099 int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
5101 void __user *ret;
5103 if (enable_unrestricted_guest)
5104 return 0;
5106 mutex_lock(&kvm->slots_lock);
5107 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
5108 PAGE_SIZE * 3);
5109 mutex_unlock(&kvm->slots_lock);
5111 if (IS_ERR(ret))
5112 return PTR_ERR(ret);
5114 to_kvm_vmx(kvm)->tss_addr = addr;
5116 return init_rmode_tss(kvm, ret);
5119 int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5121 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
5122 return 0;
5125 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
5127 switch (vec) {
5128 case BP_VECTOR:
5130 * Update instruction length as we may reinject the exception
5131 * from user space while in guest debugging mode.
5133 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
5134 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5135 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5136 return false;
5137 fallthrough;
5138 case DB_VECTOR:
5139 return !(vcpu->guest_debug &
5140 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
5141 case DE_VECTOR:
5142 case OF_VECTOR:
5143 case BR_VECTOR:
5144 case UD_VECTOR:
5145 case DF_VECTOR:
5146 case SS_VECTOR:
5147 case GP_VECTOR:
5148 case MF_VECTOR:
5149 return true;
5151 return false;
5154 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
5155 int vec, u32 err_code)
5158 * Instruction with address size override prefix opcode 0x67
5159 * Cause the #SS fault with 0 error code in VM86 mode.
5161 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5162 if (kvm_emulate_instruction(vcpu, 0)) {
5163 if (vcpu->arch.halt_request) {
5164 vcpu->arch.halt_request = 0;
5165 return kvm_emulate_halt_noskip(vcpu);
5167 return 1;
5169 return 0;
5173 * Forward all other exceptions that are valid in real mode.
5174 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5175 * the required debugging infrastructure rework.
5177 kvm_queue_exception(vcpu, vec);
5178 return 1;
5181 static int handle_machine_check(struct kvm_vcpu *vcpu)
5183 /* handled by vmx_vcpu_run() */
5184 return 1;
5188 * If the host has split lock detection disabled, then #AC is
5189 * unconditionally injected into the guest, which is the pre split lock
5190 * detection behaviour.
5192 * If the host has split lock detection enabled then #AC is
5193 * only injected into the guest when:
5194 * - Guest CPL == 3 (user mode)
5195 * - Guest has #AC detection enabled in CR0
5196 * - Guest EFLAGS has AC bit set
5198 bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu)
5200 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5201 return true;
5203 return vmx_get_cpl(vcpu) == 3 && kvm_is_cr0_bit_set(vcpu, X86_CR0_AM) &&
5204 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
5207 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
5209 struct vcpu_vmx *vmx = to_vmx(vcpu);
5210 struct kvm_run *kvm_run = vcpu->run;
5211 u32 intr_info, ex_no, error_code;
5212 unsigned long cr2, dr6;
5213 u32 vect_info;
5215 vect_info = vmx->idt_vectoring_info;
5216 intr_info = vmx_get_intr_info(vcpu);
5219 * Machine checks are handled by handle_exception_irqoff(), or by
5220 * vmx_vcpu_run() if a #MC occurs on VM-Entry. NMIs are handled by
5221 * vmx_vcpu_enter_exit().
5223 if (is_machine_check(intr_info) || is_nmi(intr_info))
5224 return 1;
5227 * Queue the exception here instead of in handle_nm_fault_irqoff().
5228 * This ensures the nested_vmx check is not skipped so vmexit can
5229 * be reflected to L1 (when it intercepts #NM) before reaching this
5230 * point.
5232 if (is_nm_fault(intr_info)) {
5233 kvm_queue_exception(vcpu, NM_VECTOR);
5234 return 1;
5237 if (is_invalid_opcode(intr_info))
5238 return handle_ud(vcpu);
5240 if (WARN_ON_ONCE(is_ve_fault(intr_info))) {
5241 struct vmx_ve_information *ve_info = vmx->ve_info;
5243 WARN_ONCE(ve_info->exit_reason != EXIT_REASON_EPT_VIOLATION,
5244 "Unexpected #VE on VM-Exit reason 0x%x", ve_info->exit_reason);
5245 dump_vmcs(vcpu);
5246 kvm_mmu_print_sptes(vcpu, ve_info->guest_physical_address, "#VE");
5247 return 1;
5250 error_code = 0;
5251 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5252 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5254 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
5255 WARN_ON_ONCE(!enable_vmware_backdoor);
5258 * VMware backdoor emulation on #GP interception only handles
5259 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
5260 * error code on #GP.
5262 if (error_code) {
5263 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
5264 return 1;
5266 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
5270 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5271 * MMIO, it is better to report an internal error.
5272 * See the comments in vmx_handle_exit.
5274 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5275 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5276 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5277 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5278 vcpu->run->internal.ndata = 4;
5279 vcpu->run->internal.data[0] = vect_info;
5280 vcpu->run->internal.data[1] = intr_info;
5281 vcpu->run->internal.data[2] = error_code;
5282 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
5283 return 0;
5286 if (is_page_fault(intr_info)) {
5287 cr2 = vmx_get_exit_qual(vcpu);
5288 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
5290 * EPT will cause page fault only if we need to
5291 * detect illegal GPAs.
5293 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
5294 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
5295 return 1;
5296 } else
5297 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
5300 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5302 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5303 return handle_rmode_exception(vcpu, ex_no, error_code);
5305 switch (ex_no) {
5306 case DB_VECTOR:
5307 dr6 = vmx_get_exit_qual(vcpu);
5308 if (!(vcpu->guest_debug &
5309 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5311 * If the #DB was due to ICEBP, a.k.a. INT1, skip the
5312 * instruction. ICEBP generates a trap-like #DB, but
5313 * despite its interception control being tied to #DB,
5314 * is an instruction intercept, i.e. the VM-Exit occurs
5315 * on the ICEBP itself. Use the inner "skip" helper to
5316 * avoid single-step #DB and MTF updates, as ICEBP is
5317 * higher priority. Note, skipping ICEBP still clears
5318 * STI and MOVSS blocking.
5320 * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
5321 * if single-step is enabled in RFLAGS and STI or MOVSS
5322 * blocking is active, as the CPU doesn't set the bit
5323 * on VM-Exit due to #DB interception. VM-Entry has a
5324 * consistency check that a single-step #DB is pending
5325 * in this scenario as the previous instruction cannot
5326 * have toggled RFLAGS.TF 0=>1 (because STI and POP/MOV
5327 * don't modify RFLAGS), therefore the one instruction
5328 * delay when activating single-step breakpoints must
5329 * have already expired. Note, the CPU sets/clears BS
5330 * as appropriate for all other VM-Exits types.
5332 if (is_icebp(intr_info))
5333 WARN_ON(!skip_emulated_instruction(vcpu));
5334 else if ((vmx_get_rflags(vcpu) & X86_EFLAGS_TF) &&
5335 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5336 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)))
5337 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
5338 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS) | DR6_BS);
5340 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
5341 return 1;
5343 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
5344 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5345 fallthrough;
5346 case BP_VECTOR:
5348 * Update instruction length as we may reinject #BP from
5349 * user space while in guest debugging mode. Reading it for
5350 * #DB as well causes no harm, it is not used in that case.
5352 vmx->vcpu.arch.event_exit_inst_len =
5353 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5354 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5355 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5356 kvm_run->debug.arch.exception = ex_no;
5357 break;
5358 case AC_VECTOR:
5359 if (vmx_guest_inject_ac(vcpu)) {
5360 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5361 return 1;
5365 * Handle split lock. Depending on detection mode this will
5366 * either warn and disable split lock detection for this
5367 * task or force SIGBUS on it.
5369 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
5370 return 1;
5371 fallthrough;
5372 default:
5373 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5374 kvm_run->ex.exception = ex_no;
5375 kvm_run->ex.error_code = error_code;
5376 break;
5378 return 0;
5381 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
5383 ++vcpu->stat.irq_exits;
5384 return 1;
5387 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5389 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5390 vcpu->mmio_needed = 0;
5391 return 0;
5394 static int handle_io(struct kvm_vcpu *vcpu)
5396 unsigned long exit_qualification;
5397 int size, in, string;
5398 unsigned port;
5400 exit_qualification = vmx_get_exit_qual(vcpu);
5401 string = (exit_qualification & 16) != 0;
5403 ++vcpu->stat.io_exits;
5405 if (string)
5406 return kvm_emulate_instruction(vcpu, 0);
5408 port = exit_qualification >> 16;
5409 size = (exit_qualification & 7) + 1;
5410 in = (exit_qualification & 8) != 0;
5412 return kvm_fast_pio(vcpu, size, port, in);
5415 void vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5418 * Patch in the VMCALL instruction:
5420 hypercall[0] = 0x0f;
5421 hypercall[1] = 0x01;
5422 hypercall[2] = 0xc1;
5425 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5426 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5428 if (is_guest_mode(vcpu)) {
5429 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5430 unsigned long orig_val = val;
5433 * We get here when L2 changed cr0 in a way that did not change
5434 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5435 * but did change L0 shadowed bits. So we first calculate the
5436 * effective cr0 value that L1 would like to write into the
5437 * hardware. It consists of the L2-owned bits from the new
5438 * value combined with the L1-owned bits from L1's guest_cr0.
5440 val = (val & ~vmcs12->cr0_guest_host_mask) |
5441 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5443 if (kvm_set_cr0(vcpu, val))
5444 return 1;
5445 vmcs_writel(CR0_READ_SHADOW, orig_val);
5446 return 0;
5447 } else {
5448 return kvm_set_cr0(vcpu, val);
5452 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5454 if (is_guest_mode(vcpu)) {
5455 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5456 unsigned long orig_val = val;
5458 /* analogously to handle_set_cr0 */
5459 val = (val & ~vmcs12->cr4_guest_host_mask) |
5460 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5461 if (kvm_set_cr4(vcpu, val))
5462 return 1;
5463 vmcs_writel(CR4_READ_SHADOW, orig_val);
5464 return 0;
5465 } else
5466 return kvm_set_cr4(vcpu, val);
5469 static int handle_desc(struct kvm_vcpu *vcpu)
5472 * UMIP emulation relies on intercepting writes to CR4.UMIP, i.e. this
5473 * and other code needs to be updated if UMIP can be guest owned.
5475 BUILD_BUG_ON(KVM_POSSIBLE_CR4_GUEST_BITS & X86_CR4_UMIP);
5477 WARN_ON_ONCE(!kvm_is_cr4_bit_set(vcpu, X86_CR4_UMIP));
5478 return kvm_emulate_instruction(vcpu, 0);
5481 static int handle_cr(struct kvm_vcpu *vcpu)
5483 unsigned long exit_qualification, val;
5484 int cr;
5485 int reg;
5486 int err;
5487 int ret;
5489 exit_qualification = vmx_get_exit_qual(vcpu);
5490 cr = exit_qualification & 15;
5491 reg = (exit_qualification >> 8) & 15;
5492 switch ((exit_qualification >> 4) & 3) {
5493 case 0: /* mov to cr */
5494 val = kvm_register_read(vcpu, reg);
5495 trace_kvm_cr_write(cr, val);
5496 switch (cr) {
5497 case 0:
5498 err = handle_set_cr0(vcpu, val);
5499 return kvm_complete_insn_gp(vcpu, err);
5500 case 3:
5501 WARN_ON_ONCE(enable_unrestricted_guest);
5503 err = kvm_set_cr3(vcpu, val);
5504 return kvm_complete_insn_gp(vcpu, err);
5505 case 4:
5506 err = handle_set_cr4(vcpu, val);
5507 return kvm_complete_insn_gp(vcpu, err);
5508 case 8: {
5509 u8 cr8_prev = kvm_get_cr8(vcpu);
5510 u8 cr8 = (u8)val;
5511 err = kvm_set_cr8(vcpu, cr8);
5512 ret = kvm_complete_insn_gp(vcpu, err);
5513 if (lapic_in_kernel(vcpu))
5514 return ret;
5515 if (cr8_prev <= cr8)
5516 return ret;
5518 * TODO: we might be squashing a
5519 * KVM_GUESTDBG_SINGLESTEP-triggered
5520 * KVM_EXIT_DEBUG here.
5522 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5523 return 0;
5526 break;
5527 case 2: /* clts */
5528 KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS");
5529 return -EIO;
5530 case 1: /*mov from cr*/
5531 switch (cr) {
5532 case 3:
5533 WARN_ON_ONCE(enable_unrestricted_guest);
5535 val = kvm_read_cr3(vcpu);
5536 kvm_register_write(vcpu, reg, val);
5537 trace_kvm_cr_read(cr, val);
5538 return kvm_skip_emulated_instruction(vcpu);
5539 case 8:
5540 val = kvm_get_cr8(vcpu);
5541 kvm_register_write(vcpu, reg, val);
5542 trace_kvm_cr_read(cr, val);
5543 return kvm_skip_emulated_instruction(vcpu);
5545 break;
5546 case 3: /* lmsw */
5547 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5548 trace_kvm_cr_write(0, (kvm_read_cr0_bits(vcpu, ~0xful) | val));
5549 kvm_lmsw(vcpu, val);
5551 return kvm_skip_emulated_instruction(vcpu);
5552 default:
5553 break;
5555 vcpu->run->exit_reason = 0;
5556 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5557 (int)(exit_qualification >> 4) & 3, cr);
5558 return 0;
5561 static int handle_dr(struct kvm_vcpu *vcpu)
5563 unsigned long exit_qualification;
5564 int dr, dr7, reg;
5565 int err = 1;
5567 exit_qualification = vmx_get_exit_qual(vcpu);
5568 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5570 /* First, if DR does not exist, trigger UD */
5571 if (!kvm_require_dr(vcpu, dr))
5572 return 1;
5574 if (vmx_get_cpl(vcpu) > 0)
5575 goto out;
5577 dr7 = vmcs_readl(GUEST_DR7);
5578 if (dr7 & DR7_GD) {
5580 * As the vm-exit takes precedence over the debug trap, we
5581 * need to emulate the latter, either for the host or the
5582 * guest debugging itself.
5584 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5585 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5586 vcpu->run->debug.arch.dr7 = dr7;
5587 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5588 vcpu->run->debug.arch.exception = DB_VECTOR;
5589 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5590 return 0;
5591 } else {
5592 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5593 return 1;
5597 if (vcpu->guest_debug == 0) {
5598 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5601 * No more DR vmexits; force a reload of the debug registers
5602 * and reenter on this instruction. The next vmexit will
5603 * retrieve the full state of the debug registers.
5605 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5606 return 1;
5609 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5610 if (exit_qualification & TYPE_MOV_FROM_DR) {
5611 kvm_register_write(vcpu, reg, kvm_get_dr(vcpu, dr));
5612 err = 0;
5613 } else {
5614 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5617 out:
5618 return kvm_complete_insn_gp(vcpu, err);
5621 void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5623 get_debugreg(vcpu->arch.db[0], 0);
5624 get_debugreg(vcpu->arch.db[1], 1);
5625 get_debugreg(vcpu->arch.db[2], 2);
5626 get_debugreg(vcpu->arch.db[3], 3);
5627 get_debugreg(vcpu->arch.dr6, 6);
5628 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5630 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5631 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5634 * exc_debug expects dr6 to be cleared after it runs, avoid that it sees
5635 * a stale dr6 from the guest.
5637 set_debugreg(DR6_RESERVED, 6);
5640 void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5642 vmcs_writel(GUEST_DR7, val);
5645 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5647 kvm_apic_update_ppr(vcpu);
5648 return 1;
5651 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5653 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5655 kvm_make_request(KVM_REQ_EVENT, vcpu);
5657 ++vcpu->stat.irq_window_exits;
5658 return 1;
5661 static int handle_invlpg(struct kvm_vcpu *vcpu)
5663 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5665 kvm_mmu_invlpg(vcpu, exit_qualification);
5666 return kvm_skip_emulated_instruction(vcpu);
5669 static int handle_apic_access(struct kvm_vcpu *vcpu)
5671 if (likely(fasteoi)) {
5672 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5673 int access_type, offset;
5675 access_type = exit_qualification & APIC_ACCESS_TYPE;
5676 offset = exit_qualification & APIC_ACCESS_OFFSET;
5678 * Sane guest uses MOV to write EOI, with written value
5679 * not cared. So make a short-circuit here by avoiding
5680 * heavy instruction emulation.
5682 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5683 (offset == APIC_EOI)) {
5684 kvm_lapic_set_eoi(vcpu);
5685 return kvm_skip_emulated_instruction(vcpu);
5688 return kvm_emulate_instruction(vcpu, 0);
5691 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5693 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5694 int vector = exit_qualification & 0xff;
5696 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5697 kvm_apic_set_eoi_accelerated(vcpu, vector);
5698 return 1;
5701 static int handle_apic_write(struct kvm_vcpu *vcpu)
5703 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5706 * APIC-write VM-Exit is trap-like, KVM doesn't need to advance RIP and
5707 * hardware has done any necessary aliasing, offset adjustments, etc...
5708 * for the access. I.e. the correct value has already been written to
5709 * the vAPIC page for the correct 16-byte chunk. KVM needs only to
5710 * retrieve the register value and emulate the access.
5712 u32 offset = exit_qualification & 0xff0;
5714 kvm_apic_write_nodecode(vcpu, offset);
5715 return 1;
5718 static int handle_task_switch(struct kvm_vcpu *vcpu)
5720 struct vcpu_vmx *vmx = to_vmx(vcpu);
5721 unsigned long exit_qualification;
5722 bool has_error_code = false;
5723 u32 error_code = 0;
5724 u16 tss_selector;
5725 int reason, type, idt_v, idt_index;
5727 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5728 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5729 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5731 exit_qualification = vmx_get_exit_qual(vcpu);
5733 reason = (u32)exit_qualification >> 30;
5734 if (reason == TASK_SWITCH_GATE && idt_v) {
5735 switch (type) {
5736 case INTR_TYPE_NMI_INTR:
5737 vcpu->arch.nmi_injected = false;
5738 vmx_set_nmi_mask(vcpu, true);
5739 break;
5740 case INTR_TYPE_EXT_INTR:
5741 case INTR_TYPE_SOFT_INTR:
5742 kvm_clear_interrupt_queue(vcpu);
5743 break;
5744 case INTR_TYPE_HARD_EXCEPTION:
5745 if (vmx->idt_vectoring_info &
5746 VECTORING_INFO_DELIVER_CODE_MASK) {
5747 has_error_code = true;
5748 error_code =
5749 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5751 fallthrough;
5752 case INTR_TYPE_SOFT_EXCEPTION:
5753 kvm_clear_exception_queue(vcpu);
5754 break;
5755 default:
5756 break;
5759 tss_selector = exit_qualification;
5761 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5762 type != INTR_TYPE_EXT_INTR &&
5763 type != INTR_TYPE_NMI_INTR))
5764 WARN_ON(!skip_emulated_instruction(vcpu));
5767 * TODO: What about debug traps on tss switch?
5768 * Are we supposed to inject them and update dr6?
5770 return kvm_task_switch(vcpu, tss_selector,
5771 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5772 reason, has_error_code, error_code);
5775 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5777 unsigned long exit_qualification;
5778 gpa_t gpa;
5779 u64 error_code;
5781 exit_qualification = vmx_get_exit_qual(vcpu);
5784 * EPT violation happened while executing iret from NMI,
5785 * "blocked by NMI" bit has to be set before next VM entry.
5786 * There are errata that may cause this bit to not be set:
5787 * AAK134, BY25.
5789 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5790 enable_vnmi &&
5791 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5792 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5794 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5795 trace_kvm_page_fault(vcpu, gpa, exit_qualification);
5797 /* Is it a read fault? */
5798 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5799 ? PFERR_USER_MASK : 0;
5800 /* Is it a write fault? */
5801 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5802 ? PFERR_WRITE_MASK : 0;
5803 /* Is it a fetch fault? */
5804 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5805 ? PFERR_FETCH_MASK : 0;
5806 /* ept page table entry is present? */
5807 error_code |= (exit_qualification & EPT_VIOLATION_RWX_MASK)
5808 ? PFERR_PRESENT_MASK : 0;
5810 if (error_code & EPT_VIOLATION_GVA_IS_VALID)
5811 error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) ?
5812 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5815 * Check that the GPA doesn't exceed physical memory limits, as that is
5816 * a guest page fault. We have to emulate the instruction here, because
5817 * if the illegal address is that of a paging structure, then
5818 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5819 * would also use advanced VM-exit information for EPT violations to
5820 * reconstruct the page fault error code.
5822 if (unlikely(allow_smaller_maxphyaddr && !kvm_vcpu_is_legal_gpa(vcpu, gpa)))
5823 return kvm_emulate_instruction(vcpu, 0);
5825 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5828 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5830 gpa_t gpa;
5832 if (vmx_check_emulate_instruction(vcpu, EMULTYPE_PF, NULL, 0))
5833 return 1;
5836 * A nested guest cannot optimize MMIO vmexits, because we have an
5837 * nGPA here instead of the required GPA.
5839 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5840 if (!is_guest_mode(vcpu) &&
5841 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5842 trace_kvm_fast_mmio(gpa);
5843 return kvm_skip_emulated_instruction(vcpu);
5846 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5849 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5851 if (KVM_BUG_ON(!enable_vnmi, vcpu->kvm))
5852 return -EIO;
5854 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5855 ++vcpu->stat.nmi_window_exits;
5856 kvm_make_request(KVM_REQ_EVENT, vcpu);
5858 return 1;
5861 static bool vmx_emulation_required_with_pending_exception(struct kvm_vcpu *vcpu)
5863 struct vcpu_vmx *vmx = to_vmx(vcpu);
5865 return vmx->emulation_required && !vmx->rmode.vm86_active &&
5866 (kvm_is_exception_pending(vcpu) || vcpu->arch.exception.injected);
5869 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5871 struct vcpu_vmx *vmx = to_vmx(vcpu);
5872 bool intr_window_requested;
5873 unsigned count = 130;
5875 intr_window_requested = exec_controls_get(vmx) &
5876 CPU_BASED_INTR_WINDOW_EXITING;
5878 while (vmx->emulation_required && count-- != 0) {
5879 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5880 return handle_interrupt_window(&vmx->vcpu);
5882 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5883 return 1;
5885 if (!kvm_emulate_instruction(vcpu, 0))
5886 return 0;
5888 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5889 kvm_prepare_emulation_failure_exit(vcpu);
5890 return 0;
5893 if (vcpu->arch.halt_request) {
5894 vcpu->arch.halt_request = 0;
5895 return kvm_emulate_halt_noskip(vcpu);
5899 * Note, return 1 and not 0, vcpu_run() will invoke
5900 * xfer_to_guest_mode() which will create a proper return
5901 * code.
5903 if (__xfer_to_guest_mode_work_pending())
5904 return 1;
5907 return 1;
5910 int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu)
5912 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5913 kvm_prepare_emulation_failure_exit(vcpu);
5914 return 0;
5917 return 1;
5921 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5922 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5924 static int handle_pause(struct kvm_vcpu *vcpu)
5926 if (!kvm_pause_in_guest(vcpu->kvm))
5927 grow_ple_window(vcpu);
5930 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5931 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5932 * never set PAUSE_EXITING and just set PLE if supported,
5933 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5935 kvm_vcpu_on_spin(vcpu, true);
5936 return kvm_skip_emulated_instruction(vcpu);
5939 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5941 return 1;
5944 static int handle_invpcid(struct kvm_vcpu *vcpu)
5946 u32 vmx_instruction_info;
5947 unsigned long type;
5948 gva_t gva;
5949 struct {
5950 u64 pcid;
5951 u64 gla;
5952 } operand;
5953 int gpr_index;
5955 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5956 kvm_queue_exception(vcpu, UD_VECTOR);
5957 return 1;
5960 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5961 gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
5962 type = kvm_register_read(vcpu, gpr_index);
5964 /* According to the Intel instruction reference, the memory operand
5965 * is read even if it isn't needed (e.g., for type==all)
5967 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5968 vmx_instruction_info, false,
5969 sizeof(operand), &gva))
5970 return 1;
5972 return kvm_handle_invpcid(vcpu, type, gva);
5975 static int handle_pml_full(struct kvm_vcpu *vcpu)
5977 unsigned long exit_qualification;
5979 trace_kvm_pml_full(vcpu->vcpu_id);
5981 exit_qualification = vmx_get_exit_qual(vcpu);
5984 * PML buffer FULL happened while executing iret from NMI,
5985 * "blocked by NMI" bit has to be set before next VM entry.
5987 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5988 enable_vnmi &&
5989 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5990 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5991 GUEST_INTR_STATE_NMI);
5994 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5995 * here.., and there's no userspace involvement needed for PML.
5997 return 1;
6000 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu,
6001 bool force_immediate_exit)
6003 struct vcpu_vmx *vmx = to_vmx(vcpu);
6006 * In the *extremely* unlikely scenario that this is a spurious VM-Exit
6007 * due to the timer expiring while it was "soft" disabled, just eat the
6008 * exit and re-enter the guest.
6010 if (unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled))
6011 return EXIT_FASTPATH_REENTER_GUEST;
6014 * If the timer expired because KVM used it to force an immediate exit,
6015 * then mission accomplished.
6017 if (force_immediate_exit)
6018 return EXIT_FASTPATH_EXIT_HANDLED;
6021 * If L2 is active, go down the slow path as emulating the guest timer
6022 * expiration likely requires synthesizing a nested VM-Exit.
6024 if (is_guest_mode(vcpu))
6025 return EXIT_FASTPATH_NONE;
6027 kvm_lapic_expired_hv_timer(vcpu);
6028 return EXIT_FASTPATH_REENTER_GUEST;
6031 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
6034 * This non-fastpath handler is reached if and only if the preemption
6035 * timer was being used to emulate a guest timer while L2 is active.
6036 * All other scenarios are supposed to be handled in the fastpath.
6038 WARN_ON_ONCE(!is_guest_mode(vcpu));
6039 kvm_lapic_expired_hv_timer(vcpu);
6040 return 1;
6044 * When nested=0, all VMX instruction VM Exits filter here. The handlers
6045 * are overwritten by nested_vmx_setup() when nested=1.
6047 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
6049 kvm_queue_exception(vcpu, UD_VECTOR);
6050 return 1;
6053 #ifndef CONFIG_X86_SGX_KVM
6054 static int handle_encls(struct kvm_vcpu *vcpu)
6057 * SGX virtualization is disabled. There is no software enable bit for
6058 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
6059 * the guest from executing ENCLS (when SGX is supported by hardware).
6061 kvm_queue_exception(vcpu, UD_VECTOR);
6062 return 1;
6064 #endif /* CONFIG_X86_SGX_KVM */
6066 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
6069 * Hardware may or may not set the BUS_LOCK_DETECTED flag on BUS_LOCK
6070 * VM-Exits. Unconditionally set the flag here and leave the handling to
6071 * vmx_handle_exit().
6073 to_vmx(vcpu)->exit_reason.bus_lock_detected = true;
6074 return 1;
6077 static int handle_notify(struct kvm_vcpu *vcpu)
6079 unsigned long exit_qual = vmx_get_exit_qual(vcpu);
6080 bool context_invalid = exit_qual & NOTIFY_VM_CONTEXT_INVALID;
6082 ++vcpu->stat.notify_window_exits;
6085 * Notify VM exit happened while executing iret from NMI,
6086 * "blocked by NMI" bit has to be set before next VM entry.
6088 if (enable_vnmi && (exit_qual & INTR_INFO_UNBLOCK_NMI))
6089 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6090 GUEST_INTR_STATE_NMI);
6092 if (vcpu->kvm->arch.notify_vmexit_flags & KVM_X86_NOTIFY_VMEXIT_USER ||
6093 context_invalid) {
6094 vcpu->run->exit_reason = KVM_EXIT_NOTIFY;
6095 vcpu->run->notify.flags = context_invalid ?
6096 KVM_NOTIFY_CONTEXT_INVALID : 0;
6097 return 0;
6100 return 1;
6104 * The exit handlers return 1 if the exit was handled fully and guest execution
6105 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
6106 * to be done to userspace and return 0.
6108 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
6109 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
6110 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
6111 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
6112 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
6113 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
6114 [EXIT_REASON_CR_ACCESS] = handle_cr,
6115 [EXIT_REASON_DR_ACCESS] = handle_dr,
6116 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
6117 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
6118 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
6119 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
6120 [EXIT_REASON_HLT] = kvm_emulate_halt,
6121 [EXIT_REASON_INVD] = kvm_emulate_invd,
6122 [EXIT_REASON_INVLPG] = handle_invlpg,
6123 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
6124 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
6125 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
6126 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
6127 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
6128 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
6129 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
6130 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
6131 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
6132 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
6133 [EXIT_REASON_VMON] = handle_vmx_instruction,
6134 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
6135 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
6136 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
6137 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
6138 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
6139 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
6140 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
6141 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
6142 [EXIT_REASON_GDTR_IDTR] = handle_desc,
6143 [EXIT_REASON_LDTR_TR] = handle_desc,
6144 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
6145 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
6146 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
6147 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
6148 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
6149 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
6150 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
6151 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
6152 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
6153 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
6154 [EXIT_REASON_PML_FULL] = handle_pml_full,
6155 [EXIT_REASON_INVPCID] = handle_invpcid,
6156 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
6157 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
6158 [EXIT_REASON_ENCLS] = handle_encls,
6159 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
6160 [EXIT_REASON_NOTIFY] = handle_notify,
6163 static const int kvm_vmx_max_exit_handlers =
6164 ARRAY_SIZE(kvm_vmx_exit_handlers);
6166 void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
6167 u64 *info1, u64 *info2, u32 *intr_info, u32 *error_code)
6169 struct vcpu_vmx *vmx = to_vmx(vcpu);
6171 *reason = vmx->exit_reason.full;
6172 *info1 = vmx_get_exit_qual(vcpu);
6173 if (!(vmx->exit_reason.failed_vmentry)) {
6174 *info2 = vmx->idt_vectoring_info;
6175 *intr_info = vmx_get_intr_info(vcpu);
6176 if (is_exception_with_error_code(*intr_info))
6177 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6178 else
6179 *error_code = 0;
6180 } else {
6181 *info2 = 0;
6182 *intr_info = 0;
6183 *error_code = 0;
6187 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
6189 if (vmx->pml_pg) {
6190 __free_page(vmx->pml_pg);
6191 vmx->pml_pg = NULL;
6195 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
6197 struct vcpu_vmx *vmx = to_vmx(vcpu);
6198 u64 *pml_buf;
6199 u16 pml_idx;
6201 pml_idx = vmcs_read16(GUEST_PML_INDEX);
6203 /* Do nothing if PML buffer is empty */
6204 if (pml_idx == (PML_ENTITY_NUM - 1))
6205 return;
6207 /* PML index always points to next available PML buffer entity */
6208 if (pml_idx >= PML_ENTITY_NUM)
6209 pml_idx = 0;
6210 else
6211 pml_idx++;
6213 pml_buf = page_address(vmx->pml_pg);
6214 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
6215 u64 gpa;
6217 gpa = pml_buf[pml_idx];
6218 WARN_ON(gpa & (PAGE_SIZE - 1));
6219 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
6222 /* reset PML index */
6223 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6226 static void vmx_dump_sel(char *name, uint32_t sel)
6228 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
6229 name, vmcs_read16(sel),
6230 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
6231 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
6232 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
6235 static void vmx_dump_dtsel(char *name, uint32_t limit)
6237 pr_err("%s limit=0x%08x, base=0x%016lx\n",
6238 name, vmcs_read32(limit),
6239 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
6242 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
6244 unsigned int i;
6245 struct vmx_msr_entry *e;
6247 pr_err("MSR %s:\n", name);
6248 for (i = 0, e = m->val; i < m->nr; ++i, ++e)
6249 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
6252 void dump_vmcs(struct kvm_vcpu *vcpu)
6254 struct vcpu_vmx *vmx = to_vmx(vcpu);
6255 u32 vmentry_ctl, vmexit_ctl;
6256 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
6257 u64 tertiary_exec_control;
6258 unsigned long cr4;
6259 int efer_slot;
6261 if (!dump_invalid_vmcs) {
6262 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
6263 return;
6266 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
6267 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
6268 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6269 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
6270 cr4 = vmcs_readl(GUEST_CR4);
6272 if (cpu_has_secondary_exec_ctrls())
6273 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6274 else
6275 secondary_exec_control = 0;
6277 if (cpu_has_tertiary_exec_ctrls())
6278 tertiary_exec_control = vmcs_read64(TERTIARY_VM_EXEC_CONTROL);
6279 else
6280 tertiary_exec_control = 0;
6282 pr_err("VMCS %p, last attempted VM-entry on CPU %d\n",
6283 vmx->loaded_vmcs->vmcs, vcpu->arch.last_vmentry_cpu);
6284 pr_err("*** Guest State ***\n");
6285 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6286 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
6287 vmcs_readl(CR0_GUEST_HOST_MASK));
6288 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6289 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
6290 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
6291 if (cpu_has_vmx_ept()) {
6292 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
6293 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
6294 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
6295 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
6297 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
6298 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
6299 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
6300 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
6301 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6302 vmcs_readl(GUEST_SYSENTER_ESP),
6303 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
6304 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
6305 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
6306 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
6307 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
6308 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
6309 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
6310 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
6311 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
6312 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
6313 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
6314 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
6315 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
6316 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
6317 else if (efer_slot >= 0)
6318 pr_err("EFER= 0x%016llx (autoload)\n",
6319 vmx->msr_autoload.guest.val[efer_slot].value);
6320 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
6321 pr_err("EFER= 0x%016llx (effective)\n",
6322 vcpu->arch.efer | (EFER_LMA | EFER_LME));
6323 else
6324 pr_err("EFER= 0x%016llx (effective)\n",
6325 vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
6326 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
6327 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
6328 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
6329 vmcs_read64(GUEST_IA32_DEBUGCTL),
6330 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
6331 if (cpu_has_load_perf_global_ctrl() &&
6332 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
6333 pr_err("PerfGlobCtl = 0x%016llx\n",
6334 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
6335 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
6336 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
6337 pr_err("Interruptibility = %08x ActivityState = %08x\n",
6338 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
6339 vmcs_read32(GUEST_ACTIVITY_STATE));
6340 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
6341 pr_err("InterruptStatus = %04x\n",
6342 vmcs_read16(GUEST_INTR_STATUS));
6343 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
6344 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
6345 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
6346 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
6348 pr_err("*** Host State ***\n");
6349 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
6350 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
6351 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
6352 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
6353 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
6354 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
6355 vmcs_read16(HOST_TR_SELECTOR));
6356 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
6357 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
6358 vmcs_readl(HOST_TR_BASE));
6359 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
6360 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
6361 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
6362 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
6363 vmcs_readl(HOST_CR4));
6364 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6365 vmcs_readl(HOST_IA32_SYSENTER_ESP),
6366 vmcs_read32(HOST_IA32_SYSENTER_CS),
6367 vmcs_readl(HOST_IA32_SYSENTER_EIP));
6368 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
6369 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
6370 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
6371 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
6372 if (cpu_has_load_perf_global_ctrl() &&
6373 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
6374 pr_err("PerfGlobCtl = 0x%016llx\n",
6375 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
6376 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
6377 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
6379 pr_err("*** Control State ***\n");
6380 pr_err("CPUBased=0x%08x SecondaryExec=0x%08x TertiaryExec=0x%016llx\n",
6381 cpu_based_exec_ctrl, secondary_exec_control, tertiary_exec_control);
6382 pr_err("PinBased=0x%08x EntryControls=%08x ExitControls=%08x\n",
6383 pin_based_exec_ctrl, vmentry_ctl, vmexit_ctl);
6384 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
6385 vmcs_read32(EXCEPTION_BITMAP),
6386 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
6387 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
6388 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
6389 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6390 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
6391 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
6392 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
6393 vmcs_read32(VM_EXIT_INTR_INFO),
6394 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
6395 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
6396 pr_err(" reason=%08x qualification=%016lx\n",
6397 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
6398 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
6399 vmcs_read32(IDT_VECTORING_INFO_FIELD),
6400 vmcs_read32(IDT_VECTORING_ERROR_CODE));
6401 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
6402 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
6403 pr_err("TSC Multiplier = 0x%016llx\n",
6404 vmcs_read64(TSC_MULTIPLIER));
6405 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
6406 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
6407 u16 status = vmcs_read16(GUEST_INTR_STATUS);
6408 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
6410 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
6411 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
6412 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
6413 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
6415 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
6416 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
6417 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
6418 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
6419 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
6420 pr_err("PLE Gap=%08x Window=%08x\n",
6421 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
6422 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
6423 pr_err("Virtual processor ID = 0x%04x\n",
6424 vmcs_read16(VIRTUAL_PROCESSOR_ID));
6425 if (secondary_exec_control & SECONDARY_EXEC_EPT_VIOLATION_VE) {
6426 struct vmx_ve_information *ve_info = vmx->ve_info;
6427 u64 ve_info_pa = vmcs_read64(VE_INFORMATION_ADDRESS);
6430 * If KVM is dumping the VMCS, then something has gone wrong
6431 * already. Derefencing an address from the VMCS, which could
6432 * very well be corrupted, is a terrible idea. The virtual
6433 * address is known so use it.
6435 pr_err("VE info address = 0x%016llx%s\n", ve_info_pa,
6436 ve_info_pa == __pa(ve_info) ? "" : "(corrupted!)");
6437 pr_err("ve_info: 0x%08x 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%04x\n",
6438 ve_info->exit_reason, ve_info->delivery,
6439 ve_info->exit_qualification,
6440 ve_info->guest_linear_address,
6441 ve_info->guest_physical_address, ve_info->eptp_index);
6446 * The guest has exited. See if we can fix it or if we need userspace
6447 * assistance.
6449 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6451 struct vcpu_vmx *vmx = to_vmx(vcpu);
6452 union vmx_exit_reason exit_reason = vmx->exit_reason;
6453 u32 vectoring_info = vmx->idt_vectoring_info;
6454 u16 exit_handler_index;
6457 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
6458 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
6459 * querying dirty_bitmap, we only need to kick all vcpus out of guest
6460 * mode as if vcpus is in root mode, the PML buffer must has been
6461 * flushed already. Note, PML is never enabled in hardware while
6462 * running L2.
6464 if (enable_pml && !is_guest_mode(vcpu))
6465 vmx_flush_pml_buffer(vcpu);
6468 * KVM should never reach this point with a pending nested VM-Enter.
6469 * More specifically, short-circuiting VM-Entry to emulate L2 due to
6470 * invalid guest state should never happen as that means KVM knowingly
6471 * allowed a nested VM-Enter with an invalid vmcs12. More below.
6473 if (KVM_BUG_ON(vmx->nested.nested_run_pending, vcpu->kvm))
6474 return -EIO;
6476 if (is_guest_mode(vcpu)) {
6478 * PML is never enabled when running L2, bail immediately if a
6479 * PML full exit occurs as something is horribly wrong.
6481 if (exit_reason.basic == EXIT_REASON_PML_FULL)
6482 goto unexpected_vmexit;
6485 * The host physical addresses of some pages of guest memory
6486 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6487 * Page). The CPU may write to these pages via their host
6488 * physical address while L2 is running, bypassing any
6489 * address-translation-based dirty tracking (e.g. EPT write
6490 * protection).
6492 * Mark them dirty on every exit from L2 to prevent them from
6493 * getting out of sync with dirty tracking.
6495 nested_mark_vmcs12_pages_dirty(vcpu);
6498 * Synthesize a triple fault if L2 state is invalid. In normal
6499 * operation, nested VM-Enter rejects any attempt to enter L2
6500 * with invalid state. However, those checks are skipped if
6501 * state is being stuffed via RSM or KVM_SET_NESTED_STATE. If
6502 * L2 state is invalid, it means either L1 modified SMRAM state
6503 * or userspace provided bad state. Synthesize TRIPLE_FAULT as
6504 * doing so is architecturally allowed in the RSM case, and is
6505 * the least awful solution for the userspace case without
6506 * risking false positives.
6508 if (vmx->emulation_required) {
6509 nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
6510 return 1;
6513 if (nested_vmx_reflect_vmexit(vcpu))
6514 return 1;
6517 /* If guest state is invalid, start emulating. L2 is handled above. */
6518 if (vmx->emulation_required)
6519 return handle_invalid_guest_state(vcpu);
6521 if (exit_reason.failed_vmentry) {
6522 dump_vmcs(vcpu);
6523 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6524 vcpu->run->fail_entry.hardware_entry_failure_reason
6525 = exit_reason.full;
6526 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6527 return 0;
6530 if (unlikely(vmx->fail)) {
6531 dump_vmcs(vcpu);
6532 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6533 vcpu->run->fail_entry.hardware_entry_failure_reason
6534 = vmcs_read32(VM_INSTRUCTION_ERROR);
6535 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6536 return 0;
6540 * Note:
6541 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6542 * delivery event since it indicates guest is accessing MMIO.
6543 * The vm-exit can be triggered again after return to guest that
6544 * will cause infinite loop.
6546 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6547 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6548 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6549 exit_reason.basic != EXIT_REASON_PML_FULL &&
6550 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6551 exit_reason.basic != EXIT_REASON_TASK_SWITCH &&
6552 exit_reason.basic != EXIT_REASON_NOTIFY)) {
6553 int ndata = 3;
6555 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6556 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6557 vcpu->run->internal.data[0] = vectoring_info;
6558 vcpu->run->internal.data[1] = exit_reason.full;
6559 vcpu->run->internal.data[2] = vmx_get_exit_qual(vcpu);
6560 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6561 vcpu->run->internal.data[ndata++] =
6562 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6564 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6565 vcpu->run->internal.ndata = ndata;
6566 return 0;
6569 if (unlikely(!enable_vnmi &&
6570 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6571 if (!vmx_interrupt_blocked(vcpu)) {
6572 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6573 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6574 vcpu->arch.nmi_pending) {
6576 * This CPU don't support us in finding the end of an
6577 * NMI-blocked window if the guest runs with IRQs
6578 * disabled. So we pull the trigger after 1 s of
6579 * futile waiting, but inform the user about this.
6581 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6582 "state on VCPU %d after 1 s timeout\n",
6583 __func__, vcpu->vcpu_id);
6584 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6588 if (exit_fastpath != EXIT_FASTPATH_NONE)
6589 return 1;
6591 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6592 goto unexpected_vmexit;
6593 #ifdef CONFIG_MITIGATION_RETPOLINE
6594 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6595 return kvm_emulate_wrmsr(vcpu);
6596 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6597 return handle_preemption_timer(vcpu);
6598 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6599 return handle_interrupt_window(vcpu);
6600 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6601 return handle_external_interrupt(vcpu);
6602 else if (exit_reason.basic == EXIT_REASON_HLT)
6603 return kvm_emulate_halt(vcpu);
6604 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6605 return handle_ept_misconfig(vcpu);
6606 #endif
6608 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6609 kvm_vmx_max_exit_handlers);
6610 if (!kvm_vmx_exit_handlers[exit_handler_index])
6611 goto unexpected_vmexit;
6613 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6615 unexpected_vmexit:
6616 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6617 exit_reason.full);
6618 dump_vmcs(vcpu);
6619 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6620 vcpu->run->internal.suberror =
6621 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6622 vcpu->run->internal.ndata = 2;
6623 vcpu->run->internal.data[0] = exit_reason.full;
6624 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6625 return 0;
6628 int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6630 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6633 * Exit to user space when bus lock detected to inform that there is
6634 * a bus lock in guest.
6636 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6637 if (ret > 0)
6638 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6640 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6641 return 0;
6643 return ret;
6647 * Software based L1D cache flush which is used when microcode providing
6648 * the cache control MSR is not loaded.
6650 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6651 * flush it is required to read in 64 KiB because the replacement algorithm
6652 * is not exactly LRU. This could be sized at runtime via topology
6653 * information but as all relevant affected CPUs have 32KiB L1D cache size
6654 * there is no point in doing so.
6656 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6658 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6661 * This code is only executed when the flush mode is 'cond' or
6662 * 'always'
6664 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6665 bool flush_l1d;
6668 * Clear the per-vcpu flush bit, it gets set again if the vCPU
6669 * is reloaded, i.e. if the vCPU is scheduled out or if KVM
6670 * exits to userspace, or if KVM reaches one of the unsafe
6671 * VMEXIT handlers, e.g. if KVM calls into the emulator.
6673 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6674 vcpu->arch.l1tf_flush_l1d = false;
6677 * Clear the per-cpu flush bit, it gets set again from
6678 * the interrupt handlers.
6680 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6681 kvm_clear_cpu_l1tf_flush_l1d();
6683 if (!flush_l1d)
6684 return;
6687 vcpu->stat.l1d_flush++;
6689 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6690 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6691 return;
6694 asm volatile(
6695 /* First ensure the pages are in the TLB */
6696 "xorl %%eax, %%eax\n"
6697 ".Lpopulate_tlb:\n\t"
6698 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6699 "addl $4096, %%eax\n\t"
6700 "cmpl %%eax, %[size]\n\t"
6701 "jne .Lpopulate_tlb\n\t"
6702 "xorl %%eax, %%eax\n\t"
6703 "cpuid\n\t"
6704 /* Now fill the cache */
6705 "xorl %%eax, %%eax\n"
6706 ".Lfill_cache:\n"
6707 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6708 "addl $64, %%eax\n\t"
6709 "cmpl %%eax, %[size]\n\t"
6710 "jne .Lfill_cache\n\t"
6711 "lfence\n"
6712 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6713 [size] "r" (size)
6714 : "eax", "ebx", "ecx", "edx");
6717 void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6719 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6720 int tpr_threshold;
6722 if (is_guest_mode(vcpu) &&
6723 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6724 return;
6726 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6727 if (is_guest_mode(vcpu))
6728 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6729 else
6730 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6733 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6735 struct vcpu_vmx *vmx = to_vmx(vcpu);
6736 u32 sec_exec_control;
6738 if (!lapic_in_kernel(vcpu))
6739 return;
6741 if (!flexpriority_enabled &&
6742 !cpu_has_vmx_virtualize_x2apic_mode())
6743 return;
6745 /* Postpone execution until vmcs01 is the current VMCS. */
6746 if (is_guest_mode(vcpu)) {
6747 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6748 return;
6751 sec_exec_control = secondary_exec_controls_get(vmx);
6752 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6753 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6755 switch (kvm_get_apic_mode(vcpu)) {
6756 case LAPIC_MODE_INVALID:
6757 WARN_ONCE(true, "Invalid local APIC state");
6758 break;
6759 case LAPIC_MODE_DISABLED:
6760 break;
6761 case LAPIC_MODE_XAPIC:
6762 if (flexpriority_enabled) {
6763 sec_exec_control |=
6764 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6765 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6768 * Flush the TLB, reloading the APIC access page will
6769 * only do so if its physical address has changed, but
6770 * the guest may have inserted a non-APIC mapping into
6771 * the TLB while the APIC access page was disabled.
6773 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6775 break;
6776 case LAPIC_MODE_X2APIC:
6777 if (cpu_has_vmx_virtualize_x2apic_mode())
6778 sec_exec_control |=
6779 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6780 break;
6782 secondary_exec_controls_set(vmx, sec_exec_control);
6784 vmx_update_msr_bitmap_x2apic(vcpu);
6787 void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6789 const gfn_t gfn = APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT;
6790 struct kvm *kvm = vcpu->kvm;
6791 struct kvm_memslots *slots = kvm_memslots(kvm);
6792 struct kvm_memory_slot *slot;
6793 unsigned long mmu_seq;
6794 kvm_pfn_t pfn;
6796 /* Defer reload until vmcs01 is the current VMCS. */
6797 if (is_guest_mode(vcpu)) {
6798 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6799 return;
6802 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6803 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6804 return;
6807 * Explicitly grab the memslot using KVM's internal slot ID to ensure
6808 * KVM doesn't unintentionally grab a userspace memslot. It _should_
6809 * be impossible for userspace to create a memslot for the APIC when
6810 * APICv is enabled, but paranoia won't hurt in this case.
6812 slot = id_to_memslot(slots, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT);
6813 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
6814 return;
6817 * Ensure that the mmu_notifier sequence count is read before KVM
6818 * retrieves the pfn from the primary MMU. Note, the memslot is
6819 * protected by SRCU, not the mmu_notifier. Pairs with the smp_wmb()
6820 * in kvm_mmu_invalidate_end().
6822 mmu_seq = kvm->mmu_invalidate_seq;
6823 smp_rmb();
6826 * No need to retry if the memslot does not exist or is invalid. KVM
6827 * controls the APIC-access page memslot, and only deletes the memslot
6828 * if APICv is permanently inhibited, i.e. the memslot won't reappear.
6830 pfn = gfn_to_pfn_memslot(slot, gfn);
6831 if (is_error_noslot_pfn(pfn))
6832 return;
6834 read_lock(&vcpu->kvm->mmu_lock);
6835 if (mmu_invalidate_retry_gfn(kvm, mmu_seq, gfn)) {
6836 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6837 read_unlock(&vcpu->kvm->mmu_lock);
6838 goto out;
6841 vmcs_write64(APIC_ACCESS_ADDR, pfn_to_hpa(pfn));
6842 read_unlock(&vcpu->kvm->mmu_lock);
6845 * No need for a manual TLB flush at this point, KVM has already done a
6846 * flush if there were SPTEs pointing at the previous page.
6848 out:
6850 * Do not pin apic access page in memory, the MMU notifier
6851 * will call us again if it is migrated or swapped out.
6853 kvm_release_pfn_clean(pfn);
6856 void vmx_hwapic_isr_update(int max_isr)
6858 u16 status;
6859 u8 old;
6861 if (max_isr == -1)
6862 max_isr = 0;
6864 status = vmcs_read16(GUEST_INTR_STATUS);
6865 old = status >> 8;
6866 if (max_isr != old) {
6867 status &= 0xff;
6868 status |= max_isr << 8;
6869 vmcs_write16(GUEST_INTR_STATUS, status);
6873 static void vmx_set_rvi(int vector)
6875 u16 status;
6876 u8 old;
6878 if (vector == -1)
6879 vector = 0;
6881 status = vmcs_read16(GUEST_INTR_STATUS);
6882 old = (u8)status & 0xff;
6883 if ((u8)vector != old) {
6884 status &= ~0xff;
6885 status |= (u8)vector;
6886 vmcs_write16(GUEST_INTR_STATUS, status);
6890 void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6893 * When running L2, updating RVI is only relevant when
6894 * vmcs12 virtual-interrupt-delivery enabled.
6895 * However, it can be enabled only when L1 also
6896 * intercepts external-interrupts and in that case
6897 * we should not update vmcs02 RVI but instead intercept
6898 * interrupt. Therefore, do nothing when running L2.
6900 if (!is_guest_mode(vcpu))
6901 vmx_set_rvi(max_irr);
6904 int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6906 struct vcpu_vmx *vmx = to_vmx(vcpu);
6907 int max_irr;
6908 bool got_posted_interrupt;
6910 if (KVM_BUG_ON(!enable_apicv, vcpu->kvm))
6911 return -EIO;
6913 if (pi_test_on(&vmx->pi_desc)) {
6914 pi_clear_on(&vmx->pi_desc);
6916 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6917 * But on x86 this is just a compiler barrier anyway.
6919 smp_mb__after_atomic();
6920 got_posted_interrupt =
6921 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6922 } else {
6923 max_irr = kvm_lapic_find_highest_irr(vcpu);
6924 got_posted_interrupt = false;
6928 * Newly recognized interrupts are injected via either virtual interrupt
6929 * delivery (RVI) or KVM_REQ_EVENT. Virtual interrupt delivery is
6930 * disabled in two cases:
6932 * 1) If L2 is running and the vCPU has a new pending interrupt. If L1
6933 * wants to exit on interrupts, KVM_REQ_EVENT is needed to synthesize a
6934 * VM-Exit to L1. If L1 doesn't want to exit, the interrupt is injected
6935 * into L2, but KVM doesn't use virtual interrupt delivery to inject
6936 * interrupts into L2, and so KVM_REQ_EVENT is again needed.
6938 * 2) If APICv is disabled for this vCPU, assigned devices may still
6939 * attempt to post interrupts. The posted interrupt vector will cause
6940 * a VM-Exit and the subsequent entry will call sync_pir_to_irr.
6942 if (!is_guest_mode(vcpu) && kvm_vcpu_apicv_active(vcpu))
6943 vmx_set_rvi(max_irr);
6944 else if (got_posted_interrupt)
6945 kvm_make_request(KVM_REQ_EVENT, vcpu);
6947 return max_irr;
6950 void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6952 if (!kvm_vcpu_apicv_active(vcpu))
6953 return;
6955 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6956 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6957 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6958 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6961 void vmx_apicv_pre_state_restore(struct kvm_vcpu *vcpu)
6963 struct vcpu_vmx *vmx = to_vmx(vcpu);
6965 pi_clear_on(&vmx->pi_desc);
6966 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6969 void vmx_do_interrupt_irqoff(unsigned long entry);
6970 void vmx_do_nmi_irqoff(void);
6972 static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
6975 * Save xfd_err to guest_fpu before interrupt is enabled, so the
6976 * MSR value is not clobbered by the host activity before the guest
6977 * has chance to consume it.
6979 * Do not blindly read xfd_err here, since this exception might
6980 * be caused by L1 interception on a platform which doesn't
6981 * support xfd at all.
6983 * Do it conditionally upon guest_fpu::xfd. xfd_err matters
6984 * only when xfd contains a non-zero value.
6986 * Queuing exception is done in vmx_handle_exit. See comment there.
6988 if (vcpu->arch.guest_fpu.fpstate->xfd)
6989 rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
6992 static void handle_exception_irqoff(struct kvm_vcpu *vcpu, u32 intr_info)
6994 /* if exit due to PF check for async PF */
6995 if (is_page_fault(intr_info))
6996 vcpu->arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6997 /* if exit due to NM, handle before interrupts are enabled */
6998 else if (is_nm_fault(intr_info))
6999 handle_nm_fault_irqoff(vcpu);
7000 /* Handle machine checks before interrupts are enabled */
7001 else if (is_machine_check(intr_info))
7002 kvm_machine_check();
7005 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu,
7006 u32 intr_info)
7008 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
7010 if (KVM_BUG(!is_external_intr(intr_info), vcpu->kvm,
7011 "unexpected VM-Exit interrupt info: 0x%x", intr_info))
7012 return;
7014 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
7015 if (cpu_feature_enabled(X86_FEATURE_FRED))
7016 fred_entry_from_kvm(EVENT_TYPE_EXTINT, vector);
7017 else
7018 vmx_do_interrupt_irqoff(gate_offset((gate_desc *)host_idt_base + vector));
7019 kvm_after_interrupt(vcpu);
7021 vcpu->arch.at_instruction_boundary = true;
7024 void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
7026 struct vcpu_vmx *vmx = to_vmx(vcpu);
7028 if (vmx->emulation_required)
7029 return;
7031 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
7032 handle_external_interrupt_irqoff(vcpu, vmx_get_intr_info(vcpu));
7033 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
7034 handle_exception_irqoff(vcpu, vmx_get_intr_info(vcpu));
7038 * The kvm parameter can be NULL (module initialization, or invocation before
7039 * VM creation). Be sure to check the kvm parameter before using it.
7041 bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
7043 switch (index) {
7044 case MSR_IA32_SMBASE:
7045 if (!IS_ENABLED(CONFIG_KVM_SMM))
7046 return false;
7048 * We cannot do SMM unless we can run the guest in big
7049 * real mode.
7051 return enable_unrestricted_guest || emulate_invalid_guest_state;
7052 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR:
7053 return nested;
7054 case MSR_AMD64_VIRT_SPEC_CTRL:
7055 case MSR_AMD64_TSC_RATIO:
7056 /* This is AMD only. */
7057 return false;
7058 default:
7059 return true;
7063 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
7065 u32 exit_intr_info;
7066 bool unblock_nmi;
7067 u8 vector;
7068 bool idtv_info_valid;
7070 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
7072 if (enable_vnmi) {
7073 if (vmx->loaded_vmcs->nmi_known_unmasked)
7074 return;
7076 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
7077 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
7078 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
7080 * SDM 3: 27.7.1.2 (September 2008)
7081 * Re-set bit "block by NMI" before VM entry if vmexit caused by
7082 * a guest IRET fault.
7083 * SDM 3: 23.2.2 (September 2008)
7084 * Bit 12 is undefined in any of the following cases:
7085 * If the VM exit sets the valid bit in the IDT-vectoring
7086 * information field.
7087 * If the VM exit is due to a double fault.
7089 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
7090 vector != DF_VECTOR && !idtv_info_valid)
7091 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
7092 GUEST_INTR_STATE_NMI);
7093 else
7094 vmx->loaded_vmcs->nmi_known_unmasked =
7095 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
7096 & GUEST_INTR_STATE_NMI);
7097 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
7098 vmx->loaded_vmcs->vnmi_blocked_time +=
7099 ktime_to_ns(ktime_sub(ktime_get(),
7100 vmx->loaded_vmcs->entry_time));
7103 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
7104 u32 idt_vectoring_info,
7105 int instr_len_field,
7106 int error_code_field)
7108 u8 vector;
7109 int type;
7110 bool idtv_info_valid;
7112 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
7114 vcpu->arch.nmi_injected = false;
7115 kvm_clear_exception_queue(vcpu);
7116 kvm_clear_interrupt_queue(vcpu);
7118 if (!idtv_info_valid)
7119 return;
7121 kvm_make_request(KVM_REQ_EVENT, vcpu);
7123 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
7124 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
7126 switch (type) {
7127 case INTR_TYPE_NMI_INTR:
7128 vcpu->arch.nmi_injected = true;
7130 * SDM 3: 27.7.1.2 (September 2008)
7131 * Clear bit "block by NMI" before VM entry if a NMI
7132 * delivery faulted.
7134 vmx_set_nmi_mask(vcpu, false);
7135 break;
7136 case INTR_TYPE_SOFT_EXCEPTION:
7137 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
7138 fallthrough;
7139 case INTR_TYPE_HARD_EXCEPTION:
7140 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
7141 u32 err = vmcs_read32(error_code_field);
7142 kvm_requeue_exception_e(vcpu, vector, err);
7143 } else
7144 kvm_requeue_exception(vcpu, vector);
7145 break;
7146 case INTR_TYPE_SOFT_INTR:
7147 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
7148 fallthrough;
7149 case INTR_TYPE_EXT_INTR:
7150 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
7151 break;
7152 default:
7153 break;
7157 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
7159 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
7160 VM_EXIT_INSTRUCTION_LEN,
7161 IDT_VECTORING_ERROR_CODE);
7164 void vmx_cancel_injection(struct kvm_vcpu *vcpu)
7166 __vmx_complete_interrupts(vcpu,
7167 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
7168 VM_ENTRY_INSTRUCTION_LEN,
7169 VM_ENTRY_EXCEPTION_ERROR_CODE);
7171 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
7174 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
7176 int i, nr_msrs;
7177 struct perf_guest_switch_msr *msrs;
7178 struct kvm_pmu *pmu = vcpu_to_pmu(&vmx->vcpu);
7180 pmu->host_cross_mapped_mask = 0;
7181 if (pmu->pebs_enable & pmu->global_ctrl)
7182 intel_pmu_cross_mapped_check(pmu);
7184 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
7185 msrs = perf_guest_get_msrs(&nr_msrs, (void *)pmu);
7186 if (!msrs)
7187 return;
7189 for (i = 0; i < nr_msrs; i++)
7190 if (msrs[i].host == msrs[i].guest)
7191 clear_atomic_switch_msr(vmx, msrs[i].msr);
7192 else
7193 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
7194 msrs[i].host, false);
7197 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu, bool force_immediate_exit)
7199 struct vcpu_vmx *vmx = to_vmx(vcpu);
7200 u64 tscl;
7201 u32 delta_tsc;
7203 if (force_immediate_exit) {
7204 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
7205 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
7206 } else if (vmx->hv_deadline_tsc != -1) {
7207 tscl = rdtsc();
7208 if (vmx->hv_deadline_tsc > tscl)
7209 /* set_hv_timer ensures the delta fits in 32-bits */
7210 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
7211 cpu_preemption_timer_multi);
7212 else
7213 delta_tsc = 0;
7215 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
7216 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
7217 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
7218 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
7219 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
7223 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
7225 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
7226 vmx->loaded_vmcs->host_state.rsp = host_rsp;
7227 vmcs_writel(HOST_RSP, host_rsp);
7231 void noinstr vmx_spec_ctrl_restore_host(struct vcpu_vmx *vmx,
7232 unsigned int flags)
7234 u64 hostval = this_cpu_read(x86_spec_ctrl_current);
7236 if (!cpu_feature_enabled(X86_FEATURE_MSR_SPEC_CTRL))
7237 return;
7239 if (flags & VMX_RUN_SAVE_SPEC_CTRL)
7240 vmx->spec_ctrl = __rdmsr(MSR_IA32_SPEC_CTRL);
7243 * If the guest/host SPEC_CTRL values differ, restore the host value.
7245 * For legacy IBRS, the IBRS bit always needs to be written after
7246 * transitioning from a less privileged predictor mode, regardless of
7247 * whether the guest/host values differ.
7249 if (cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS) ||
7250 vmx->spec_ctrl != hostval)
7251 native_wrmsrl(MSR_IA32_SPEC_CTRL, hostval);
7253 barrier_nospec();
7256 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu,
7257 bool force_immediate_exit)
7260 * If L2 is active, some VMX preemption timer exits can be handled in
7261 * the fastpath even, all other exits must use the slow path.
7263 if (is_guest_mode(vcpu) &&
7264 to_vmx(vcpu)->exit_reason.basic != EXIT_REASON_PREEMPTION_TIMER)
7265 return EXIT_FASTPATH_NONE;
7267 switch (to_vmx(vcpu)->exit_reason.basic) {
7268 case EXIT_REASON_MSR_WRITE:
7269 return handle_fastpath_set_msr_irqoff(vcpu);
7270 case EXIT_REASON_PREEMPTION_TIMER:
7271 return handle_fastpath_preemption_timer(vcpu, force_immediate_exit);
7272 case EXIT_REASON_HLT:
7273 return handle_fastpath_hlt(vcpu);
7274 default:
7275 return EXIT_FASTPATH_NONE;
7279 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
7280 unsigned int flags)
7282 struct vcpu_vmx *vmx = to_vmx(vcpu);
7284 guest_state_enter_irqoff();
7287 * L1D Flush includes CPU buffer clear to mitigate MDS, but VERW
7288 * mitigation for MDS is done late in VMentry and is still
7289 * executed in spite of L1D Flush. This is because an extra VERW
7290 * should not matter much after the big hammer L1D Flush.
7292 if (static_branch_unlikely(&vmx_l1d_should_flush))
7293 vmx_l1d_flush(vcpu);
7294 else if (static_branch_unlikely(&mmio_stale_data_clear) &&
7295 kvm_arch_has_assigned_device(vcpu->kvm))
7296 mds_clear_cpu_buffers();
7298 vmx_disable_fb_clear(vmx);
7300 if (vcpu->arch.cr2 != native_read_cr2())
7301 native_write_cr2(vcpu->arch.cr2);
7303 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
7304 flags);
7306 vcpu->arch.cr2 = native_read_cr2();
7307 vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
7309 vmx->idt_vectoring_info = 0;
7311 vmx_enable_fb_clear(vmx);
7313 if (unlikely(vmx->fail)) {
7314 vmx->exit_reason.full = 0xdead;
7315 goto out;
7318 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
7319 if (likely(!vmx->exit_reason.failed_vmentry))
7320 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
7322 if ((u16)vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI &&
7323 is_nmi(vmx_get_intr_info(vcpu))) {
7324 kvm_before_interrupt(vcpu, KVM_HANDLING_NMI);
7325 if (cpu_feature_enabled(X86_FEATURE_FRED))
7326 fred_entry_from_kvm(EVENT_TYPE_NMI, NMI_VECTOR);
7327 else
7328 vmx_do_nmi_irqoff();
7329 kvm_after_interrupt(vcpu);
7332 out:
7333 guest_state_exit_irqoff();
7336 fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu, bool force_immediate_exit)
7338 struct vcpu_vmx *vmx = to_vmx(vcpu);
7339 unsigned long cr3, cr4;
7341 /* Record the guest's net vcpu time for enforced NMI injections. */
7342 if (unlikely(!enable_vnmi &&
7343 vmx->loaded_vmcs->soft_vnmi_blocked))
7344 vmx->loaded_vmcs->entry_time = ktime_get();
7347 * Don't enter VMX if guest state is invalid, let the exit handler
7348 * start emulation until we arrive back to a valid state. Synthesize a
7349 * consistency check VM-Exit due to invalid guest state and bail.
7351 if (unlikely(vmx->emulation_required)) {
7352 vmx->fail = 0;
7354 vmx->exit_reason.full = EXIT_REASON_INVALID_STATE;
7355 vmx->exit_reason.failed_vmentry = 1;
7356 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_1);
7357 vmx->exit_qualification = ENTRY_FAIL_DEFAULT;
7358 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_2);
7359 vmx->exit_intr_info = 0;
7360 return EXIT_FASTPATH_NONE;
7363 trace_kvm_entry(vcpu, force_immediate_exit);
7365 if (vmx->ple_window_dirty) {
7366 vmx->ple_window_dirty = false;
7367 vmcs_write32(PLE_WINDOW, vmx->ple_window);
7371 * We did this in prepare_switch_to_guest, because it needs to
7372 * be within srcu_read_lock.
7374 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
7376 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
7377 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
7378 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
7379 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
7380 vcpu->arch.regs_dirty = 0;
7383 * Refresh vmcs.HOST_CR3 if necessary. This must be done immediately
7384 * prior to VM-Enter, as the kernel may load a new ASID (PCID) any time
7385 * it switches back to the current->mm, which can occur in KVM context
7386 * when switching to a temporary mm to patch kernel code, e.g. if KVM
7387 * toggles a static key while handling a VM-Exit.
7389 cr3 = __get_current_cr3_fast();
7390 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
7391 vmcs_writel(HOST_CR3, cr3);
7392 vmx->loaded_vmcs->host_state.cr3 = cr3;
7395 cr4 = cr4_read_shadow();
7396 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
7397 vmcs_writel(HOST_CR4, cr4);
7398 vmx->loaded_vmcs->host_state.cr4 = cr4;
7401 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
7402 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
7403 set_debugreg(vcpu->arch.dr6, 6);
7405 /* When single-stepping over STI and MOV SS, we must clear the
7406 * corresponding interruptibility bits in the guest state. Otherwise
7407 * vmentry fails as it then expects bit 14 (BS) in pending debug
7408 * exceptions being set, but that's not correct for the guest debugging
7409 * case. */
7410 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7411 vmx_set_interrupt_shadow(vcpu, 0);
7413 kvm_load_guest_xsave_state(vcpu);
7415 pt_guest_enter(vmx);
7417 atomic_switch_perf_msrs(vmx);
7418 if (intel_pmu_lbr_is_enabled(vcpu))
7419 vmx_passthrough_lbr_msrs(vcpu);
7421 if (enable_preemption_timer)
7422 vmx_update_hv_timer(vcpu, force_immediate_exit);
7423 else if (force_immediate_exit)
7424 smp_send_reschedule(vcpu->cpu);
7426 kvm_wait_lapic_expire(vcpu);
7428 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
7429 vmx_vcpu_enter_exit(vcpu, __vmx_vcpu_run_flags(vmx));
7431 /* All fields are clean at this point */
7432 if (kvm_is_using_evmcs()) {
7433 current_evmcs->hv_clean_fields |=
7434 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
7436 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
7439 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
7440 if (vmx->host_debugctlmsr)
7441 update_debugctlmsr(vmx->host_debugctlmsr);
7443 #ifndef CONFIG_X86_64
7445 * The sysexit path does not restore ds/es, so we must set them to
7446 * a reasonable value ourselves.
7448 * We can't defer this to vmx_prepare_switch_to_host() since that
7449 * function may be executed in interrupt context, which saves and
7450 * restore segments around it, nullifying its effect.
7452 loadsegment(ds, __USER_DS);
7453 loadsegment(es, __USER_DS);
7454 #endif
7456 pt_guest_exit(vmx);
7458 kvm_load_host_xsave_state(vcpu);
7460 if (is_guest_mode(vcpu)) {
7462 * Track VMLAUNCH/VMRESUME that have made past guest state
7463 * checking.
7465 if (vmx->nested.nested_run_pending &&
7466 !vmx->exit_reason.failed_vmentry)
7467 ++vcpu->stat.nested_run;
7469 vmx->nested.nested_run_pending = 0;
7472 if (unlikely(vmx->fail))
7473 return EXIT_FASTPATH_NONE;
7475 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
7476 kvm_machine_check();
7478 trace_kvm_exit(vcpu, KVM_ISA_VMX);
7480 if (unlikely(vmx->exit_reason.failed_vmentry))
7481 return EXIT_FASTPATH_NONE;
7483 vmx->loaded_vmcs->launched = 1;
7485 vmx_recover_nmi_blocking(vmx);
7486 vmx_complete_interrupts(vmx);
7488 return vmx_exit_handlers_fastpath(vcpu, force_immediate_exit);
7491 void vmx_vcpu_free(struct kvm_vcpu *vcpu)
7493 struct vcpu_vmx *vmx = to_vmx(vcpu);
7495 if (enable_pml)
7496 vmx_destroy_pml_buffer(vmx);
7497 free_vpid(vmx->vpid);
7498 nested_vmx_free_vcpu(vcpu);
7499 free_loaded_vmcs(vmx->loaded_vmcs);
7500 free_page((unsigned long)vmx->ve_info);
7503 int vmx_vcpu_create(struct kvm_vcpu *vcpu)
7505 struct vmx_uret_msr *tsx_ctrl;
7506 struct vcpu_vmx *vmx;
7507 int i, err;
7509 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
7510 vmx = to_vmx(vcpu);
7512 INIT_LIST_HEAD(&vmx->pi_wakeup_list);
7514 err = -ENOMEM;
7516 vmx->vpid = allocate_vpid();
7519 * If PML is turned on, failure on enabling PML just results in failure
7520 * of creating the vcpu, therefore we can simplify PML logic (by
7521 * avoiding dealing with cases, such as enabling PML partially on vcpus
7522 * for the guest), etc.
7524 if (enable_pml) {
7525 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
7526 if (!vmx->pml_pg)
7527 goto free_vpid;
7530 for (i = 0; i < kvm_nr_uret_msrs; ++i)
7531 vmx->guest_uret_msrs[i].mask = -1ull;
7532 if (boot_cpu_has(X86_FEATURE_RTM)) {
7534 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception.
7535 * Keep the host value unchanged to avoid changing CPUID bits
7536 * under the host kernel's feet.
7538 tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7539 if (tsx_ctrl)
7540 tsx_ctrl->mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
7543 err = alloc_loaded_vmcs(&vmx->vmcs01);
7544 if (err < 0)
7545 goto free_pml;
7548 * Use Hyper-V 'Enlightened MSR Bitmap' feature when KVM runs as a
7549 * nested (L1) hypervisor and Hyper-V in L0 supports it. Enable the
7550 * feature only for vmcs01, KVM currently isn't equipped to realize any
7551 * performance benefits from enabling it for vmcs02.
7553 if (kvm_is_using_evmcs() &&
7554 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
7555 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
7557 evmcs->hv_enlightenments_control.msr_bitmap = 1;
7560 /* The MSR bitmap starts with all ones */
7561 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7562 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7564 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
7565 #ifdef CONFIG_X86_64
7566 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
7567 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
7568 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
7569 #endif
7570 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
7571 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
7572 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
7573 if (kvm_cstate_in_guest(vcpu->kvm)) {
7574 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
7575 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
7576 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
7577 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
7580 vmx->loaded_vmcs = &vmx->vmcs01;
7582 if (cpu_need_virtualize_apic_accesses(vcpu)) {
7583 err = kvm_alloc_apic_access_page(vcpu->kvm);
7584 if (err)
7585 goto free_vmcs;
7588 if (enable_ept && !enable_unrestricted_guest) {
7589 err = init_rmode_identity_map(vcpu->kvm);
7590 if (err)
7591 goto free_vmcs;
7594 err = -ENOMEM;
7595 if (vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_EPT_VIOLATION_VE) {
7596 struct page *page;
7598 BUILD_BUG_ON(sizeof(*vmx->ve_info) > PAGE_SIZE);
7600 /* ve_info must be page aligned. */
7601 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
7602 if (!page)
7603 goto free_vmcs;
7605 vmx->ve_info = page_to_virt(page);
7608 if (vmx_can_use_ipiv(vcpu))
7609 WRITE_ONCE(to_kvm_vmx(vcpu->kvm)->pid_table[vcpu->vcpu_id],
7610 __pa(&vmx->pi_desc) | PID_TABLE_ENTRY_VALID);
7612 return 0;
7614 free_vmcs:
7615 free_loaded_vmcs(vmx->loaded_vmcs);
7616 free_pml:
7617 vmx_destroy_pml_buffer(vmx);
7618 free_vpid:
7619 free_vpid(vmx->vpid);
7620 return err;
7623 #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"
7624 #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"
7626 int vmx_vm_init(struct kvm *kvm)
7628 if (!ple_gap)
7629 kvm->arch.pause_in_guest = true;
7631 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7632 switch (l1tf_mitigation) {
7633 case L1TF_MITIGATION_OFF:
7634 case L1TF_MITIGATION_FLUSH_NOWARN:
7635 /* 'I explicitly don't care' is set */
7636 break;
7637 case L1TF_MITIGATION_FLUSH:
7638 case L1TF_MITIGATION_FLUSH_NOSMT:
7639 case L1TF_MITIGATION_FULL:
7641 * Warn upon starting the first VM in a potentially
7642 * insecure environment.
7644 if (sched_smt_active())
7645 pr_warn_once(L1TF_MSG_SMT);
7646 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7647 pr_warn_once(L1TF_MSG_L1D);
7648 break;
7649 case L1TF_MITIGATION_FULL_FORCE:
7650 /* Flush is enforced */
7651 break;
7654 return 0;
7657 u8 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7660 * Force UC for host MMIO regions, as allowing the guest to access MMIO
7661 * with cacheable accesses will result in Machine Checks.
7663 if (is_mmio)
7664 return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
7667 * Force WB and ignore guest PAT if the VM does NOT have a non-coherent
7668 * device attached. Letting the guest control memory types on Intel
7669 * CPUs may result in unexpected behavior, and so KVM's ABI is to trust
7670 * the guest to behave only as a last resort.
7672 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
7673 return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7675 return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT);
7678 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx, u32 new_ctl)
7681 * These bits in the secondary execution controls field
7682 * are dynamic, the others are mostly based on the hypervisor
7683 * architecture and the guest's CPUID. Do not touch the
7684 * dynamic bits.
7686 u32 mask =
7687 SECONDARY_EXEC_SHADOW_VMCS |
7688 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7689 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7690 SECONDARY_EXEC_DESC;
7692 u32 cur_ctl = secondary_exec_controls_get(vmx);
7694 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7698 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7699 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7701 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7703 struct vcpu_vmx *vmx = to_vmx(vcpu);
7704 struct kvm_cpuid_entry2 *entry;
7706 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7707 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7709 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7710 if (entry && (entry->_reg & (_cpuid_mask))) \
7711 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7712 } while (0)
7714 entry = kvm_find_cpuid_entry(vcpu, 0x1);
7715 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7716 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7717 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7718 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7719 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7720 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7721 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7722 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7723 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7724 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7725 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7726 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7727 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7728 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7730 entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 0);
7731 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7732 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7733 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7734 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7735 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7736 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7738 entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 1);
7739 cr4_fixed1_update(X86_CR4_LAM_SUP, eax, feature_bit(LAM));
7741 #undef cr4_fixed1_update
7744 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7746 struct vcpu_vmx *vmx = to_vmx(vcpu);
7747 struct kvm_cpuid_entry2 *best = NULL;
7748 int i;
7750 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7751 best = kvm_find_cpuid_entry_index(vcpu, 0x14, i);
7752 if (!best)
7753 return;
7754 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7755 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7756 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7757 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7760 /* Get the number of configurable Address Ranges for filtering */
7761 vmx->pt_desc.num_address_ranges = intel_pt_validate_cap(vmx->pt_desc.caps,
7762 PT_CAP_num_address_ranges);
7764 /* Initialize and clear the no dependency bits */
7765 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7766 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC |
7767 RTIT_CTL_BRANCH_EN);
7770 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7771 * will inject an #GP
7773 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7774 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7777 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7778 * PSBFreq can be set
7780 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7781 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7782 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7785 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn and MTCFreq can be set
7787 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7788 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7789 RTIT_CTL_MTC_RANGE);
7791 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7792 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7793 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7794 RTIT_CTL_PTW_EN);
7796 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7797 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7798 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7800 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7801 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7802 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7804 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7805 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7806 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7808 /* unmask address range configure area */
7809 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++)
7810 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7813 void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7815 struct vcpu_vmx *vmx = to_vmx(vcpu);
7818 * XSAVES is effectively enabled if and only if XSAVE is also exposed
7819 * to the guest. XSAVES depends on CR4.OSXSAVE, and CR4.OSXSAVE can be
7820 * set if and only if XSAVE is supported.
7822 if (boot_cpu_has(X86_FEATURE_XSAVE) &&
7823 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE))
7824 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_XSAVES);
7826 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_VMX);
7827 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_LAM);
7829 vmx_setup_uret_msrs(vmx);
7831 if (cpu_has_secondary_exec_ctrls())
7832 vmcs_set_secondary_exec_control(vmx,
7833 vmx_secondary_exec_control(vmx));
7835 if (guest_can_use(vcpu, X86_FEATURE_VMX))
7836 vmx->msr_ia32_feature_control_valid_bits |=
7837 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7838 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7839 else
7840 vmx->msr_ia32_feature_control_valid_bits &=
7841 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7842 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7844 if (guest_can_use(vcpu, X86_FEATURE_VMX))
7845 nested_vmx_cr_fixed1_bits_update(vcpu);
7847 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7848 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7849 update_intel_pt_cfg(vcpu);
7851 if (boot_cpu_has(X86_FEATURE_RTM)) {
7852 struct vmx_uret_msr *msr;
7853 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7854 if (msr) {
7855 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7856 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7860 if (kvm_cpu_cap_has(X86_FEATURE_XFD))
7861 vmx_set_intercept_for_msr(vcpu, MSR_IA32_XFD_ERR, MSR_TYPE_R,
7862 !guest_cpuid_has(vcpu, X86_FEATURE_XFD));
7864 if (boot_cpu_has(X86_FEATURE_IBPB))
7865 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W,
7866 !guest_has_pred_cmd_msr(vcpu));
7868 if (boot_cpu_has(X86_FEATURE_FLUSH_L1D))
7869 vmx_set_intercept_for_msr(vcpu, MSR_IA32_FLUSH_CMD, MSR_TYPE_W,
7870 !guest_cpuid_has(vcpu, X86_FEATURE_FLUSH_L1D));
7872 set_cr4_guest_host_mask(vmx);
7874 vmx_write_encls_bitmap(vcpu, NULL);
7875 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7876 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7877 else
7878 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7880 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7881 vmx->msr_ia32_feature_control_valid_bits |=
7882 FEAT_CTL_SGX_LC_ENABLED;
7883 else
7884 vmx->msr_ia32_feature_control_valid_bits &=
7885 ~FEAT_CTL_SGX_LC_ENABLED;
7887 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7888 vmx_update_exception_bitmap(vcpu);
7891 static __init u64 vmx_get_perf_capabilities(void)
7893 u64 perf_cap = PMU_CAP_FW_WRITES;
7894 u64 host_perf_cap = 0;
7896 if (!enable_pmu)
7897 return 0;
7899 if (boot_cpu_has(X86_FEATURE_PDCM))
7900 rdmsrl(MSR_IA32_PERF_CAPABILITIES, host_perf_cap);
7902 if (!cpu_feature_enabled(X86_FEATURE_ARCH_LBR)) {
7903 x86_perf_get_lbr(&vmx_lbr_caps);
7906 * KVM requires LBR callstack support, as the overhead due to
7907 * context switching LBRs without said support is too high.
7908 * See intel_pmu_create_guest_lbr_event() for more info.
7910 if (!vmx_lbr_caps.has_callstack)
7911 memset(&vmx_lbr_caps, 0, sizeof(vmx_lbr_caps));
7912 else if (vmx_lbr_caps.nr)
7913 perf_cap |= host_perf_cap & PMU_CAP_LBR_FMT;
7916 if (vmx_pebs_supported()) {
7917 perf_cap |= host_perf_cap & PERF_CAP_PEBS_MASK;
7920 * Disallow adaptive PEBS as it is functionally broken, can be
7921 * used by the guest to read *host* LBRs, and can be used to
7922 * bypass userspace event filters. To correctly and safely
7923 * support adaptive PEBS, KVM needs to:
7925 * 1. Account for the ADAPTIVE flag when (re)programming fixed
7926 * counters.
7928 * 2. Gain support from perf (or take direct control of counter
7929 * programming) to support events without adaptive PEBS
7930 * enabled for the hardware counter.
7932 * 3. Ensure LBR MSRs cannot hold host data on VM-Entry with
7933 * adaptive PEBS enabled and MSR_PEBS_DATA_CFG.LBRS=1.
7935 * 4. Document which PMU events are effectively exposed to the
7936 * guest via adaptive PEBS, and make adaptive PEBS mutually
7937 * exclusive with KVM_SET_PMU_EVENT_FILTER if necessary.
7939 perf_cap &= ~PERF_CAP_PEBS_BASELINE;
7942 return perf_cap;
7945 static __init void vmx_set_cpu_caps(void)
7947 kvm_set_cpu_caps();
7949 /* CPUID 0x1 */
7950 if (nested)
7951 kvm_cpu_cap_set(X86_FEATURE_VMX);
7953 /* CPUID 0x7 */
7954 if (kvm_mpx_supported())
7955 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7956 if (!cpu_has_vmx_invpcid())
7957 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7958 if (vmx_pt_mode_is_host_guest())
7959 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7960 if (vmx_pebs_supported()) {
7961 kvm_cpu_cap_check_and_set(X86_FEATURE_DS);
7962 kvm_cpu_cap_check_and_set(X86_FEATURE_DTES64);
7965 if (!enable_pmu)
7966 kvm_cpu_cap_clear(X86_FEATURE_PDCM);
7967 kvm_caps.supported_perf_cap = vmx_get_perf_capabilities();
7969 if (!enable_sgx) {
7970 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7971 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7972 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7973 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7974 kvm_cpu_cap_clear(X86_FEATURE_SGX_EDECCSSA);
7977 if (vmx_umip_emulated())
7978 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7980 /* CPUID 0xD.1 */
7981 kvm_caps.supported_xss = 0;
7982 if (!cpu_has_vmx_xsaves())
7983 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7985 /* CPUID 0x80000001 and 0x7 (RDPID) */
7986 if (!cpu_has_vmx_rdtscp()) {
7987 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7988 kvm_cpu_cap_clear(X86_FEATURE_RDPID);
7991 if (cpu_has_vmx_waitpkg())
7992 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7995 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7996 struct x86_instruction_info *info)
7998 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7999 unsigned short port;
8000 bool intercept;
8001 int size;
8003 if (info->intercept == x86_intercept_in ||
8004 info->intercept == x86_intercept_ins) {
8005 port = info->src_val;
8006 size = info->dst_bytes;
8007 } else {
8008 port = info->dst_val;
8009 size = info->src_bytes;
8013 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
8014 * VM-exits depend on the 'unconditional IO exiting' VM-execution
8015 * control.
8017 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
8019 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
8020 intercept = nested_cpu_has(vmcs12,
8021 CPU_BASED_UNCOND_IO_EXITING);
8022 else
8023 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
8025 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
8026 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
8029 int vmx_check_intercept(struct kvm_vcpu *vcpu,
8030 struct x86_instruction_info *info,
8031 enum x86_intercept_stage stage,
8032 struct x86_exception *exception)
8034 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8036 switch (info->intercept) {
8038 * RDPID causes #UD if disabled through secondary execution controls.
8039 * Because it is marked as EmulateOnUD, we need to intercept it here.
8040 * Note, RDPID is hidden behind ENABLE_RDTSCP.
8042 case x86_intercept_rdpid:
8043 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
8044 exception->vector = UD_VECTOR;
8045 exception->error_code_valid = false;
8046 return X86EMUL_PROPAGATE_FAULT;
8048 break;
8050 case x86_intercept_in:
8051 case x86_intercept_ins:
8052 case x86_intercept_out:
8053 case x86_intercept_outs:
8054 return vmx_check_intercept_io(vcpu, info);
8056 case x86_intercept_lgdt:
8057 case x86_intercept_lidt:
8058 case x86_intercept_lldt:
8059 case x86_intercept_ltr:
8060 case x86_intercept_sgdt:
8061 case x86_intercept_sidt:
8062 case x86_intercept_sldt:
8063 case x86_intercept_str:
8064 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
8065 return X86EMUL_CONTINUE;
8067 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
8068 break;
8070 case x86_intercept_pause:
8072 * PAUSE is a single-byte NOP with a REPE prefix, i.e. collides
8073 * with vanilla NOPs in the emulator. Apply the interception
8074 * check only to actual PAUSE instructions. Don't check
8075 * PAUSE-loop-exiting, software can't expect a given PAUSE to
8076 * exit, i.e. KVM is within its rights to allow L2 to execute
8077 * the PAUSE.
8079 if ((info->rep_prefix != REPE_PREFIX) ||
8080 !nested_cpu_has2(vmcs12, CPU_BASED_PAUSE_EXITING))
8081 return X86EMUL_CONTINUE;
8083 break;
8085 /* TODO: check more intercepts... */
8086 default:
8087 break;
8090 return X86EMUL_UNHANDLEABLE;
8093 #ifdef CONFIG_X86_64
8094 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
8095 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
8096 u64 divisor, u64 *result)
8098 u64 low = a << shift, high = a >> (64 - shift);
8100 /* To avoid the overflow on divq */
8101 if (high >= divisor)
8102 return 1;
8104 /* Low hold the result, high hold rem which is discarded */
8105 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
8106 "rm" (divisor), "0" (low), "1" (high));
8107 *result = low;
8109 return 0;
8112 int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
8113 bool *expired)
8115 struct vcpu_vmx *vmx;
8116 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
8117 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
8119 vmx = to_vmx(vcpu);
8120 tscl = rdtsc();
8121 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
8122 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
8123 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
8124 ktimer->timer_advance_ns);
8126 if (delta_tsc > lapic_timer_advance_cycles)
8127 delta_tsc -= lapic_timer_advance_cycles;
8128 else
8129 delta_tsc = 0;
8131 /* Convert to host delta tsc if tsc scaling is enabled */
8132 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio &&
8133 delta_tsc && u64_shl_div_u64(delta_tsc,
8134 kvm_caps.tsc_scaling_ratio_frac_bits,
8135 vcpu->arch.l1_tsc_scaling_ratio, &delta_tsc))
8136 return -ERANGE;
8139 * If the delta tsc can't fit in the 32 bit after the multi shift,
8140 * we can't use the preemption timer.
8141 * It's possible that it fits on later vmentries, but checking
8142 * on every vmentry is costly so we just use an hrtimer.
8144 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
8145 return -ERANGE;
8147 vmx->hv_deadline_tsc = tscl + delta_tsc;
8148 *expired = !delta_tsc;
8149 return 0;
8152 void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
8154 to_vmx(vcpu)->hv_deadline_tsc = -1;
8156 #endif
8158 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
8160 struct vcpu_vmx *vmx = to_vmx(vcpu);
8162 if (WARN_ON_ONCE(!enable_pml))
8163 return;
8165 if (is_guest_mode(vcpu)) {
8166 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
8167 return;
8171 * Note, nr_memslots_dirty_logging can be changed concurrent with this
8172 * code, but in that case another update request will be made and so
8173 * the guest will never run with a stale PML value.
8175 if (atomic_read(&vcpu->kvm->nr_memslots_dirty_logging))
8176 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
8177 else
8178 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
8181 void vmx_setup_mce(struct kvm_vcpu *vcpu)
8183 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
8184 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
8185 FEAT_CTL_LMCE_ENABLED;
8186 else
8187 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
8188 ~FEAT_CTL_LMCE_ENABLED;
8191 #ifdef CONFIG_KVM_SMM
8192 int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
8194 /* we need a nested vmexit to enter SMM, postpone if run is pending */
8195 if (to_vmx(vcpu)->nested.nested_run_pending)
8196 return -EBUSY;
8197 return !is_smm(vcpu);
8200 int vmx_enter_smm(struct kvm_vcpu *vcpu, union kvm_smram *smram)
8202 struct vcpu_vmx *vmx = to_vmx(vcpu);
8205 * TODO: Implement custom flows for forcing the vCPU out/in of L2 on
8206 * SMI and RSM. Using the common VM-Exit + VM-Enter routines is wrong
8207 * SMI and RSM only modify state that is saved and restored via SMRAM.
8208 * E.g. most MSRs are left untouched, but many are modified by VM-Exit
8209 * and VM-Enter, and thus L2's values may be corrupted on SMI+RSM.
8211 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
8212 if (vmx->nested.smm.guest_mode)
8213 nested_vmx_vmexit(vcpu, -1, 0, 0);
8215 vmx->nested.smm.vmxon = vmx->nested.vmxon;
8216 vmx->nested.vmxon = false;
8217 vmx_clear_hlt(vcpu);
8218 return 0;
8221 int vmx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram)
8223 struct vcpu_vmx *vmx = to_vmx(vcpu);
8224 int ret;
8226 if (vmx->nested.smm.vmxon) {
8227 vmx->nested.vmxon = true;
8228 vmx->nested.smm.vmxon = false;
8231 if (vmx->nested.smm.guest_mode) {
8232 ret = nested_vmx_enter_non_root_mode(vcpu, false);
8233 if (ret)
8234 return ret;
8236 vmx->nested.nested_run_pending = 1;
8237 vmx->nested.smm.guest_mode = false;
8239 return 0;
8242 void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
8244 /* RSM will cause a vmexit anyway. */
8246 #endif
8248 bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
8250 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
8253 void vmx_migrate_timers(struct kvm_vcpu *vcpu)
8255 if (is_guest_mode(vcpu)) {
8256 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
8258 if (hrtimer_try_to_cancel(timer) == 1)
8259 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
8263 void vmx_hardware_unsetup(void)
8265 kvm_set_posted_intr_wakeup_handler(NULL);
8267 if (nested)
8268 nested_vmx_hardware_unsetup();
8270 free_kvm_area();
8273 void vmx_vm_destroy(struct kvm *kvm)
8275 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
8277 free_pages((unsigned long)kvm_vmx->pid_table, vmx_get_pid_table_order(kvm));
8281 * Note, the SDM states that the linear address is masked *after* the modified
8282 * canonicality check, whereas KVM masks (untags) the address and then performs
8283 * a "normal" canonicality check. Functionally, the two methods are identical,
8284 * and when the masking occurs relative to the canonicality check isn't visible
8285 * to software, i.e. KVM's behavior doesn't violate the SDM.
8287 gva_t vmx_get_untagged_addr(struct kvm_vcpu *vcpu, gva_t gva, unsigned int flags)
8289 int lam_bit;
8290 unsigned long cr3_bits;
8292 if (flags & (X86EMUL_F_FETCH | X86EMUL_F_IMPLICIT | X86EMUL_F_INVLPG))
8293 return gva;
8295 if (!is_64_bit_mode(vcpu))
8296 return gva;
8299 * Bit 63 determines if the address should be treated as user address
8300 * or a supervisor address.
8302 if (!(gva & BIT_ULL(63))) {
8303 cr3_bits = kvm_get_active_cr3_lam_bits(vcpu);
8304 if (!(cr3_bits & (X86_CR3_LAM_U57 | X86_CR3_LAM_U48)))
8305 return gva;
8307 /* LAM_U48 is ignored if LAM_U57 is set. */
8308 lam_bit = cr3_bits & X86_CR3_LAM_U57 ? 56 : 47;
8309 } else {
8310 if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_LAM_SUP))
8311 return gva;
8313 lam_bit = kvm_is_cr4_bit_set(vcpu, X86_CR4_LA57) ? 56 : 47;
8317 * Untag the address by sign-extending the lam_bit, but NOT to bit 63.
8318 * Bit 63 is retained from the raw virtual address so that untagging
8319 * doesn't change a user access to a supervisor access, and vice versa.
8321 return (sign_extend64(gva, lam_bit) & ~BIT_ULL(63)) | (gva & BIT_ULL(63));
8324 static unsigned int vmx_handle_intel_pt_intr(void)
8326 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
8328 /* '0' on failure so that the !PT case can use a RET0 static call. */
8329 if (!vcpu || !kvm_handling_nmi_from_guest(vcpu))
8330 return 0;
8332 kvm_make_request(KVM_REQ_PMI, vcpu);
8333 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
8334 (unsigned long *)&vcpu->arch.pmu.global_status);
8335 return 1;
8338 static __init void vmx_setup_user_return_msrs(void)
8342 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
8343 * will emulate SYSCALL in legacy mode if the vendor string in guest
8344 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
8345 * support this emulation, MSR_STAR is included in the list for i386,
8346 * but is never loaded into hardware. MSR_CSTAR is also never loaded
8347 * into hardware and is here purely for emulation purposes.
8349 const u32 vmx_uret_msrs_list[] = {
8350 #ifdef CONFIG_X86_64
8351 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
8352 #endif
8353 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
8354 MSR_IA32_TSX_CTRL,
8356 int i;
8358 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
8360 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
8361 kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
8364 static void __init vmx_setup_me_spte_mask(void)
8366 u64 me_mask = 0;
8369 * On pre-MKTME system, boot_cpu_data.x86_phys_bits equals to
8370 * kvm_host.maxphyaddr. On MKTME and/or TDX capable systems,
8371 * boot_cpu_data.x86_phys_bits holds the actual physical address
8372 * w/o the KeyID bits, and kvm_host.maxphyaddr equals to
8373 * MAXPHYADDR reported by CPUID. Those bits between are KeyID bits.
8375 if (boot_cpu_data.x86_phys_bits != kvm_host.maxphyaddr)
8376 me_mask = rsvd_bits(boot_cpu_data.x86_phys_bits,
8377 kvm_host.maxphyaddr - 1);
8380 * Unlike SME, host kernel doesn't support setting up any
8381 * MKTME KeyID on Intel platforms. No memory encryption
8382 * bits should be included into the SPTE.
8384 kvm_mmu_set_me_spte_mask(0, me_mask);
8387 __init int vmx_hardware_setup(void)
8389 unsigned long host_bndcfgs;
8390 struct desc_ptr dt;
8391 int r;
8393 store_idt(&dt);
8394 host_idt_base = dt.address;
8396 vmx_setup_user_return_msrs();
8398 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
8399 return -EIO;
8401 if (cpu_has_perf_global_ctrl_bug())
8402 pr_warn_once("VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
8403 "does not work properly. Using workaround\n");
8405 if (boot_cpu_has(X86_FEATURE_NX))
8406 kvm_enable_efer_bits(EFER_NX);
8408 if (boot_cpu_has(X86_FEATURE_MPX)) {
8409 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
8410 WARN_ONCE(host_bndcfgs, "BNDCFGS in host will be lost");
8413 if (!cpu_has_vmx_mpx())
8414 kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
8415 XFEATURE_MASK_BNDCSR);
8417 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
8418 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
8419 enable_vpid = 0;
8421 if (!cpu_has_vmx_ept() ||
8422 !cpu_has_vmx_ept_4levels() ||
8423 !cpu_has_vmx_ept_mt_wb() ||
8424 !cpu_has_vmx_invept_global())
8425 enable_ept = 0;
8427 /* NX support is required for shadow paging. */
8428 if (!enable_ept && !boot_cpu_has(X86_FEATURE_NX)) {
8429 pr_err_ratelimited("NX (Execute Disable) not supported\n");
8430 return -EOPNOTSUPP;
8433 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
8434 enable_ept_ad_bits = 0;
8436 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
8437 enable_unrestricted_guest = 0;
8439 if (!cpu_has_vmx_flexpriority())
8440 flexpriority_enabled = 0;
8442 if (!cpu_has_virtual_nmis())
8443 enable_vnmi = 0;
8445 #ifdef CONFIG_X86_SGX_KVM
8446 if (!cpu_has_vmx_encls_vmexit())
8447 enable_sgx = false;
8448 #endif
8451 * set_apic_access_page_addr() is used to reload apic access
8452 * page upon invalidation. No need to do anything if not
8453 * using the APIC_ACCESS_ADDR VMCS field.
8455 if (!flexpriority_enabled)
8456 vt_x86_ops.set_apic_access_page_addr = NULL;
8458 if (!cpu_has_vmx_tpr_shadow())
8459 vt_x86_ops.update_cr8_intercept = NULL;
8461 #if IS_ENABLED(CONFIG_HYPERV)
8462 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
8463 && enable_ept) {
8464 vt_x86_ops.flush_remote_tlbs = hv_flush_remote_tlbs;
8465 vt_x86_ops.flush_remote_tlbs_range = hv_flush_remote_tlbs_range;
8467 #endif
8469 if (!cpu_has_vmx_ple()) {
8470 ple_gap = 0;
8471 ple_window = 0;
8472 ple_window_grow = 0;
8473 ple_window_max = 0;
8474 ple_window_shrink = 0;
8477 if (!cpu_has_vmx_apicv())
8478 enable_apicv = 0;
8479 if (!enable_apicv)
8480 vt_x86_ops.sync_pir_to_irr = NULL;
8482 if (!enable_apicv || !cpu_has_vmx_ipiv())
8483 enable_ipiv = false;
8485 if (cpu_has_vmx_tsc_scaling())
8486 kvm_caps.has_tsc_control = true;
8488 kvm_caps.max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
8489 kvm_caps.tsc_scaling_ratio_frac_bits = 48;
8490 kvm_caps.has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
8491 kvm_caps.has_notify_vmexit = cpu_has_notify_vmexit();
8493 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8495 if (enable_ept)
8496 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
8497 cpu_has_vmx_ept_execute_only());
8500 * Setup shadow_me_value/shadow_me_mask to include MKTME KeyID
8501 * bits to shadow_zero_check.
8503 vmx_setup_me_spte_mask();
8505 kvm_configure_mmu(enable_ept, 0, vmx_get_max_ept_level(),
8506 ept_caps_to_lpage_level(vmx_capability.ept));
8509 * Only enable PML when hardware supports PML feature, and both EPT
8510 * and EPT A/D bit features are enabled -- PML depends on them to work.
8512 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8513 enable_pml = 0;
8515 if (!enable_pml)
8516 vt_x86_ops.cpu_dirty_log_size = 0;
8518 if (!cpu_has_vmx_preemption_timer())
8519 enable_preemption_timer = false;
8521 if (enable_preemption_timer) {
8522 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8524 cpu_preemption_timer_multi =
8525 vmx_misc_preemption_timer_rate(vmcs_config.misc);
8527 if (tsc_khz)
8528 use_timer_freq = (u64)tsc_khz * 1000;
8529 use_timer_freq >>= cpu_preemption_timer_multi;
8532 * KVM "disables" the preemption timer by setting it to its max
8533 * value. Don't use the timer if it might cause spurious exits
8534 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8536 if (use_timer_freq > 0xffffffffu / 10)
8537 enable_preemption_timer = false;
8540 if (!enable_preemption_timer) {
8541 vt_x86_ops.set_hv_timer = NULL;
8542 vt_x86_ops.cancel_hv_timer = NULL;
8545 kvm_caps.supported_mce_cap |= MCG_LMCE_P;
8546 kvm_caps.supported_mce_cap |= MCG_CMCI_P;
8548 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8549 return -EINVAL;
8550 if (!enable_ept || !enable_pmu || !cpu_has_vmx_intel_pt())
8551 pt_mode = PT_MODE_SYSTEM;
8552 if (pt_mode == PT_MODE_HOST_GUEST)
8553 vt_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr;
8554 else
8555 vt_init_ops.handle_intel_pt_intr = NULL;
8557 setup_default_sgx_lepubkeyhash();
8559 if (nested) {
8560 nested_vmx_setup_ctls_msrs(&vmcs_config, vmx_capability.ept);
8562 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8563 if (r)
8564 return r;
8567 vmx_set_cpu_caps();
8569 r = alloc_kvm_area();
8570 if (r && nested)
8571 nested_vmx_hardware_unsetup();
8573 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
8575 return r;
8578 static void vmx_cleanup_l1d_flush(void)
8580 if (vmx_l1d_flush_pages) {
8581 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8582 vmx_l1d_flush_pages = NULL;
8584 /* Restore state so sysfs ignores VMX */
8585 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8588 static void __vmx_exit(void)
8590 allow_smaller_maxphyaddr = false;
8592 vmx_cleanup_l1d_flush();
8595 static void vmx_exit(void)
8597 kvm_exit();
8598 __vmx_exit();
8599 kvm_x86_vendor_exit();
8602 module_exit(vmx_exit);
8604 static int __init vmx_init(void)
8606 int r, cpu;
8608 if (!kvm_is_vmx_supported())
8609 return -EOPNOTSUPP;
8612 * Note, hv_init_evmcs() touches only VMX knobs, i.e. there's nothing
8613 * to unwind if a later step fails.
8615 hv_init_evmcs();
8617 r = kvm_x86_vendor_init(&vt_init_ops);
8618 if (r)
8619 return r;
8622 * Must be called after common x86 init so enable_ept is properly set
8623 * up. Hand the parameter mitigation value in which was stored in
8624 * the pre module init parser. If no parameter was given, it will
8625 * contain 'auto' which will be turned into the default 'cond'
8626 * mitigation mode.
8628 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8629 if (r)
8630 goto err_l1d_flush;
8632 for_each_possible_cpu(cpu) {
8633 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8635 pi_init_cpu(cpu);
8638 vmx_check_vmcs12_offsets();
8641 * Shadow paging doesn't have a (further) performance penalty
8642 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8643 * by default
8645 if (!enable_ept)
8646 allow_smaller_maxphyaddr = true;
8649 * Common KVM initialization _must_ come last, after this, /dev/kvm is
8650 * exposed to userspace!
8652 r = kvm_init(sizeof(struct vcpu_vmx), __alignof__(struct vcpu_vmx),
8653 THIS_MODULE);
8654 if (r)
8655 goto err_kvm_init;
8657 return 0;
8659 err_kvm_init:
8660 __vmx_exit();
8661 err_l1d_flush:
8662 kvm_x86_vendor_exit();
8663 return r;
8665 module_init(vmx_init);