1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <linux/highmem.h>
17 #include <linux/hrtimer.h>
18 #include <linux/kernel.h>
19 #include <linux/kvm_host.h>
20 #include <linux/module.h>
21 #include <linux/moduleparam.h>
22 #include <linux/mod_devicetable.h>
24 #include <linux/objtool.h>
25 #include <linux/sched.h>
26 #include <linux/sched/smt.h>
27 #include <linux/slab.h>
28 #include <linux/tboot.h>
29 #include <linux/trace_events.h>
30 #include <linux/entry-kvm.h>
35 #include <asm/cpu_device_id.h>
36 #include <asm/debugreg.h>
38 #include <asm/fpu/internal.h>
40 #include <asm/irq_remapping.h>
41 #include <asm/kexec.h>
42 #include <asm/perf_event.h>
43 #include <asm/mmu_context.h>
44 #include <asm/mshyperv.h>
45 #include <asm/mwait.h>
46 #include <asm/spec-ctrl.h>
47 #include <asm/virtext.h>
50 #include "capabilities.h"
54 #include "kvm_cache_regs.h"
65 MODULE_AUTHOR("Qumranet");
66 MODULE_LICENSE("GPL");
69 static const struct x86_cpu_id vmx_cpu_id[] = {
70 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
73 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
76 bool __read_mostly enable_vpid = 1;
77 module_param_named(vpid, enable_vpid, bool, 0444);
79 static bool __read_mostly enable_vnmi = 1;
80 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
82 bool __read_mostly flexpriority_enabled = 1;
83 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
85 bool __read_mostly enable_ept = 1;
86 module_param_named(ept, enable_ept, bool, S_IRUGO);
88 bool __read_mostly enable_unrestricted_guest = 1;
89 module_param_named(unrestricted_guest,
90 enable_unrestricted_guest, bool, S_IRUGO);
92 bool __read_mostly enable_ept_ad_bits = 1;
93 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
95 static bool __read_mostly emulate_invalid_guest_state = true;
96 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
98 static bool __read_mostly fasteoi = 1;
99 module_param(fasteoi, bool, S_IRUGO);
101 bool __read_mostly enable_apicv = 1;
102 module_param(enable_apicv, bool, S_IRUGO);
105 * If nested=1, nested virtualization is supported, i.e., guests may use
106 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
107 * use VMX instructions.
109 static bool __read_mostly nested = 1;
110 module_param(nested, bool, S_IRUGO);
112 bool __read_mostly enable_pml = 1;
113 module_param_named(pml, enable_pml, bool, S_IRUGO);
115 static bool __read_mostly dump_invalid_vmcs = 0;
116 module_param(dump_invalid_vmcs, bool, 0644);
118 #define MSR_BITMAP_MODE_X2APIC 1
119 #define MSR_BITMAP_MODE_X2APIC_APICV 2
121 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
123 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
124 static int __read_mostly cpu_preemption_timer_multi;
125 static bool __read_mostly enable_preemption_timer = 1;
127 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
130 extern bool __read_mostly allow_smaller_maxphyaddr;
131 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
133 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
134 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
135 #define KVM_VM_CR0_ALWAYS_ON \
136 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
137 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
139 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
140 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
141 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
143 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
145 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
146 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
147 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
148 RTIT_STATUS_BYTECNT))
151 * List of MSRs that can be directly passed to the guest.
152 * In addition to these x2apic and PT MSRs are handled specially.
154 static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
161 MSR_IA32_SYSENTER_CS,
162 MSR_IA32_SYSENTER_ESP,
163 MSR_IA32_SYSENTER_EIP,
165 MSR_CORE_C3_RESIDENCY,
166 MSR_CORE_C6_RESIDENCY,
167 MSR_CORE_C7_RESIDENCY,
171 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
172 * ple_gap: upper bound on the amount of time between two successive
173 * executions of PAUSE in a loop. Also indicate if ple enabled.
174 * According to test, this time is usually smaller than 128 cycles.
175 * ple_window: upper bound on the amount of time a guest is allowed to execute
176 * in a PAUSE loop. Tests indicate that most spinlocks are held for
177 * less than 2^12 cycles
178 * Time is measured based on a counter that runs at the same rate as the TSC,
179 * refer SDM volume 3b section 21.6.13 & 22.1.3.
181 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
182 module_param(ple_gap, uint, 0444);
184 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
185 module_param(ple_window, uint, 0444);
187 /* Default doubles per-vcpu window every exit. */
188 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
189 module_param(ple_window_grow, uint, 0444);
191 /* Default resets per-vcpu window every exit to ple_window. */
192 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
193 module_param(ple_window_shrink, uint, 0444);
195 /* Default is to compute the maximum so we can never overflow. */
196 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
197 module_param(ple_window_max, uint, 0444);
199 /* Default is SYSTEM mode, 1 for host-guest mode */
200 int __read_mostly pt_mode = PT_MODE_SYSTEM;
201 module_param(pt_mode, int, S_IRUGO);
203 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
204 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
205 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
207 /* Storage for pre module init parameter parsing */
208 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
210 static const struct {
213 } vmentry_l1d_param[] = {
214 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
215 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
216 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
217 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
218 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
219 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
222 #define L1D_CACHE_ORDER 4
223 static void *vmx_l1d_flush_pages;
225 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
230 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
231 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
236 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
240 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
243 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
244 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
245 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
250 /* If set to auto use the default l1tf mitigation method */
251 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
252 switch (l1tf_mitigation) {
253 case L1TF_MITIGATION_OFF:
254 l1tf = VMENTER_L1D_FLUSH_NEVER;
256 case L1TF_MITIGATION_FLUSH_NOWARN:
257 case L1TF_MITIGATION_FLUSH:
258 case L1TF_MITIGATION_FLUSH_NOSMT:
259 l1tf = VMENTER_L1D_FLUSH_COND;
261 case L1TF_MITIGATION_FULL:
262 case L1TF_MITIGATION_FULL_FORCE:
263 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
266 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
267 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
270 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
271 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
273 * This allocation for vmx_l1d_flush_pages is not tied to a VM
274 * lifetime and so should not be charged to a memcg.
276 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
279 vmx_l1d_flush_pages = page_address(page);
282 * Initialize each page with a different pattern in
283 * order to protect against KSM in the nested
284 * virtualization case.
286 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
287 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
292 l1tf_vmx_mitigation = l1tf;
294 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
295 static_branch_enable(&vmx_l1d_should_flush);
297 static_branch_disable(&vmx_l1d_should_flush);
299 if (l1tf == VMENTER_L1D_FLUSH_COND)
300 static_branch_enable(&vmx_l1d_flush_cond);
302 static_branch_disable(&vmx_l1d_flush_cond);
306 static int vmentry_l1d_flush_parse(const char *s)
311 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
312 if (vmentry_l1d_param[i].for_parse &&
313 sysfs_streq(s, vmentry_l1d_param[i].option))
320 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
324 l1tf = vmentry_l1d_flush_parse(s);
328 if (!boot_cpu_has(X86_BUG_L1TF))
332 * Has vmx_init() run already? If not then this is the pre init
333 * parameter parsing. In that case just store the value and let
334 * vmx_init() do the proper setup after enable_ept has been
337 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
338 vmentry_l1d_flush_param = l1tf;
342 mutex_lock(&vmx_l1d_flush_mutex);
343 ret = vmx_setup_l1d_flush(l1tf);
344 mutex_unlock(&vmx_l1d_flush_mutex);
348 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
350 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
351 return sprintf(s, "???\n");
353 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
356 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
357 .set = vmentry_l1d_flush_set,
358 .get = vmentry_l1d_flush_get,
360 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
362 static u32 vmx_segment_access_rights(struct kvm_segment *var);
363 static __always_inline void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu,
366 void vmx_vmexit(void);
368 #define vmx_insn_failed(fmt...) \
371 pr_warn_ratelimited(fmt); \
374 asmlinkage void vmread_error(unsigned long field, bool fault)
377 kvm_spurious_fault();
379 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
382 noinline void vmwrite_error(unsigned long field, unsigned long value)
384 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
385 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
388 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
390 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
393 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
395 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
398 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
400 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
404 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
406 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
410 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
411 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
413 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
414 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
416 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
418 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
419 static DEFINE_SPINLOCK(vmx_vpid_lock);
421 struct vmcs_config vmcs_config;
422 struct vmx_capability vmx_capability;
424 #define VMX_SEGMENT_FIELD(seg) \
425 [VCPU_SREG_##seg] = { \
426 .selector = GUEST_##seg##_SELECTOR, \
427 .base = GUEST_##seg##_BASE, \
428 .limit = GUEST_##seg##_LIMIT, \
429 .ar_bytes = GUEST_##seg##_AR_BYTES, \
432 static const struct kvm_vmx_segment_field {
437 } kvm_vmx_segment_fields[] = {
438 VMX_SEGMENT_FIELD(CS),
439 VMX_SEGMENT_FIELD(DS),
440 VMX_SEGMENT_FIELD(ES),
441 VMX_SEGMENT_FIELD(FS),
442 VMX_SEGMENT_FIELD(GS),
443 VMX_SEGMENT_FIELD(SS),
444 VMX_SEGMENT_FIELD(TR),
445 VMX_SEGMENT_FIELD(LDTR),
448 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
450 vmx->segment_cache.bitmask = 0;
453 static unsigned long host_idt_base;
456 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
457 * will emulate SYSCALL in legacy mode if the vendor string in guest
458 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
459 * support this emulation, IA32_STAR must always be included in
460 * vmx_uret_msrs_list[], even in i386 builds.
462 static const u32 vmx_uret_msrs_list[] = {
464 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
466 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
470 #if IS_ENABLED(CONFIG_HYPERV)
471 static bool __read_mostly enlightened_vmcs = true;
472 module_param(enlightened_vmcs, bool, 0444);
474 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
475 static void check_ept_pointer_match(struct kvm *kvm)
477 struct kvm_vcpu *vcpu;
478 u64 tmp_eptp = INVALID_PAGE;
481 kvm_for_each_vcpu(i, vcpu, kvm) {
482 if (!VALID_PAGE(tmp_eptp)) {
483 tmp_eptp = to_vmx(vcpu)->ept_pointer;
484 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
485 to_kvm_vmx(kvm)->ept_pointers_match
486 = EPT_POINTERS_MISMATCH;
491 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
494 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
497 struct kvm_tlb_range *range = data;
499 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
503 static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
504 struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
506 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
509 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
510 * of the base of EPT PML4 table, strip off EPT configuration
514 return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
515 kvm_fill_hv_flush_list_func, (void *)range);
517 return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
520 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
521 struct kvm_tlb_range *range)
523 struct kvm_vcpu *vcpu;
526 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
528 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
529 check_ept_pointer_match(kvm);
531 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
532 kvm_for_each_vcpu(i, vcpu, kvm) {
533 /* If ept_pointer is invalid pointer, bypass flush request. */
534 if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
535 ret |= __hv_remote_flush_tlb_with_range(
539 ret = __hv_remote_flush_tlb_with_range(kvm,
540 kvm_get_vcpu(kvm, 0), range);
543 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
546 static int hv_remote_flush_tlb(struct kvm *kvm)
548 return hv_remote_flush_tlb_with_range(kvm, NULL);
551 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
553 struct hv_enlightened_vmcs *evmcs;
554 struct hv_partition_assist_pg **p_hv_pa_pg =
555 &vcpu->kvm->arch.hyperv.hv_pa_pg;
557 * Synthetic VM-Exit is not enabled in current code and so All
558 * evmcs in singe VM shares same assist page.
561 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL);
566 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
568 evmcs->partition_assist_page =
570 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
571 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
576 #endif /* IS_ENABLED(CONFIG_HYPERV) */
579 * Comment's format: document - errata name - stepping - processor name.
581 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
583 static u32 vmx_preemption_cpu_tfms[] = {
584 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
586 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
587 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
588 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
590 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
592 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
593 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
595 * 320767.pdf - AAP86 - B1 -
596 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
599 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
601 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
603 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
605 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
606 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
607 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
609 /* Xeon E3-1220 V2 */
613 static inline bool cpu_has_broken_vmx_preemption_timer(void)
615 u32 eax = cpuid_eax(0x00000001), i;
617 /* Clear the reserved bits */
618 eax &= ~(0x3U << 14 | 0xfU << 28);
619 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
620 if (eax == vmx_preemption_cpu_tfms[i])
626 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
628 return flexpriority_enabled && lapic_in_kernel(vcpu);
631 static inline bool report_flexpriority(void)
633 return flexpriority_enabled;
636 static int possible_passthrough_msr_slot(u32 msr)
640 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
641 if (vmx_possible_passthrough_msrs[i] == msr)
647 static bool is_valid_passthrough_msr(u32 msr)
652 case 0x800 ... 0x8ff:
653 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
655 case MSR_IA32_RTIT_STATUS:
656 case MSR_IA32_RTIT_OUTPUT_BASE:
657 case MSR_IA32_RTIT_OUTPUT_MASK:
658 case MSR_IA32_RTIT_CR3_MATCH:
659 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
660 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
663 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
664 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
665 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
666 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
667 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
668 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
672 r = possible_passthrough_msr_slot(msr) != -ENOENT;
674 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
679 static inline int __vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
683 for (i = 0; i < vmx->nr_uret_msrs; ++i)
684 if (vmx_uret_msrs_list[vmx->guest_uret_msrs[i].slot] == msr)
689 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
693 i = __vmx_find_uret_msr(vmx, msr);
695 return &vmx->guest_uret_msrs[i];
699 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
700 struct vmx_uret_msr *msr, u64 data)
704 u64 old_msr_data = msr->data;
706 if (msr - vmx->guest_uret_msrs < vmx->nr_active_uret_msrs) {
708 ret = kvm_set_user_return_msr(msr->slot, msr->data, msr->mask);
711 msr->data = old_msr_data;
716 #ifdef CONFIG_KEXEC_CORE
717 static void crash_vmclear_local_loaded_vmcss(void)
719 int cpu = raw_smp_processor_id();
720 struct loaded_vmcs *v;
722 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
723 loaded_vmcss_on_cpu_link)
726 #endif /* CONFIG_KEXEC_CORE */
728 static void __loaded_vmcs_clear(void *arg)
730 struct loaded_vmcs *loaded_vmcs = arg;
731 int cpu = raw_smp_processor_id();
733 if (loaded_vmcs->cpu != cpu)
734 return; /* vcpu migration can race with cpu offline */
735 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
736 per_cpu(current_vmcs, cpu) = NULL;
738 vmcs_clear(loaded_vmcs->vmcs);
739 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
740 vmcs_clear(loaded_vmcs->shadow_vmcs);
742 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
745 * Ensure all writes to loaded_vmcs, including deleting it from its
746 * current percpu list, complete before setting loaded_vmcs->vcpu to
747 * -1, otherwise a different cpu can see vcpu == -1 first and add
748 * loaded_vmcs to its percpu list before it's deleted from this cpu's
749 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
753 loaded_vmcs->cpu = -1;
754 loaded_vmcs->launched = 0;
757 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
759 int cpu = loaded_vmcs->cpu;
762 smp_call_function_single(cpu,
763 __loaded_vmcs_clear, loaded_vmcs, 1);
766 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
770 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
772 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
773 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
774 vmx->segment_cache.bitmask = 0;
776 ret = vmx->segment_cache.bitmask & mask;
777 vmx->segment_cache.bitmask |= mask;
781 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
783 u16 *p = &vmx->segment_cache.seg[seg].selector;
785 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
786 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
790 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
792 ulong *p = &vmx->segment_cache.seg[seg].base;
794 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
795 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
799 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
801 u32 *p = &vmx->segment_cache.seg[seg].limit;
803 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
804 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
808 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
810 u32 *p = &vmx->segment_cache.seg[seg].ar;
812 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
813 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
817 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
821 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
822 (1u << DB_VECTOR) | (1u << AC_VECTOR);
824 * Guest access to VMware backdoor ports could legitimately
825 * trigger #GP because of TSS I/O permission bitmap.
826 * We intercept those #GP and allow access to them anyway
829 if (enable_vmware_backdoor)
830 eb |= (1u << GP_VECTOR);
831 if ((vcpu->guest_debug &
832 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
833 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
834 eb |= 1u << BP_VECTOR;
835 if (to_vmx(vcpu)->rmode.vm86_active)
837 if (!vmx_need_pf_intercept(vcpu))
838 eb &= ~(1u << PF_VECTOR);
840 /* When we are running a nested L2 guest and L1 specified for it a
841 * certain exception bitmap, we must trap the same exceptions and pass
842 * them to L1. When running L2, we will only handle the exceptions
843 * specified above if L1 did not want them.
845 if (is_guest_mode(vcpu))
846 eb |= get_vmcs12(vcpu)->exception_bitmap;
849 * If EPT is enabled, #PF is only trapped if MAXPHYADDR is mismatched
850 * between guest and host. In that case we only care about present
851 * faults. For vmcs02, however, PFEC_MASK and PFEC_MATCH are set in
852 * prepare_vmcs02_rare.
854 bool selective_pf_trap = enable_ept && (eb & (1u << PF_VECTOR));
855 int mask = selective_pf_trap ? PFERR_PRESENT_MASK : 0;
856 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
857 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, mask);
860 vmcs_write32(EXCEPTION_BITMAP, eb);
864 * Check if MSR is intercepted for currently loaded MSR bitmap.
866 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
868 unsigned long *msr_bitmap;
869 int f = sizeof(unsigned long);
871 if (!cpu_has_vmx_msr_bitmap())
874 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
877 return !!test_bit(msr, msr_bitmap + 0x800 / f);
878 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
880 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
886 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
887 unsigned long entry, unsigned long exit)
889 vm_entry_controls_clearbit(vmx, entry);
890 vm_exit_controls_clearbit(vmx, exit);
893 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
897 for (i = 0; i < m->nr; ++i) {
898 if (m->val[i].index == msr)
904 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
907 struct msr_autoload *m = &vmx->msr_autoload;
911 if (cpu_has_load_ia32_efer()) {
912 clear_atomic_switch_msr_special(vmx,
913 VM_ENTRY_LOAD_IA32_EFER,
914 VM_EXIT_LOAD_IA32_EFER);
918 case MSR_CORE_PERF_GLOBAL_CTRL:
919 if (cpu_has_load_perf_global_ctrl()) {
920 clear_atomic_switch_msr_special(vmx,
921 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
922 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
927 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
931 m->guest.val[i] = m->guest.val[m->guest.nr];
932 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
935 i = vmx_find_loadstore_msr_slot(&m->host, msr);
940 m->host.val[i] = m->host.val[m->host.nr];
941 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
944 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
945 unsigned long entry, unsigned long exit,
946 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
947 u64 guest_val, u64 host_val)
949 vmcs_write64(guest_val_vmcs, guest_val);
950 if (host_val_vmcs != HOST_IA32_EFER)
951 vmcs_write64(host_val_vmcs, host_val);
952 vm_entry_controls_setbit(vmx, entry);
953 vm_exit_controls_setbit(vmx, exit);
956 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
957 u64 guest_val, u64 host_val, bool entry_only)
960 struct msr_autoload *m = &vmx->msr_autoload;
964 if (cpu_has_load_ia32_efer()) {
965 add_atomic_switch_msr_special(vmx,
966 VM_ENTRY_LOAD_IA32_EFER,
967 VM_EXIT_LOAD_IA32_EFER,
970 guest_val, host_val);
974 case MSR_CORE_PERF_GLOBAL_CTRL:
975 if (cpu_has_load_perf_global_ctrl()) {
976 add_atomic_switch_msr_special(vmx,
977 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
978 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
979 GUEST_IA32_PERF_GLOBAL_CTRL,
980 HOST_IA32_PERF_GLOBAL_CTRL,
981 guest_val, host_val);
985 case MSR_IA32_PEBS_ENABLE:
986 /* PEBS needs a quiescent period after being disabled (to write
987 * a record). Disabling PEBS through VMX MSR swapping doesn't
988 * provide that period, so a CPU could write host's record into
991 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
994 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
996 j = vmx_find_loadstore_msr_slot(&m->host, msr);
998 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
999 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
1000 printk_once(KERN_WARNING "Not enough msr switch entries. "
1001 "Can't add msr %x\n", msr);
1006 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1008 m->guest.val[i].index = msr;
1009 m->guest.val[i].value = guest_val;
1016 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1018 m->host.val[j].index = msr;
1019 m->host.val[j].value = host_val;
1022 static bool update_transition_efer(struct vcpu_vmx *vmx)
1024 u64 guest_efer = vmx->vcpu.arch.efer;
1025 u64 ignore_bits = 0;
1028 /* Shadow paging assumes NX to be available. */
1030 guest_efer |= EFER_NX;
1033 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1035 ignore_bits |= EFER_SCE;
1036 #ifdef CONFIG_X86_64
1037 ignore_bits |= EFER_LMA | EFER_LME;
1038 /* SCE is meaningful only in long mode on Intel */
1039 if (guest_efer & EFER_LMA)
1040 ignore_bits &= ~(u64)EFER_SCE;
1044 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1045 * On CPUs that support "load IA32_EFER", always switch EFER
1046 * atomically, since it's faster than switching it manually.
1048 if (cpu_has_load_ia32_efer() ||
1049 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1050 if (!(guest_efer & EFER_LMA))
1051 guest_efer &= ~EFER_LME;
1052 if (guest_efer != host_efer)
1053 add_atomic_switch_msr(vmx, MSR_EFER,
1054 guest_efer, host_efer, false);
1056 clear_atomic_switch_msr(vmx, MSR_EFER);
1060 i = __vmx_find_uret_msr(vmx, MSR_EFER);
1064 clear_atomic_switch_msr(vmx, MSR_EFER);
1066 guest_efer &= ~ignore_bits;
1067 guest_efer |= host_efer & ignore_bits;
1069 vmx->guest_uret_msrs[i].data = guest_efer;
1070 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1075 #ifdef CONFIG_X86_32
1077 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1078 * VMCS rather than the segment table. KVM uses this helper to figure
1079 * out the current bases to poke them into the VMCS before entry.
1081 static unsigned long segment_base(u16 selector)
1083 struct desc_struct *table;
1086 if (!(selector & ~SEGMENT_RPL_MASK))
1089 table = get_current_gdt_ro();
1091 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1092 u16 ldt_selector = kvm_read_ldt();
1094 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1097 table = (struct desc_struct *)segment_base(ldt_selector);
1099 v = get_desc_base(&table[selector >> 3]);
1104 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1106 return vmx_pt_mode_is_host_guest() &&
1107 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1110 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1112 /* The base must be 128-byte aligned and a legal physical address. */
1113 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1116 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1120 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1121 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1122 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1123 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1124 for (i = 0; i < addr_range; i++) {
1125 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1126 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1130 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1134 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1135 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1136 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1137 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1138 for (i = 0; i < addr_range; i++) {
1139 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1140 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1144 static void pt_guest_enter(struct vcpu_vmx *vmx)
1146 if (vmx_pt_mode_is_system())
1150 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1151 * Save host state before VM entry.
1153 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1154 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1155 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1156 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1157 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1161 static void pt_guest_exit(struct vcpu_vmx *vmx)
1163 if (vmx_pt_mode_is_system())
1166 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1167 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1168 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1171 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1172 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1175 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1176 unsigned long fs_base, unsigned long gs_base)
1178 if (unlikely(fs_sel != host->fs_sel)) {
1180 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1182 vmcs_write16(HOST_FS_SELECTOR, 0);
1183 host->fs_sel = fs_sel;
1185 if (unlikely(gs_sel != host->gs_sel)) {
1187 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1189 vmcs_write16(HOST_GS_SELECTOR, 0);
1190 host->gs_sel = gs_sel;
1192 if (unlikely(fs_base != host->fs_base)) {
1193 vmcs_writel(HOST_FS_BASE, fs_base);
1194 host->fs_base = fs_base;
1196 if (unlikely(gs_base != host->gs_base)) {
1197 vmcs_writel(HOST_GS_BASE, gs_base);
1198 host->gs_base = gs_base;
1202 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1204 struct vcpu_vmx *vmx = to_vmx(vcpu);
1205 struct vmcs_host_state *host_state;
1206 #ifdef CONFIG_X86_64
1207 int cpu = raw_smp_processor_id();
1209 unsigned long fs_base, gs_base;
1213 vmx->req_immediate_exit = false;
1216 * Note that guest MSRs to be saved/restored can also be changed
1217 * when guest state is loaded. This happens when guest transitions
1218 * to/from long-mode by setting MSR_EFER.LMA.
1220 if (!vmx->guest_uret_msrs_loaded) {
1221 vmx->guest_uret_msrs_loaded = true;
1222 for (i = 0; i < vmx->nr_active_uret_msrs; ++i)
1223 kvm_set_user_return_msr(vmx->guest_uret_msrs[i].slot,
1224 vmx->guest_uret_msrs[i].data,
1225 vmx->guest_uret_msrs[i].mask);
1229 if (vmx->nested.need_vmcs12_to_shadow_sync)
1230 nested_sync_vmcs12_to_shadow(vcpu);
1232 if (vmx->guest_state_loaded)
1235 host_state = &vmx->loaded_vmcs->host_state;
1238 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1239 * allow segment selectors with cpl > 0 or ti == 1.
1241 host_state->ldt_sel = kvm_read_ldt();
1243 #ifdef CONFIG_X86_64
1244 savesegment(ds, host_state->ds_sel);
1245 savesegment(es, host_state->es_sel);
1247 gs_base = cpu_kernelmode_gs_base(cpu);
1248 if (likely(is_64bit_mm(current->mm))) {
1249 current_save_fsgs();
1250 fs_sel = current->thread.fsindex;
1251 gs_sel = current->thread.gsindex;
1252 fs_base = current->thread.fsbase;
1253 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1255 savesegment(fs, fs_sel);
1256 savesegment(gs, gs_sel);
1257 fs_base = read_msr(MSR_FS_BASE);
1258 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1261 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1263 savesegment(fs, fs_sel);
1264 savesegment(gs, gs_sel);
1265 fs_base = segment_base(fs_sel);
1266 gs_base = segment_base(gs_sel);
1269 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1270 vmx->guest_state_loaded = true;
1273 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1275 struct vmcs_host_state *host_state;
1277 if (!vmx->guest_state_loaded)
1280 host_state = &vmx->loaded_vmcs->host_state;
1282 ++vmx->vcpu.stat.host_state_reload;
1284 #ifdef CONFIG_X86_64
1285 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1287 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1288 kvm_load_ldt(host_state->ldt_sel);
1289 #ifdef CONFIG_X86_64
1290 load_gs_index(host_state->gs_sel);
1292 loadsegment(gs, host_state->gs_sel);
1295 if (host_state->fs_sel & 7)
1296 loadsegment(fs, host_state->fs_sel);
1297 #ifdef CONFIG_X86_64
1298 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1299 loadsegment(ds, host_state->ds_sel);
1300 loadsegment(es, host_state->es_sel);
1303 invalidate_tss_limit();
1304 #ifdef CONFIG_X86_64
1305 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1307 load_fixmap_gdt(raw_smp_processor_id());
1308 vmx->guest_state_loaded = false;
1309 vmx->guest_uret_msrs_loaded = false;
1312 #ifdef CONFIG_X86_64
1313 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1316 if (vmx->guest_state_loaded)
1317 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1319 return vmx->msr_guest_kernel_gs_base;
1322 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1325 if (vmx->guest_state_loaded)
1326 wrmsrl(MSR_KERNEL_GS_BASE, data);
1328 vmx->msr_guest_kernel_gs_base = data;
1332 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1333 struct loaded_vmcs *buddy)
1335 struct vcpu_vmx *vmx = to_vmx(vcpu);
1336 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1339 if (!already_loaded) {
1340 loaded_vmcs_clear(vmx->loaded_vmcs);
1341 local_irq_disable();
1344 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1345 * this cpu's percpu list, otherwise it may not yet be deleted
1346 * from its previous cpu's percpu list. Pairs with the
1347 * smb_wmb() in __loaded_vmcs_clear().
1351 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1352 &per_cpu(loaded_vmcss_on_cpu, cpu));
1356 prev = per_cpu(current_vmcs, cpu);
1357 if (prev != vmx->loaded_vmcs->vmcs) {
1358 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1359 vmcs_load(vmx->loaded_vmcs->vmcs);
1362 * No indirect branch prediction barrier needed when switching
1363 * the active VMCS within a guest, e.g. on nested VM-Enter.
1364 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1366 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1367 indirect_branch_prediction_barrier();
1370 if (!already_loaded) {
1371 void *gdt = get_current_gdt_ro();
1372 unsigned long sysenter_esp;
1375 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1376 * TLB entries from its previous association with the vCPU.
1378 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1381 * Linux uses per-cpu TSS and GDT, so set these when switching
1382 * processors. See 22.2.4.
1384 vmcs_writel(HOST_TR_BASE,
1385 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1386 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1388 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1389 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1391 vmx->loaded_vmcs->cpu = cpu;
1394 /* Setup TSC multiplier */
1395 if (kvm_has_tsc_control &&
1396 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1397 decache_tsc_multiplier(vmx);
1401 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1402 * vcpu mutex is already taken.
1404 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1406 struct vcpu_vmx *vmx = to_vmx(vcpu);
1408 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1410 vmx_vcpu_pi_load(vcpu, cpu);
1412 vmx->host_debugctlmsr = get_debugctlmsr();
1415 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1417 vmx_vcpu_pi_put(vcpu);
1419 vmx_prepare_switch_to_host(to_vmx(vcpu));
1422 static bool emulation_required(struct kvm_vcpu *vcpu)
1424 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1427 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1429 struct vcpu_vmx *vmx = to_vmx(vcpu);
1430 unsigned long rflags, save_rflags;
1432 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1433 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1434 rflags = vmcs_readl(GUEST_RFLAGS);
1435 if (vmx->rmode.vm86_active) {
1436 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1437 save_rflags = vmx->rmode.save_rflags;
1438 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1440 vmx->rflags = rflags;
1445 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1447 struct vcpu_vmx *vmx = to_vmx(vcpu);
1448 unsigned long old_rflags;
1450 if (is_unrestricted_guest(vcpu)) {
1451 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1452 vmx->rflags = rflags;
1453 vmcs_writel(GUEST_RFLAGS, rflags);
1457 old_rflags = vmx_get_rflags(vcpu);
1458 vmx->rflags = rflags;
1459 if (vmx->rmode.vm86_active) {
1460 vmx->rmode.save_rflags = rflags;
1461 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1463 vmcs_writel(GUEST_RFLAGS, rflags);
1465 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1466 vmx->emulation_required = emulation_required(vcpu);
1469 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1471 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1474 if (interruptibility & GUEST_INTR_STATE_STI)
1475 ret |= KVM_X86_SHADOW_INT_STI;
1476 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1477 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1482 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1484 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1485 u32 interruptibility = interruptibility_old;
1487 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1489 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1490 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1491 else if (mask & KVM_X86_SHADOW_INT_STI)
1492 interruptibility |= GUEST_INTR_STATE_STI;
1494 if ((interruptibility != interruptibility_old))
1495 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1498 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1500 struct vcpu_vmx *vmx = to_vmx(vcpu);
1501 unsigned long value;
1504 * Any MSR write that attempts to change bits marked reserved will
1507 if (data & vmx->pt_desc.ctl_bitmask)
1511 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1512 * result in a #GP unless the same write also clears TraceEn.
1514 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1515 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1519 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1520 * and FabricEn would cause #GP, if
1521 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1523 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1524 !(data & RTIT_CTL_FABRIC_EN) &&
1525 !intel_pt_validate_cap(vmx->pt_desc.caps,
1526 PT_CAP_single_range_output))
1530 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1531 * utilize encodings marked reserved will casue a #GP fault.
1533 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1534 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1535 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1536 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1538 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1539 PT_CAP_cycle_thresholds);
1540 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1541 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1542 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1544 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1545 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1546 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1547 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1551 * If ADDRx_CFG is reserved or the encodings is >2 will
1552 * cause a #GP fault.
1554 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1555 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1557 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1558 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1560 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1561 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1563 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1564 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1570 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
1575 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1577 unsigned long rip, orig_rip;
1580 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1581 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1582 * set when EPT misconfig occurs. In practice, real hardware updates
1583 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1584 * (namely Hyper-V) don't set it due to it being undefined behavior,
1585 * i.e. we end up advancing IP with some random value.
1587 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1588 to_vmx(vcpu)->exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1589 orig_rip = kvm_rip_read(vcpu);
1590 rip = orig_rip + vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1591 #ifdef CONFIG_X86_64
1593 * We need to mask out the high 32 bits of RIP if not in 64-bit
1594 * mode, but just finding out that we are in 64-bit mode is
1595 * quite expensive. Only do it if there was a carry.
1597 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1600 kvm_rip_write(vcpu, rip);
1602 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1606 /* skipping an emulated instruction also counts */
1607 vmx_set_interrupt_shadow(vcpu, 0);
1613 * Recognizes a pending MTF VM-exit and records the nested state for later
1616 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1618 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1619 struct vcpu_vmx *vmx = to_vmx(vcpu);
1621 if (!is_guest_mode(vcpu))
1625 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1626 * T-bit traps. As instruction emulation is completed (i.e. at the
1627 * instruction boundary), any #DB exception pending delivery must be a
1628 * debug-trap. Record the pending MTF state to be delivered in
1629 * vmx_check_nested_events().
1631 if (nested_cpu_has_mtf(vmcs12) &&
1632 (!vcpu->arch.exception.pending ||
1633 vcpu->arch.exception.nr == DB_VECTOR))
1634 vmx->nested.mtf_pending = true;
1636 vmx->nested.mtf_pending = false;
1639 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1641 vmx_update_emulated_instruction(vcpu);
1642 return skip_emulated_instruction(vcpu);
1645 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1648 * Ensure that we clear the HLT state in the VMCS. We don't need to
1649 * explicitly skip the instruction because if the HLT state is set,
1650 * then the instruction is already executing and RIP has already been
1653 if (kvm_hlt_in_guest(vcpu->kvm) &&
1654 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1655 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1658 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1660 struct vcpu_vmx *vmx = to_vmx(vcpu);
1661 unsigned nr = vcpu->arch.exception.nr;
1662 bool has_error_code = vcpu->arch.exception.has_error_code;
1663 u32 error_code = vcpu->arch.exception.error_code;
1664 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1666 kvm_deliver_exception_payload(vcpu);
1668 if (has_error_code) {
1669 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1670 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1673 if (vmx->rmode.vm86_active) {
1675 if (kvm_exception_is_soft(nr))
1676 inc_eip = vcpu->arch.event_exit_inst_len;
1677 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1681 WARN_ON_ONCE(vmx->emulation_required);
1683 if (kvm_exception_is_soft(nr)) {
1684 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1685 vmx->vcpu.arch.event_exit_inst_len);
1686 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1688 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1690 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1692 vmx_clear_hlt(vcpu);
1695 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr)
1697 struct vmx_uret_msr tmp;
1700 from = __vmx_find_uret_msr(vmx, msr);
1703 to = vmx->nr_active_uret_msrs++;
1705 tmp = vmx->guest_uret_msrs[to];
1706 vmx->guest_uret_msrs[to] = vmx->guest_uret_msrs[from];
1707 vmx->guest_uret_msrs[from] = tmp;
1711 * Set up the vmcs to automatically save and restore system
1712 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1713 * mode, as fiddling with msrs is very expensive.
1715 static void setup_msrs(struct vcpu_vmx *vmx)
1717 vmx->guest_uret_msrs_loaded = false;
1718 vmx->nr_active_uret_msrs = 0;
1719 #ifdef CONFIG_X86_64
1721 * The SYSCALL MSRs are only needed on long mode guests, and only
1722 * when EFER.SCE is set.
1724 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1725 vmx_setup_uret_msr(vmx, MSR_STAR);
1726 vmx_setup_uret_msr(vmx, MSR_LSTAR);
1727 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK);
1730 if (update_transition_efer(vmx))
1731 vmx_setup_uret_msr(vmx, MSR_EFER);
1733 if (guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1734 vmx_setup_uret_msr(vmx, MSR_TSC_AUX);
1736 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL);
1738 if (cpu_has_vmx_msr_bitmap())
1739 vmx_update_msr_bitmap(&vmx->vcpu);
1742 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1744 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1745 u64 g_tsc_offset = 0;
1748 * We're here if L1 chose not to trap WRMSR to TSC. According
1749 * to the spec, this should set L1's TSC; The offset that L1
1750 * set for L2 remains unchanged, and still needs to be added
1751 * to the newly set TSC to get L2's TSC.
1753 if (is_guest_mode(vcpu) &&
1754 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
1755 g_tsc_offset = vmcs12->tsc_offset;
1757 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1758 vcpu->arch.tsc_offset - g_tsc_offset,
1760 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1761 return offset + g_tsc_offset;
1765 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1766 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1767 * all guests if the "nested" module option is off, and can also be disabled
1768 * for a single guest by disabling its VMX cpuid bit.
1770 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1772 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1775 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1778 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1780 return !(val & ~valid_bits);
1783 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1785 switch (msr->index) {
1786 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1789 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1790 case MSR_IA32_PERF_CAPABILITIES:
1791 msr->data = vmx_get_perf_capabilities();
1794 return KVM_MSR_RET_INVALID;
1799 * Reads an msr value (of 'msr_index') into 'pdata'.
1800 * Returns 0 on success, non-0 otherwise.
1801 * Assumes vcpu_load() was already called.
1803 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1805 struct vcpu_vmx *vmx = to_vmx(vcpu);
1806 struct vmx_uret_msr *msr;
1809 switch (msr_info->index) {
1810 #ifdef CONFIG_X86_64
1812 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1815 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1817 case MSR_KERNEL_GS_BASE:
1818 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1822 return kvm_get_msr_common(vcpu, msr_info);
1823 case MSR_IA32_TSX_CTRL:
1824 if (!msr_info->host_initiated &&
1825 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1828 case MSR_IA32_UMWAIT_CONTROL:
1829 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1832 msr_info->data = vmx->msr_ia32_umwait_control;
1834 case MSR_IA32_SPEC_CTRL:
1835 if (!msr_info->host_initiated &&
1836 !guest_has_spec_ctrl_msr(vcpu))
1839 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1841 case MSR_IA32_SYSENTER_CS:
1842 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1844 case MSR_IA32_SYSENTER_EIP:
1845 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1847 case MSR_IA32_SYSENTER_ESP:
1848 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1850 case MSR_IA32_BNDCFGS:
1851 if (!kvm_mpx_supported() ||
1852 (!msr_info->host_initiated &&
1853 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1855 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1857 case MSR_IA32_MCG_EXT_CTL:
1858 if (!msr_info->host_initiated &&
1859 !(vmx->msr_ia32_feature_control &
1860 FEAT_CTL_LMCE_ENABLED))
1862 msr_info->data = vcpu->arch.mcg_ext_ctl;
1864 case MSR_IA32_FEAT_CTL:
1865 msr_info->data = vmx->msr_ia32_feature_control;
1867 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1868 if (!nested_vmx_allowed(vcpu))
1870 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1874 * Enlightened VMCS v1 doesn't have certain fields, but buggy
1875 * Hyper-V versions are still trying to use corresponding
1876 * features when they are exposed. Filter out the essential
1879 if (!msr_info->host_initiated &&
1880 vmx->nested.enlightened_vmcs_enabled)
1881 nested_evmcs_filter_control_msr(msr_info->index,
1884 case MSR_IA32_RTIT_CTL:
1885 if (!vmx_pt_mode_is_host_guest())
1887 msr_info->data = vmx->pt_desc.guest.ctl;
1889 case MSR_IA32_RTIT_STATUS:
1890 if (!vmx_pt_mode_is_host_guest())
1892 msr_info->data = vmx->pt_desc.guest.status;
1894 case MSR_IA32_RTIT_CR3_MATCH:
1895 if (!vmx_pt_mode_is_host_guest() ||
1896 !intel_pt_validate_cap(vmx->pt_desc.caps,
1897 PT_CAP_cr3_filtering))
1899 msr_info->data = vmx->pt_desc.guest.cr3_match;
1901 case MSR_IA32_RTIT_OUTPUT_BASE:
1902 if (!vmx_pt_mode_is_host_guest() ||
1903 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1904 PT_CAP_topa_output) &&
1905 !intel_pt_validate_cap(vmx->pt_desc.caps,
1906 PT_CAP_single_range_output)))
1908 msr_info->data = vmx->pt_desc.guest.output_base;
1910 case MSR_IA32_RTIT_OUTPUT_MASK:
1911 if (!vmx_pt_mode_is_host_guest() ||
1912 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1913 PT_CAP_topa_output) &&
1914 !intel_pt_validate_cap(vmx->pt_desc.caps,
1915 PT_CAP_single_range_output)))
1917 msr_info->data = vmx->pt_desc.guest.output_mask;
1919 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1920 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1921 if (!vmx_pt_mode_is_host_guest() ||
1922 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1923 PT_CAP_num_address_ranges)))
1926 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1928 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1931 if (!msr_info->host_initiated &&
1932 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1935 case MSR_IA32_DEBUGCTLMSR:
1936 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
1940 msr = vmx_find_uret_msr(vmx, msr_info->index);
1942 msr_info->data = msr->data;
1945 return kvm_get_msr_common(vcpu, msr_info);
1951 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
1954 #ifdef CONFIG_X86_64
1955 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
1958 return (unsigned long)data;
1961 static u64 vcpu_supported_debugctl(struct kvm_vcpu *vcpu)
1963 u64 debugctl = vmx_supported_debugctl();
1965 if (!intel_pmu_lbr_is_enabled(vcpu))
1966 debugctl &= ~DEBUGCTLMSR_LBR_MASK;
1972 * Writes msr value into the appropriate "register".
1973 * Returns 0 on success, non-0 otherwise.
1974 * Assumes vcpu_load() was already called.
1976 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1978 struct vcpu_vmx *vmx = to_vmx(vcpu);
1979 struct vmx_uret_msr *msr;
1981 u32 msr_index = msr_info->index;
1982 u64 data = msr_info->data;
1985 switch (msr_index) {
1987 ret = kvm_set_msr_common(vcpu, msr_info);
1989 #ifdef CONFIG_X86_64
1991 vmx_segment_cache_clear(vmx);
1992 vmcs_writel(GUEST_FS_BASE, data);
1995 vmx_segment_cache_clear(vmx);
1996 vmcs_writel(GUEST_GS_BASE, data);
1998 case MSR_KERNEL_GS_BASE:
1999 vmx_write_guest_kernel_gs_base(vmx, data);
2002 case MSR_IA32_SYSENTER_CS:
2003 if (is_guest_mode(vcpu))
2004 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2005 vmcs_write32(GUEST_SYSENTER_CS, data);
2007 case MSR_IA32_SYSENTER_EIP:
2008 if (is_guest_mode(vcpu)) {
2009 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2010 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2012 vmcs_writel(GUEST_SYSENTER_EIP, data);
2014 case MSR_IA32_SYSENTER_ESP:
2015 if (is_guest_mode(vcpu)) {
2016 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2017 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2019 vmcs_writel(GUEST_SYSENTER_ESP, data);
2021 case MSR_IA32_DEBUGCTLMSR: {
2022 u64 invalid = data & ~vcpu_supported_debugctl(vcpu);
2023 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2024 if (report_ignored_msrs)
2025 vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
2027 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2028 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2034 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2035 VM_EXIT_SAVE_DEBUG_CONTROLS)
2036 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2038 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2039 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2040 (data & DEBUGCTLMSR_LBR))
2041 intel_pmu_create_guest_lbr_event(vcpu);
2044 case MSR_IA32_BNDCFGS:
2045 if (!kvm_mpx_supported() ||
2046 (!msr_info->host_initiated &&
2047 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2049 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2050 (data & MSR_IA32_BNDCFGS_RSVD))
2052 vmcs_write64(GUEST_BNDCFGS, data);
2054 case MSR_IA32_UMWAIT_CONTROL:
2055 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2058 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2059 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2062 vmx->msr_ia32_umwait_control = data;
2064 case MSR_IA32_SPEC_CTRL:
2065 if (!msr_info->host_initiated &&
2066 !guest_has_spec_ctrl_msr(vcpu))
2069 if (kvm_spec_ctrl_test_value(data))
2072 vmx->spec_ctrl = data;
2078 * When it's written (to non-zero) for the first time, pass
2082 * The handling of the MSR bitmap for L2 guests is done in
2083 * nested_vmx_prepare_msr_bitmap. We should not touch the
2084 * vmcs02.msr_bitmap here since it gets completely overwritten
2085 * in the merging. We update the vmcs01 here for L1 as well
2086 * since it will end up touching the MSR anyway now.
2088 vmx_disable_intercept_for_msr(vcpu,
2092 case MSR_IA32_TSX_CTRL:
2093 if (!msr_info->host_initiated &&
2094 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2096 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2099 case MSR_IA32_PRED_CMD:
2100 if (!msr_info->host_initiated &&
2101 !guest_has_pred_cmd_msr(vcpu))
2104 if (data & ~PRED_CMD_IBPB)
2106 if (!boot_cpu_has(X86_FEATURE_IBPB))
2111 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2115 * When it's written (to non-zero) for the first time, pass
2119 * The handling of the MSR bitmap for L2 guests is done in
2120 * nested_vmx_prepare_msr_bitmap. We should not touch the
2121 * vmcs02.msr_bitmap here since it gets completely overwritten
2124 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
2126 case MSR_IA32_CR_PAT:
2127 if (!kvm_pat_valid(data))
2130 if (is_guest_mode(vcpu) &&
2131 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2132 get_vmcs12(vcpu)->guest_ia32_pat = data;
2134 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2135 vmcs_write64(GUEST_IA32_PAT, data);
2136 vcpu->arch.pat = data;
2139 ret = kvm_set_msr_common(vcpu, msr_info);
2141 case MSR_IA32_TSC_ADJUST:
2142 ret = kvm_set_msr_common(vcpu, msr_info);
2144 case MSR_IA32_MCG_EXT_CTL:
2145 if ((!msr_info->host_initiated &&
2146 !(to_vmx(vcpu)->msr_ia32_feature_control &
2147 FEAT_CTL_LMCE_ENABLED)) ||
2148 (data & ~MCG_EXT_CTL_LMCE_EN))
2150 vcpu->arch.mcg_ext_ctl = data;
2152 case MSR_IA32_FEAT_CTL:
2153 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2154 (to_vmx(vcpu)->msr_ia32_feature_control &
2155 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2157 vmx->msr_ia32_feature_control = data;
2158 if (msr_info->host_initiated && data == 0)
2159 vmx_leave_nested(vcpu);
2161 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2162 if (!msr_info->host_initiated)
2163 return 1; /* they are read-only */
2164 if (!nested_vmx_allowed(vcpu))
2166 return vmx_set_vmx_msr(vcpu, msr_index, data);
2167 case MSR_IA32_RTIT_CTL:
2168 if (!vmx_pt_mode_is_host_guest() ||
2169 vmx_rtit_ctl_check(vcpu, data) ||
2172 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2173 vmx->pt_desc.guest.ctl = data;
2174 pt_update_intercept_for_msr(vcpu);
2176 case MSR_IA32_RTIT_STATUS:
2177 if (!pt_can_write_msr(vmx))
2179 if (data & MSR_IA32_RTIT_STATUS_MASK)
2181 vmx->pt_desc.guest.status = data;
2183 case MSR_IA32_RTIT_CR3_MATCH:
2184 if (!pt_can_write_msr(vmx))
2186 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2187 PT_CAP_cr3_filtering))
2189 vmx->pt_desc.guest.cr3_match = data;
2191 case MSR_IA32_RTIT_OUTPUT_BASE:
2192 if (!pt_can_write_msr(vmx))
2194 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2195 PT_CAP_topa_output) &&
2196 !intel_pt_validate_cap(vmx->pt_desc.caps,
2197 PT_CAP_single_range_output))
2199 if (!pt_output_base_valid(vcpu, data))
2201 vmx->pt_desc.guest.output_base = data;
2203 case MSR_IA32_RTIT_OUTPUT_MASK:
2204 if (!pt_can_write_msr(vmx))
2206 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2207 PT_CAP_topa_output) &&
2208 !intel_pt_validate_cap(vmx->pt_desc.caps,
2209 PT_CAP_single_range_output))
2211 vmx->pt_desc.guest.output_mask = data;
2213 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2214 if (!pt_can_write_msr(vmx))
2216 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2217 if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2218 PT_CAP_num_address_ranges))
2220 if (is_noncanonical_address(data, vcpu))
2223 vmx->pt_desc.guest.addr_b[index / 2] = data;
2225 vmx->pt_desc.guest.addr_a[index / 2] = data;
2228 if (!msr_info->host_initiated &&
2229 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2231 /* Check reserved bit, higher 32 bits should be zero */
2232 if ((data >> 32) != 0)
2235 case MSR_IA32_PERF_CAPABILITIES:
2236 if (data && !vcpu_to_pmu(vcpu)->version)
2238 if (data & PMU_CAP_LBR_FMT) {
2239 if ((data & PMU_CAP_LBR_FMT) !=
2240 (vmx_get_perf_capabilities() & PMU_CAP_LBR_FMT))
2242 if (!intel_pmu_lbr_is_compatible(vcpu))
2245 ret = kvm_set_msr_common(vcpu, msr_info);
2250 msr = vmx_find_uret_msr(vmx, msr_index);
2252 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2254 ret = kvm_set_msr_common(vcpu, msr_info);
2260 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2262 unsigned long guest_owned_bits;
2264 kvm_register_mark_available(vcpu, reg);
2268 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2271 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2273 case VCPU_EXREG_PDPTR:
2275 ept_save_pdptrs(vcpu);
2277 case VCPU_EXREG_CR0:
2278 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2280 vcpu->arch.cr0 &= ~guest_owned_bits;
2281 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2283 case VCPU_EXREG_CR3:
2284 if (is_unrestricted_guest(vcpu) ||
2285 (enable_ept && is_paging(vcpu)))
2286 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2288 case VCPU_EXREG_CR4:
2289 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2291 vcpu->arch.cr4 &= ~guest_owned_bits;
2292 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2300 static __init int cpu_has_kvm_support(void)
2302 return cpu_has_vmx();
2305 static __init int vmx_disabled_by_bios(void)
2307 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2308 !boot_cpu_has(X86_FEATURE_VMX);
2311 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2315 cr4_set_bits(X86_CR4_VMXE);
2317 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2318 _ASM_EXTABLE(1b, %l[fault])
2319 : : [vmxon_pointer] "m"(vmxon_pointer)
2324 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2325 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2326 cr4_clear_bits(X86_CR4_VMXE);
2331 static int hardware_enable(void)
2333 int cpu = raw_smp_processor_id();
2334 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2337 if (cr4_read_shadow() & X86_CR4_VMXE)
2341 * This can happen if we hot-added a CPU but failed to allocate
2342 * VP assist page for it.
2344 if (static_branch_unlikely(&enable_evmcs) &&
2345 !hv_get_vp_assist_page(cpu))
2348 intel_pt_handle_vmx(1);
2350 r = kvm_cpu_vmxon(phys_addr);
2352 intel_pt_handle_vmx(0);
2362 static void vmclear_local_loaded_vmcss(void)
2364 int cpu = raw_smp_processor_id();
2365 struct loaded_vmcs *v, *n;
2367 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2368 loaded_vmcss_on_cpu_link)
2369 __loaded_vmcs_clear(v);
2372 static void hardware_disable(void)
2374 vmclear_local_loaded_vmcss();
2377 kvm_spurious_fault();
2379 intel_pt_handle_vmx(0);
2383 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2384 * directly instead of going through cpu_has(), to ensure KVM is trapping
2385 * ENCLS whenever it's supported in hardware. It does not matter whether
2386 * the host OS supports or has enabled SGX.
2388 static bool cpu_has_sgx(void)
2390 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2393 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2394 u32 msr, u32 *result)
2396 u32 vmx_msr_low, vmx_msr_high;
2397 u32 ctl = ctl_min | ctl_opt;
2399 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2401 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2402 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2404 /* Ensure minimum (required) set of control bits are supported. */
2412 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2413 struct vmx_capability *vmx_cap)
2415 u32 vmx_msr_low, vmx_msr_high;
2416 u32 min, opt, min2, opt2;
2417 u32 _pin_based_exec_control = 0;
2418 u32 _cpu_based_exec_control = 0;
2419 u32 _cpu_based_2nd_exec_control = 0;
2420 u32 _vmexit_control = 0;
2421 u32 _vmentry_control = 0;
2423 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2424 min = CPU_BASED_HLT_EXITING |
2425 #ifdef CONFIG_X86_64
2426 CPU_BASED_CR8_LOAD_EXITING |
2427 CPU_BASED_CR8_STORE_EXITING |
2429 CPU_BASED_CR3_LOAD_EXITING |
2430 CPU_BASED_CR3_STORE_EXITING |
2431 CPU_BASED_UNCOND_IO_EXITING |
2432 CPU_BASED_MOV_DR_EXITING |
2433 CPU_BASED_USE_TSC_OFFSETTING |
2434 CPU_BASED_MWAIT_EXITING |
2435 CPU_BASED_MONITOR_EXITING |
2436 CPU_BASED_INVLPG_EXITING |
2437 CPU_BASED_RDPMC_EXITING;
2439 opt = CPU_BASED_TPR_SHADOW |
2440 CPU_BASED_USE_MSR_BITMAPS |
2441 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2442 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2443 &_cpu_based_exec_control) < 0)
2445 #ifdef CONFIG_X86_64
2446 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2447 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2448 ~CPU_BASED_CR8_STORE_EXITING;
2450 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2452 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2453 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2454 SECONDARY_EXEC_WBINVD_EXITING |
2455 SECONDARY_EXEC_ENABLE_VPID |
2456 SECONDARY_EXEC_ENABLE_EPT |
2457 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2458 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2459 SECONDARY_EXEC_DESC |
2460 SECONDARY_EXEC_ENABLE_RDTSCP |
2461 SECONDARY_EXEC_ENABLE_INVPCID |
2462 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2463 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2464 SECONDARY_EXEC_SHADOW_VMCS |
2465 SECONDARY_EXEC_XSAVES |
2466 SECONDARY_EXEC_RDSEED_EXITING |
2467 SECONDARY_EXEC_RDRAND_EXITING |
2468 SECONDARY_EXEC_ENABLE_PML |
2469 SECONDARY_EXEC_TSC_SCALING |
2470 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2471 SECONDARY_EXEC_PT_USE_GPA |
2472 SECONDARY_EXEC_PT_CONCEAL_VMX |
2473 SECONDARY_EXEC_ENABLE_VMFUNC |
2474 SECONDARY_EXEC_BUS_LOCK_DETECTION;
2476 opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2477 if (adjust_vmx_controls(min2, opt2,
2478 MSR_IA32_VMX_PROCBASED_CTLS2,
2479 &_cpu_based_2nd_exec_control) < 0)
2482 #ifndef CONFIG_X86_64
2483 if (!(_cpu_based_2nd_exec_control &
2484 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2485 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2488 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2489 _cpu_based_2nd_exec_control &= ~(
2490 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2491 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2492 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2494 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2495 &vmx_cap->ept, &vmx_cap->vpid);
2497 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2498 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2500 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2501 CPU_BASED_CR3_STORE_EXITING |
2502 CPU_BASED_INVLPG_EXITING);
2503 } else if (vmx_cap->ept) {
2505 pr_warn_once("EPT CAP should not exist if not support "
2506 "1-setting enable EPT VM-execution control\n");
2508 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2511 pr_warn_once("VPID CAP should not exist if not support "
2512 "1-setting enable VPID VM-execution control\n");
2515 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2516 #ifdef CONFIG_X86_64
2517 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2519 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2520 VM_EXIT_LOAD_IA32_PAT |
2521 VM_EXIT_LOAD_IA32_EFER |
2522 VM_EXIT_CLEAR_BNDCFGS |
2523 VM_EXIT_PT_CONCEAL_PIP |
2524 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2525 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2526 &_vmexit_control) < 0)
2529 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2530 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2531 PIN_BASED_VMX_PREEMPTION_TIMER;
2532 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2533 &_pin_based_exec_control) < 0)
2536 if (cpu_has_broken_vmx_preemption_timer())
2537 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2538 if (!(_cpu_based_2nd_exec_control &
2539 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2540 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2542 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2543 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2544 VM_ENTRY_LOAD_IA32_PAT |
2545 VM_ENTRY_LOAD_IA32_EFER |
2546 VM_ENTRY_LOAD_BNDCFGS |
2547 VM_ENTRY_PT_CONCEAL_PIP |
2548 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2549 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2550 &_vmentry_control) < 0)
2554 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2555 * can't be used due to an errata where VM Exit may incorrectly clear
2556 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2557 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2559 if (boot_cpu_data.x86 == 0x6) {
2560 switch (boot_cpu_data.x86_model) {
2561 case 26: /* AAK155 */
2562 case 30: /* AAP115 */
2563 case 37: /* AAT100 */
2564 case 44: /* BC86,AAY89,BD102 */
2566 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2567 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2568 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2569 "does not work properly. Using workaround\n");
2577 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2579 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2580 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2583 #ifdef CONFIG_X86_64
2584 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2585 if (vmx_msr_high & (1u<<16))
2589 /* Require Write-Back (WB) memory type for VMCS accesses. */
2590 if (((vmx_msr_high >> 18) & 15) != 6)
2593 vmcs_conf->size = vmx_msr_high & 0x1fff;
2594 vmcs_conf->order = get_order(vmcs_conf->size);
2595 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2597 vmcs_conf->revision_id = vmx_msr_low;
2599 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2600 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2601 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2602 vmcs_conf->vmexit_ctrl = _vmexit_control;
2603 vmcs_conf->vmentry_ctrl = _vmentry_control;
2605 #if IS_ENABLED(CONFIG_HYPERV)
2606 if (enlightened_vmcs)
2607 evmcs_sanitize_exec_ctrls(vmcs_conf);
2613 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2615 int node = cpu_to_node(cpu);
2619 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2622 vmcs = page_address(pages);
2623 memset(vmcs, 0, vmcs_config.size);
2625 /* KVM supports Enlightened VMCS v1 only */
2626 if (static_branch_unlikely(&enable_evmcs))
2627 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2629 vmcs->hdr.revision_id = vmcs_config.revision_id;
2632 vmcs->hdr.shadow_vmcs = 1;
2636 void free_vmcs(struct vmcs *vmcs)
2638 free_pages((unsigned long)vmcs, vmcs_config.order);
2642 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2644 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2646 if (!loaded_vmcs->vmcs)
2648 loaded_vmcs_clear(loaded_vmcs);
2649 free_vmcs(loaded_vmcs->vmcs);
2650 loaded_vmcs->vmcs = NULL;
2651 if (loaded_vmcs->msr_bitmap)
2652 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2653 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2656 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2658 loaded_vmcs->vmcs = alloc_vmcs(false);
2659 if (!loaded_vmcs->vmcs)
2662 vmcs_clear(loaded_vmcs->vmcs);
2664 loaded_vmcs->shadow_vmcs = NULL;
2665 loaded_vmcs->hv_timer_soft_disabled = false;
2666 loaded_vmcs->cpu = -1;
2667 loaded_vmcs->launched = 0;
2669 if (cpu_has_vmx_msr_bitmap()) {
2670 loaded_vmcs->msr_bitmap = (unsigned long *)
2671 __get_free_page(GFP_KERNEL_ACCOUNT);
2672 if (!loaded_vmcs->msr_bitmap)
2674 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2676 if (IS_ENABLED(CONFIG_HYPERV) &&
2677 static_branch_unlikely(&enable_evmcs) &&
2678 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2679 struct hv_enlightened_vmcs *evmcs =
2680 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2682 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2686 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2687 memset(&loaded_vmcs->controls_shadow, 0,
2688 sizeof(struct vmcs_controls_shadow));
2693 free_loaded_vmcs(loaded_vmcs);
2697 static void free_kvm_area(void)
2701 for_each_possible_cpu(cpu) {
2702 free_vmcs(per_cpu(vmxarea, cpu));
2703 per_cpu(vmxarea, cpu) = NULL;
2707 static __init int alloc_kvm_area(void)
2711 for_each_possible_cpu(cpu) {
2714 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2721 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2722 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2723 * revision_id reported by MSR_IA32_VMX_BASIC.
2725 * However, even though not explicitly documented by
2726 * TLFS, VMXArea passed as VMXON argument should
2727 * still be marked with revision_id reported by
2730 if (static_branch_unlikely(&enable_evmcs))
2731 vmcs->hdr.revision_id = vmcs_config.revision_id;
2733 per_cpu(vmxarea, cpu) = vmcs;
2738 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2739 struct kvm_segment *save)
2741 if (!emulate_invalid_guest_state) {
2743 * CS and SS RPL should be equal during guest entry according
2744 * to VMX spec, but in reality it is not always so. Since vcpu
2745 * is in the middle of the transition from real mode to
2746 * protected mode it is safe to assume that RPL 0 is a good
2749 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2750 save->selector &= ~SEGMENT_RPL_MASK;
2751 save->dpl = save->selector & SEGMENT_RPL_MASK;
2754 vmx_set_segment(vcpu, save, seg);
2757 static void enter_pmode(struct kvm_vcpu *vcpu)
2759 unsigned long flags;
2760 struct vcpu_vmx *vmx = to_vmx(vcpu);
2763 * Update real mode segment cache. It may be not up-to-date if sement
2764 * register was written while vcpu was in a guest mode.
2766 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2767 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2768 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2769 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2770 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2771 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2773 vmx->rmode.vm86_active = 0;
2775 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2777 flags = vmcs_readl(GUEST_RFLAGS);
2778 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2779 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2780 vmcs_writel(GUEST_RFLAGS, flags);
2782 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2783 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2785 vmx_update_exception_bitmap(vcpu);
2787 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2788 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2789 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2790 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2791 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2792 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2795 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2797 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2798 struct kvm_segment var = *save;
2801 if (seg == VCPU_SREG_CS)
2804 if (!emulate_invalid_guest_state) {
2805 var.selector = var.base >> 4;
2806 var.base = var.base & 0xffff0;
2816 if (save->base & 0xf)
2817 printk_once(KERN_WARNING "kvm: segment base is not "
2818 "paragraph aligned when entering "
2819 "protected mode (seg=%d)", seg);
2822 vmcs_write16(sf->selector, var.selector);
2823 vmcs_writel(sf->base, var.base);
2824 vmcs_write32(sf->limit, var.limit);
2825 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2828 static void enter_rmode(struct kvm_vcpu *vcpu)
2830 unsigned long flags;
2831 struct vcpu_vmx *vmx = to_vmx(vcpu);
2832 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2834 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2835 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2836 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2837 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2838 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2839 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2840 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2842 vmx->rmode.vm86_active = 1;
2845 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2846 * vcpu. Warn the user that an update is overdue.
2848 if (!kvm_vmx->tss_addr)
2849 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2850 "called before entering vcpu\n");
2852 vmx_segment_cache_clear(vmx);
2854 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2855 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2856 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2858 flags = vmcs_readl(GUEST_RFLAGS);
2859 vmx->rmode.save_rflags = flags;
2861 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2863 vmcs_writel(GUEST_RFLAGS, flags);
2864 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2865 vmx_update_exception_bitmap(vcpu);
2867 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2868 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2869 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2870 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2871 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2872 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2874 kvm_mmu_reset_context(vcpu);
2877 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2879 struct vcpu_vmx *vmx = to_vmx(vcpu);
2880 struct vmx_uret_msr *msr = vmx_find_uret_msr(vmx, MSR_EFER);
2882 /* Nothing to do if hardware doesn't support EFER. */
2886 vcpu->arch.efer = efer;
2887 if (efer & EFER_LMA) {
2888 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2891 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2893 msr->data = efer & ~EFER_LME;
2899 #ifdef CONFIG_X86_64
2901 static void enter_lmode(struct kvm_vcpu *vcpu)
2905 vmx_segment_cache_clear(to_vmx(vcpu));
2907 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2908 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2909 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2911 vmcs_write32(GUEST_TR_AR_BYTES,
2912 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2913 | VMX_AR_TYPE_BUSY_64_TSS);
2915 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2918 static void exit_lmode(struct kvm_vcpu *vcpu)
2920 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2921 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2926 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
2928 struct vcpu_vmx *vmx = to_vmx(vcpu);
2931 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
2932 * the CPU is not required to invalidate guest-physical mappings on
2933 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
2934 * associated with the root EPT structure and not any particular VPID
2935 * (INVVPID also isn't required to invalidate guest-physical mappings).
2939 } else if (enable_vpid) {
2940 if (cpu_has_vmx_invvpid_global()) {
2941 vpid_sync_vcpu_global();
2943 vpid_sync_vcpu_single(vmx->vpid);
2944 vpid_sync_vcpu_single(vmx->nested.vpid02);
2949 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
2951 struct kvm_mmu *mmu = vcpu->arch.mmu;
2952 u64 root_hpa = mmu->root_hpa;
2954 /* No flush required if the current context is invalid. */
2955 if (!VALID_PAGE(root_hpa))
2959 ept_sync_context(construct_eptp(vcpu, root_hpa,
2960 mmu->shadow_root_level));
2961 else if (!is_guest_mode(vcpu))
2962 vpid_sync_context(to_vmx(vcpu)->vpid);
2964 vpid_sync_context(nested_get_vpid02(vcpu));
2967 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2970 * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
2971 * vmx_flush_tlb_guest() for an explanation of why this is ok.
2973 vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
2976 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
2979 * vpid_sync_context() is a nop if vmx->vpid==0, e.g. if enable_vpid==0
2980 * or a vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit
2981 * are required to flush GVA->{G,H}PA mappings from the TLB if vpid is
2982 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
2983 * i.e. no explicit INVVPID is necessary.
2985 vpid_sync_context(to_vmx(vcpu)->vpid);
2988 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
2990 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2992 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
2995 if (is_pae_paging(vcpu)) {
2996 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2997 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2998 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2999 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3003 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3005 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3007 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3010 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3011 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3012 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3013 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3015 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
3018 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3020 struct kvm_vcpu *vcpu)
3022 struct vcpu_vmx *vmx = to_vmx(vcpu);
3024 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3025 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3026 if (!(cr0 & X86_CR0_PG)) {
3027 /* From paging/starting to nonpaging */
3028 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3029 CPU_BASED_CR3_STORE_EXITING);
3030 vcpu->arch.cr0 = cr0;
3031 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3032 } else if (!is_paging(vcpu)) {
3033 /* From nonpaging to paging */
3034 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3035 CPU_BASED_CR3_STORE_EXITING);
3036 vcpu->arch.cr0 = cr0;
3037 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3040 if (!(cr0 & X86_CR0_WP))
3041 *hw_cr0 &= ~X86_CR0_WP;
3044 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3046 struct vcpu_vmx *vmx = to_vmx(vcpu);
3047 unsigned long hw_cr0;
3049 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3050 if (is_unrestricted_guest(vcpu))
3051 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3053 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3055 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3058 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3062 #ifdef CONFIG_X86_64
3063 if (vcpu->arch.efer & EFER_LME) {
3064 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3066 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3071 if (enable_ept && !is_unrestricted_guest(vcpu))
3072 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3074 vmcs_writel(CR0_READ_SHADOW, cr0);
3075 vmcs_writel(GUEST_CR0, hw_cr0);
3076 vcpu->arch.cr0 = cr0;
3077 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3079 /* depends on vcpu->arch.cr0 to be set to a new value */
3080 vmx->emulation_required = emulation_required(vcpu);
3083 static int vmx_get_max_tdp_level(void)
3085 if (cpu_has_vmx_ept_5levels())
3090 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa,
3093 u64 eptp = VMX_EPTP_MT_WB;
3095 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3097 if (enable_ept_ad_bits &&
3098 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3099 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3100 eptp |= (root_hpa & PAGE_MASK);
3105 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, unsigned long pgd,
3108 struct kvm *kvm = vcpu->kvm;
3109 bool update_guest_cr3 = true;
3110 unsigned long guest_cr3;
3114 eptp = construct_eptp(vcpu, pgd, pgd_level);
3115 vmcs_write64(EPT_POINTER, eptp);
3117 if (kvm_x86_ops.tlb_remote_flush) {
3118 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3119 to_vmx(vcpu)->ept_pointer = eptp;
3120 to_kvm_vmx(kvm)->ept_pointers_match
3121 = EPT_POINTERS_CHECK;
3122 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3125 if (!enable_unrestricted_guest && !is_paging(vcpu))
3126 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3127 else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3128 guest_cr3 = vcpu->arch.cr3;
3129 else /* vmcs01.GUEST_CR3 is already up-to-date. */
3130 update_guest_cr3 = false;
3131 vmx_ept_load_pdptrs(vcpu);
3136 if (update_guest_cr3)
3137 vmcs_writel(GUEST_CR3, guest_cr3);
3140 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3143 * We operate under the default treatment of SMM, so VMX cannot be
3144 * enabled under SMM. Note, whether or not VMXE is allowed at all is
3145 * handled by kvm_is_valid_cr4().
3147 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3150 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3156 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3158 unsigned long old_cr4 = vcpu->arch.cr4;
3159 struct vcpu_vmx *vmx = to_vmx(vcpu);
3161 * Pass through host's Machine Check Enable value to hw_cr4, which
3162 * is in force while we are in guest mode. Do not let guests control
3163 * this bit, even if host CR4.MCE == 0.
3165 unsigned long hw_cr4;
3167 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3168 if (is_unrestricted_guest(vcpu))
3169 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3170 else if (vmx->rmode.vm86_active)
3171 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3173 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3175 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3176 if (cr4 & X86_CR4_UMIP) {
3177 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3178 hw_cr4 &= ~X86_CR4_UMIP;
3179 } else if (!is_guest_mode(vcpu) ||
3180 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3181 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3185 vcpu->arch.cr4 = cr4;
3186 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3188 if (!is_unrestricted_guest(vcpu)) {
3190 if (!is_paging(vcpu)) {
3191 hw_cr4 &= ~X86_CR4_PAE;
3192 hw_cr4 |= X86_CR4_PSE;
3193 } else if (!(cr4 & X86_CR4_PAE)) {
3194 hw_cr4 &= ~X86_CR4_PAE;
3199 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3200 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3201 * to be manually disabled when guest switches to non-paging
3204 * If !enable_unrestricted_guest, the CPU is always running
3205 * with CR0.PG=1 and CR4 needs to be modified.
3206 * If enable_unrestricted_guest, the CPU automatically
3207 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3209 if (!is_paging(vcpu))
3210 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3213 vmcs_writel(CR4_READ_SHADOW, cr4);
3214 vmcs_writel(GUEST_CR4, hw_cr4);
3216 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3217 kvm_update_cpuid_runtime(vcpu);
3220 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3222 struct vcpu_vmx *vmx = to_vmx(vcpu);
3225 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3226 *var = vmx->rmode.segs[seg];
3227 if (seg == VCPU_SREG_TR
3228 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3230 var->base = vmx_read_guest_seg_base(vmx, seg);
3231 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3234 var->base = vmx_read_guest_seg_base(vmx, seg);
3235 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3236 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3237 ar = vmx_read_guest_seg_ar(vmx, seg);
3238 var->unusable = (ar >> 16) & 1;
3239 var->type = ar & 15;
3240 var->s = (ar >> 4) & 1;
3241 var->dpl = (ar >> 5) & 3;
3243 * Some userspaces do not preserve unusable property. Since usable
3244 * segment has to be present according to VMX spec we can use present
3245 * property to amend userspace bug by making unusable segment always
3246 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3247 * segment as unusable.
3249 var->present = !var->unusable;
3250 var->avl = (ar >> 12) & 1;
3251 var->l = (ar >> 13) & 1;
3252 var->db = (ar >> 14) & 1;
3253 var->g = (ar >> 15) & 1;
3256 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3258 struct kvm_segment s;
3260 if (to_vmx(vcpu)->rmode.vm86_active) {
3261 vmx_get_segment(vcpu, &s, seg);
3264 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3267 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3269 struct vcpu_vmx *vmx = to_vmx(vcpu);
3271 if (unlikely(vmx->rmode.vm86_active))
3274 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3275 return VMX_AR_DPL(ar);
3279 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3283 if (var->unusable || !var->present)
3286 ar = var->type & 15;
3287 ar |= (var->s & 1) << 4;
3288 ar |= (var->dpl & 3) << 5;
3289 ar |= (var->present & 1) << 7;
3290 ar |= (var->avl & 1) << 12;
3291 ar |= (var->l & 1) << 13;
3292 ar |= (var->db & 1) << 14;
3293 ar |= (var->g & 1) << 15;
3299 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3301 struct vcpu_vmx *vmx = to_vmx(vcpu);
3302 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3304 vmx_segment_cache_clear(vmx);
3306 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3307 vmx->rmode.segs[seg] = *var;
3308 if (seg == VCPU_SREG_TR)
3309 vmcs_write16(sf->selector, var->selector);
3311 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3315 vmcs_writel(sf->base, var->base);
3316 vmcs_write32(sf->limit, var->limit);
3317 vmcs_write16(sf->selector, var->selector);
3320 * Fix the "Accessed" bit in AR field of segment registers for older
3322 * IA32 arch specifies that at the time of processor reset the
3323 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3324 * is setting it to 0 in the userland code. This causes invalid guest
3325 * state vmexit when "unrestricted guest" mode is turned on.
3326 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3327 * tree. Newer qemu binaries with that qemu fix would not need this
3330 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3331 var->type |= 0x1; /* Accessed */
3333 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3336 vmx->emulation_required = emulation_required(vcpu);
3339 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3341 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3343 *db = (ar >> 14) & 1;
3344 *l = (ar >> 13) & 1;
3347 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3349 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3350 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3353 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3355 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3356 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3359 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3361 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3362 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3365 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3367 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3368 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3371 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3373 struct kvm_segment var;
3376 vmx_get_segment(vcpu, &var, seg);
3378 if (seg == VCPU_SREG_CS)
3380 ar = vmx_segment_access_rights(&var);
3382 if (var.base != (var.selector << 4))
3384 if (var.limit != 0xffff)
3392 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3394 struct kvm_segment cs;
3395 unsigned int cs_rpl;
3397 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3398 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3402 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3406 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3407 if (cs.dpl > cs_rpl)
3410 if (cs.dpl != cs_rpl)
3416 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3420 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3422 struct kvm_segment ss;
3423 unsigned int ss_rpl;
3425 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3426 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3430 if (ss.type != 3 && ss.type != 7)
3434 if (ss.dpl != ss_rpl) /* DPL != RPL */
3442 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3444 struct kvm_segment var;
3447 vmx_get_segment(vcpu, &var, seg);
3448 rpl = var.selector & SEGMENT_RPL_MASK;
3456 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3457 if (var.dpl < rpl) /* DPL < RPL */
3461 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3467 static bool tr_valid(struct kvm_vcpu *vcpu)
3469 struct kvm_segment tr;
3471 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3475 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3477 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3485 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3487 struct kvm_segment ldtr;
3489 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3493 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3503 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3505 struct kvm_segment cs, ss;
3507 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3508 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3510 return ((cs.selector & SEGMENT_RPL_MASK) ==
3511 (ss.selector & SEGMENT_RPL_MASK));
3515 * Check if guest state is valid. Returns true if valid, false if
3517 * We assume that registers are always usable
3519 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3521 /* real mode guest state checks */
3522 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3523 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3525 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3527 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3529 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3531 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3533 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3536 /* protected mode guest state checks */
3537 if (!cs_ss_rpl_check(vcpu))
3539 if (!code_segment_valid(vcpu))
3541 if (!stack_segment_valid(vcpu))
3543 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3545 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3547 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3549 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3551 if (!tr_valid(vcpu))
3553 if (!ldtr_valid(vcpu))
3557 * - Add checks on RIP
3558 * - Add checks on RFLAGS
3564 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3566 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3570 for (i = 0; i < 3; i++) {
3571 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3575 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3576 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3580 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3586 static int init_rmode_identity_map(struct kvm *kvm)
3588 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3593 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3594 mutex_lock(&kvm->slots_lock);
3596 if (likely(kvm_vmx->ept_identity_pagetable_done))
3599 if (!kvm_vmx->ept_identity_map_addr)
3600 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3602 uaddr = __x86_set_memory_region(kvm,
3603 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3604 kvm_vmx->ept_identity_map_addr,
3606 if (IS_ERR(uaddr)) {
3611 /* Set up identity-mapping pagetable for EPT in real mode */
3612 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3613 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3614 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3615 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3620 kvm_vmx->ept_identity_pagetable_done = true;
3623 mutex_unlock(&kvm->slots_lock);
3627 static void seg_setup(int seg)
3629 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3632 vmcs_write16(sf->selector, 0);
3633 vmcs_writel(sf->base, 0);
3634 vmcs_write32(sf->limit, 0xffff);
3636 if (seg == VCPU_SREG_CS)
3637 ar |= 0x08; /* code segment */
3639 vmcs_write32(sf->ar_bytes, ar);
3642 static int alloc_apic_access_page(struct kvm *kvm)
3648 mutex_lock(&kvm->slots_lock);
3649 if (kvm->arch.apic_access_page_done)
3651 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3652 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3658 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3659 if (is_error_page(page)) {
3665 * Do not pin the page in memory, so that memory hot-unplug
3666 * is able to migrate it.
3669 kvm->arch.apic_access_page_done = true;
3671 mutex_unlock(&kvm->slots_lock);
3675 int allocate_vpid(void)
3681 spin_lock(&vmx_vpid_lock);
3682 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3683 if (vpid < VMX_NR_VPIDS)
3684 __set_bit(vpid, vmx_vpid_bitmap);
3687 spin_unlock(&vmx_vpid_lock);
3691 void free_vpid(int vpid)
3693 if (!enable_vpid || vpid == 0)
3695 spin_lock(&vmx_vpid_lock);
3696 __clear_bit(vpid, vmx_vpid_bitmap);
3697 spin_unlock(&vmx_vpid_lock);
3700 static void vmx_clear_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3702 int f = sizeof(unsigned long);
3705 __clear_bit(msr, msr_bitmap + 0x000 / f);
3706 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3707 __clear_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3710 static void vmx_clear_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3712 int f = sizeof(unsigned long);
3715 __clear_bit(msr, msr_bitmap + 0x800 / f);
3716 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3717 __clear_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3720 static void vmx_set_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3722 int f = sizeof(unsigned long);
3725 __set_bit(msr, msr_bitmap + 0x000 / f);
3726 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3727 __set_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3730 static void vmx_set_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3732 int f = sizeof(unsigned long);
3735 __set_bit(msr, msr_bitmap + 0x800 / f);
3736 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3737 __set_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3740 static __always_inline void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu,
3743 struct vcpu_vmx *vmx = to_vmx(vcpu);
3744 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3746 if (!cpu_has_vmx_msr_bitmap())
3749 if (static_branch_unlikely(&enable_evmcs))
3750 evmcs_touch_msr_bitmap();
3753 * Mark the desired intercept state in shadow bitmap, this is needed
3754 * for resync when the MSR filters change.
3756 if (is_valid_passthrough_msr(msr)) {
3757 int idx = possible_passthrough_msr_slot(msr);
3759 if (idx != -ENOENT) {
3760 if (type & MSR_TYPE_R)
3761 clear_bit(idx, vmx->shadow_msr_intercept.read);
3762 if (type & MSR_TYPE_W)
3763 clear_bit(idx, vmx->shadow_msr_intercept.write);
3767 if ((type & MSR_TYPE_R) &&
3768 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3769 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3770 type &= ~MSR_TYPE_R;
3773 if ((type & MSR_TYPE_W) &&
3774 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3775 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3776 type &= ~MSR_TYPE_W;
3779 if (type & MSR_TYPE_R)
3780 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3782 if (type & MSR_TYPE_W)
3783 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3786 static __always_inline void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu,
3789 struct vcpu_vmx *vmx = to_vmx(vcpu);
3790 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3792 if (!cpu_has_vmx_msr_bitmap())
3795 if (static_branch_unlikely(&enable_evmcs))
3796 evmcs_touch_msr_bitmap();
3799 * Mark the desired intercept state in shadow bitmap, this is needed
3800 * for resync when the MSR filter changes.
3802 if (is_valid_passthrough_msr(msr)) {
3803 int idx = possible_passthrough_msr_slot(msr);
3805 if (idx != -ENOENT) {
3806 if (type & MSR_TYPE_R)
3807 set_bit(idx, vmx->shadow_msr_intercept.read);
3808 if (type & MSR_TYPE_W)
3809 set_bit(idx, vmx->shadow_msr_intercept.write);
3813 if (type & MSR_TYPE_R)
3814 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3816 if (type & MSR_TYPE_W)
3817 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3820 void vmx_set_intercept_for_msr(struct kvm_vcpu *vcpu,
3821 u32 msr, int type, bool value)
3824 vmx_enable_intercept_for_msr(vcpu, msr, type);
3826 vmx_disable_intercept_for_msr(vcpu, msr, type);
3829 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3833 if (cpu_has_secondary_exec_ctrls() &&
3834 (secondary_exec_controls_get(to_vmx(vcpu)) &
3835 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3836 mode |= MSR_BITMAP_MODE_X2APIC;
3837 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3838 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3844 static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
3846 unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3847 unsigned long read_intercept;
3850 read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3852 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3853 unsigned int read_idx = msr / BITS_PER_LONG;
3854 unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3856 msr_bitmap[read_idx] = read_intercept;
3857 msr_bitmap[write_idx] = ~0ul;
3861 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu, u8 mode)
3863 if (!cpu_has_vmx_msr_bitmap())
3866 vmx_reset_x2apic_msrs(vcpu, mode);
3869 * TPR reads and writes can be virtualized even if virtual interrupt
3870 * delivery is not in use.
3872 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
3873 !(mode & MSR_BITMAP_MODE_X2APIC));
3875 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3876 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
3877 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3878 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3882 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3884 struct vcpu_vmx *vmx = to_vmx(vcpu);
3885 u8 mode = vmx_msr_bitmap_mode(vcpu);
3886 u8 changed = mode ^ vmx->msr_bitmap_mode;
3891 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3892 vmx_update_msr_bitmap_x2apic(vcpu, mode);
3894 vmx->msr_bitmap_mode = mode;
3897 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
3899 struct vcpu_vmx *vmx = to_vmx(vcpu);
3900 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3903 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
3904 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
3905 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
3906 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
3907 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3908 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3909 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3913 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3915 struct vcpu_vmx *vmx = to_vmx(vcpu);
3920 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3921 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3922 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3925 rvi = vmx_get_rvi();
3927 vapic_page = vmx->nested.virtual_apic_map.hva;
3928 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3930 return ((rvi & 0xf0) > (vppr & 0xf0));
3933 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
3935 struct vcpu_vmx *vmx = to_vmx(vcpu);
3939 * Set intercept permissions for all potentially passed through MSRs
3940 * again. They will automatically get filtered through the MSR filter,
3941 * so we are back in sync after this.
3943 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
3944 u32 msr = vmx_possible_passthrough_msrs[i];
3945 bool read = test_bit(i, vmx->shadow_msr_intercept.read);
3946 bool write = test_bit(i, vmx->shadow_msr_intercept.write);
3948 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_R, read);
3949 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_W, write);
3952 pt_update_intercept_for_msr(vcpu);
3953 vmx_update_msr_bitmap_x2apic(vcpu, vmx_msr_bitmap_mode(vcpu));
3956 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3960 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3962 if (vcpu->mode == IN_GUEST_MODE) {
3964 * The vector of interrupt to be delivered to vcpu had
3965 * been set in PIR before this function.
3967 * Following cases will be reached in this block, and
3968 * we always send a notification event in all cases as
3971 * Case 1: vcpu keeps in non-root mode. Sending a
3972 * notification event posts the interrupt to vcpu.
3974 * Case 2: vcpu exits to root mode and is still
3975 * runnable. PIR will be synced to vIRR before the
3976 * next vcpu entry. Sending a notification event in
3977 * this case has no effect, as vcpu is not in root
3980 * Case 3: vcpu exits to root mode and is blocked.
3981 * vcpu_block() has already synced PIR to vIRR and
3982 * never blocks vcpu if vIRR is not cleared. Therefore,
3983 * a blocked vcpu here does not wait for any requested
3984 * interrupts in PIR, and sending a notification event
3985 * which has no effect is safe here.
3988 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3995 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3998 struct vcpu_vmx *vmx = to_vmx(vcpu);
4000 if (is_guest_mode(vcpu) &&
4001 vector == vmx->nested.posted_intr_nv) {
4003 * If a posted intr is not recognized by hardware,
4004 * we will accomplish it in the next vmentry.
4006 vmx->nested.pi_pending = true;
4007 kvm_make_request(KVM_REQ_EVENT, vcpu);
4008 /* the PIR and ON have been set by L1. */
4009 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
4010 kvm_vcpu_kick(vcpu);
4016 * Send interrupt to vcpu via posted interrupt way.
4017 * 1. If target vcpu is running(non-root mode), send posted interrupt
4018 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4019 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4020 * interrupt from PIR in next vmentry.
4022 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4024 struct vcpu_vmx *vmx = to_vmx(vcpu);
4027 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4031 if (!vcpu->arch.apicv_active)
4034 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4037 /* If a previous notification has sent the IPI, nothing to do. */
4038 if (pi_test_and_set_on(&vmx->pi_desc))
4041 if (vcpu != kvm_get_running_vcpu() &&
4042 !kvm_vcpu_trigger_posted_interrupt(vcpu, false))
4043 kvm_vcpu_kick(vcpu);
4049 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4050 * will not change in the lifetime of the guest.
4051 * Note that host-state that does change is set elsewhere. E.g., host-state
4052 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4054 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4058 unsigned long cr0, cr3, cr4;
4061 WARN_ON(cr0 & X86_CR0_TS);
4062 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4065 * Save the most likely value for this task's CR3 in the VMCS.
4066 * We can't use __get_current_cr3_fast() because we're not atomic.
4069 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4070 vmx->loaded_vmcs->host_state.cr3 = cr3;
4072 /* Save the most likely value for this task's CR4 in the VMCS. */
4073 cr4 = cr4_read_shadow();
4074 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4075 vmx->loaded_vmcs->host_state.cr4 = cr4;
4077 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4078 #ifdef CONFIG_X86_64
4080 * Load null selectors, so we can avoid reloading them in
4081 * vmx_prepare_switch_to_host(), in case userspace uses
4082 * the null selectors too (the expected case).
4084 vmcs_write16(HOST_DS_SELECTOR, 0);
4085 vmcs_write16(HOST_ES_SELECTOR, 0);
4087 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4088 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4090 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4091 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4093 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4095 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4097 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4098 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4099 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4100 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4102 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4103 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4104 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4107 if (cpu_has_load_ia32_efer())
4108 vmcs_write64(HOST_IA32_EFER, host_efer);
4111 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4113 struct kvm_vcpu *vcpu = &vmx->vcpu;
4115 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4116 ~vcpu->arch.cr4_guest_rsvd_bits;
4118 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PGE;
4119 if (is_guest_mode(&vmx->vcpu))
4120 vcpu->arch.cr4_guest_owned_bits &=
4121 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4122 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4125 u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4127 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4129 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4130 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4133 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4135 if (!enable_preemption_timer)
4136 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4138 return pin_based_exec_ctrl;
4141 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4143 struct vcpu_vmx *vmx = to_vmx(vcpu);
4145 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4146 if (cpu_has_secondary_exec_ctrls()) {
4147 if (kvm_vcpu_apicv_active(vcpu))
4148 secondary_exec_controls_setbit(vmx,
4149 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4150 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4152 secondary_exec_controls_clearbit(vmx,
4153 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4154 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4157 if (cpu_has_vmx_msr_bitmap())
4158 vmx_update_msr_bitmap(vcpu);
4161 u32 vmx_exec_control(struct vcpu_vmx *vmx)
4163 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4165 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4166 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4168 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4169 exec_control &= ~CPU_BASED_TPR_SHADOW;
4170 #ifdef CONFIG_X86_64
4171 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4172 CPU_BASED_CR8_LOAD_EXITING;
4176 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4177 CPU_BASED_CR3_LOAD_EXITING |
4178 CPU_BASED_INVLPG_EXITING;
4179 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4180 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4181 CPU_BASED_MONITOR_EXITING);
4182 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4183 exec_control &= ~CPU_BASED_HLT_EXITING;
4184 return exec_control;
4188 * Adjust a single secondary execution control bit to intercept/allow an
4189 * instruction in the guest. This is usually done based on whether or not a
4190 * feature has been exposed to the guest in order to correctly emulate faults.
4193 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4194 u32 control, bool enabled, bool exiting)
4197 * If the control is for an opt-in feature, clear the control if the
4198 * feature is not exposed to the guest, i.e. not enabled. If the
4199 * control is opt-out, i.e. an exiting control, clear the control if
4200 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4201 * disabled for the associated instruction. Note, the caller is
4202 * responsible presetting exec_control to set all supported bits.
4204 if (enabled == exiting)
4205 *exec_control &= ~control;
4208 * Update the nested MSR settings so that a nested VMM can/can't set
4209 * controls for features that are/aren't exposed to the guest.
4213 vmx->nested.msrs.secondary_ctls_high |= control;
4215 vmx->nested.msrs.secondary_ctls_high &= ~control;
4220 * Wrapper macro for the common case of adjusting a secondary execution control
4221 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4222 * verifies that the control is actually supported by KVM and hardware.
4224 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4228 if (cpu_has_vmx_##name()) { \
4229 __enabled = guest_cpuid_has(&(vmx)->vcpu, \
4230 X86_FEATURE_##feat_name); \
4231 vmx_adjust_secondary_exec_control(vmx, exec_control, \
4232 SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4236 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4237 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4238 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4240 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4241 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4243 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
4245 struct kvm_vcpu *vcpu = &vmx->vcpu;
4247 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4249 if (vmx_pt_mode_is_system())
4250 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4251 if (!cpu_need_virtualize_apic_accesses(vcpu))
4252 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4254 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4256 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4257 enable_unrestricted_guest = 0;
4259 if (!enable_unrestricted_guest)
4260 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4261 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4262 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4263 if (!kvm_vcpu_apicv_active(vcpu))
4264 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4265 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4266 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4268 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4269 * in vmx_set_cr4. */
4270 exec_control &= ~SECONDARY_EXEC_DESC;
4272 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4274 We can NOT enable shadow_vmcs here because we don't have yet
4277 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4280 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4282 if (cpu_has_vmx_xsaves()) {
4283 /* Exposing XSAVES only when XSAVE is exposed */
4284 bool xsaves_enabled =
4285 boot_cpu_has(X86_FEATURE_XSAVE) &&
4286 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4287 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4289 vcpu->arch.xsaves_enabled = xsaves_enabled;
4291 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4292 SECONDARY_EXEC_XSAVES,
4293 xsaves_enabled, false);
4296 vmx_adjust_sec_exec_feature(vmx, &exec_control, rdtscp, RDTSCP);
4299 * Expose INVPCID if and only if PCID is also exposed to the guest.
4300 * INVPCID takes a #UD when it's disabled in the VMCS, but a #GP or #PF
4301 * if CR4.PCIDE=0. Enumerating CPUID.INVPCID=1 would lead to incorrect
4302 * behavior from the guest perspective (it would expect #GP or #PF).
4304 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
4305 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
4306 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4309 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4310 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4312 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4313 ENABLE_USR_WAIT_PAUSE, false);
4315 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4316 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4318 vmx->secondary_exec_control = exec_control;
4321 static void ept_set_mmio_spte_mask(void)
4324 * EPT Misconfigurations can be generated if the value of bits 2:0
4325 * of an EPT paging-structure entry is 110b (write/execute).
4327 kvm_mmu_set_mmio_spte_mask(VMX_EPT_MISCONFIG_WX_VALUE, 0);
4330 #define VMX_XSS_EXIT_BITMAP 0
4333 * Noting that the initialization of Guest-state Area of VMCS is in
4336 static void init_vmcs(struct vcpu_vmx *vmx)
4339 nested_vmx_set_vmcs_shadowing_bitmap();
4341 if (cpu_has_vmx_msr_bitmap())
4342 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4344 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4347 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4349 exec_controls_set(vmx, vmx_exec_control(vmx));
4351 if (cpu_has_secondary_exec_ctrls()) {
4352 vmx_compute_secondary_exec_control(vmx);
4353 secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
4356 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4357 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4358 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4359 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4360 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4362 vmcs_write16(GUEST_INTR_STATUS, 0);
4364 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4365 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4368 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4369 vmcs_write32(PLE_GAP, ple_gap);
4370 vmx->ple_window = ple_window;
4371 vmx->ple_window_dirty = true;
4374 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4375 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4376 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4378 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4379 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4380 vmx_set_constant_host_state(vmx);
4381 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4382 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4384 if (cpu_has_vmx_vmfunc())
4385 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4387 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4388 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4389 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4390 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4391 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4393 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4394 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4396 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4398 /* 22.2.1, 20.8.1 */
4399 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4401 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4402 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4404 set_cr4_guest_host_mask(vmx);
4407 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4409 if (cpu_has_vmx_xsaves())
4410 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4413 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4414 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4417 if (cpu_has_vmx_encls_vmexit())
4418 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
4420 if (vmx_pt_mode_is_host_guest()) {
4421 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4422 /* Bit[6~0] are forced to 1, writes are ignored. */
4423 vmx->pt_desc.guest.output_mask = 0x7F;
4424 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4428 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4430 struct vcpu_vmx *vmx = to_vmx(vcpu);
4431 struct msr_data apic_base_msr;
4434 vmx->rmode.vm86_active = 0;
4437 vmx->msr_ia32_umwait_control = 0;
4439 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4440 vmx->hv_deadline_tsc = -1;
4441 kvm_set_cr8(vcpu, 0);
4444 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4445 MSR_IA32_APICBASE_ENABLE;
4446 if (kvm_vcpu_is_reset_bsp(vcpu))
4447 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4448 apic_base_msr.host_initiated = true;
4449 kvm_set_apic_base(vcpu, &apic_base_msr);
4452 vmx_segment_cache_clear(vmx);
4454 seg_setup(VCPU_SREG_CS);
4455 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4456 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4458 seg_setup(VCPU_SREG_DS);
4459 seg_setup(VCPU_SREG_ES);
4460 seg_setup(VCPU_SREG_FS);
4461 seg_setup(VCPU_SREG_GS);
4462 seg_setup(VCPU_SREG_SS);
4464 vmcs_write16(GUEST_TR_SELECTOR, 0);
4465 vmcs_writel(GUEST_TR_BASE, 0);
4466 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4467 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4469 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4470 vmcs_writel(GUEST_LDTR_BASE, 0);
4471 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4472 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4475 vmcs_write32(GUEST_SYSENTER_CS, 0);
4476 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4477 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4478 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4481 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4482 kvm_rip_write(vcpu, 0xfff0);
4484 vmcs_writel(GUEST_GDTR_BASE, 0);
4485 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4487 vmcs_writel(GUEST_IDTR_BASE, 0);
4488 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4490 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4491 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4492 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4493 if (kvm_mpx_supported())
4494 vmcs_write64(GUEST_BNDCFGS, 0);
4498 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4500 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4501 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4502 if (cpu_need_tpr_shadow(vcpu))
4503 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4504 __pa(vcpu->arch.apic->regs));
4505 vmcs_write32(TPR_THRESHOLD, 0);
4508 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4510 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4511 vmx->vcpu.arch.cr0 = cr0;
4512 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4513 vmx_set_cr4(vcpu, 0);
4514 vmx_set_efer(vcpu, 0);
4516 vmx_update_exception_bitmap(vcpu);
4518 vpid_sync_context(vmx->vpid);
4520 vmx_clear_hlt(vcpu);
4523 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4525 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4528 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4531 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4532 vmx_enable_irq_window(vcpu);
4536 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4539 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4541 struct vcpu_vmx *vmx = to_vmx(vcpu);
4543 int irq = vcpu->arch.interrupt.nr;
4545 trace_kvm_inj_virq(irq);
4547 ++vcpu->stat.irq_injections;
4548 if (vmx->rmode.vm86_active) {
4550 if (vcpu->arch.interrupt.soft)
4551 inc_eip = vcpu->arch.event_exit_inst_len;
4552 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4555 intr = irq | INTR_INFO_VALID_MASK;
4556 if (vcpu->arch.interrupt.soft) {
4557 intr |= INTR_TYPE_SOFT_INTR;
4558 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4559 vmx->vcpu.arch.event_exit_inst_len);
4561 intr |= INTR_TYPE_EXT_INTR;
4562 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4564 vmx_clear_hlt(vcpu);
4567 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4569 struct vcpu_vmx *vmx = to_vmx(vcpu);
4573 * Tracking the NMI-blocked state in software is built upon
4574 * finding the next open IRQ window. This, in turn, depends on
4575 * well-behaving guests: They have to keep IRQs disabled at
4576 * least as long as the NMI handler runs. Otherwise we may
4577 * cause NMI nesting, maybe breaking the guest. But as this is
4578 * highly unlikely, we can live with the residual risk.
4580 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4581 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4584 ++vcpu->stat.nmi_injections;
4585 vmx->loaded_vmcs->nmi_known_unmasked = false;
4587 if (vmx->rmode.vm86_active) {
4588 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4592 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4593 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4595 vmx_clear_hlt(vcpu);
4598 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4600 struct vcpu_vmx *vmx = to_vmx(vcpu);
4604 return vmx->loaded_vmcs->soft_vnmi_blocked;
4605 if (vmx->loaded_vmcs->nmi_known_unmasked)
4607 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4608 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4612 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4614 struct vcpu_vmx *vmx = to_vmx(vcpu);
4617 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4618 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4619 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4622 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4624 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4625 GUEST_INTR_STATE_NMI);
4627 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4628 GUEST_INTR_STATE_NMI);
4632 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4634 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4637 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4640 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4641 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4642 GUEST_INTR_STATE_NMI));
4645 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4647 if (to_vmx(vcpu)->nested.nested_run_pending)
4650 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4651 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4654 return !vmx_nmi_blocked(vcpu);
4657 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4659 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4662 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4663 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4664 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4667 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4669 if (to_vmx(vcpu)->nested.nested_run_pending)
4673 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4674 * e.g. if the IRQ arrived asynchronously after checking nested events.
4676 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4679 return !vmx_interrupt_blocked(vcpu);
4682 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4686 if (enable_unrestricted_guest)
4689 mutex_lock(&kvm->slots_lock);
4690 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4692 mutex_unlock(&kvm->slots_lock);
4695 return PTR_ERR(ret);
4697 to_kvm_vmx(kvm)->tss_addr = addr;
4699 return init_rmode_tss(kvm, ret);
4702 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4704 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4708 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4713 * Update instruction length as we may reinject the exception
4714 * from user space while in guest debugging mode.
4716 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4717 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4718 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4722 return !(vcpu->guest_debug &
4723 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4737 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4738 int vec, u32 err_code)
4741 * Instruction with address size override prefix opcode 0x67
4742 * Cause the #SS fault with 0 error code in VM86 mode.
4744 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4745 if (kvm_emulate_instruction(vcpu, 0)) {
4746 if (vcpu->arch.halt_request) {
4747 vcpu->arch.halt_request = 0;
4748 return kvm_vcpu_halt(vcpu);
4756 * Forward all other exceptions that are valid in real mode.
4757 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4758 * the required debugging infrastructure rework.
4760 kvm_queue_exception(vcpu, vec);
4764 static int handle_machine_check(struct kvm_vcpu *vcpu)
4766 /* handled by vmx_vcpu_run() */
4771 * If the host has split lock detection disabled, then #AC is
4772 * unconditionally injected into the guest, which is the pre split lock
4773 * detection behaviour.
4775 * If the host has split lock detection enabled then #AC is
4776 * only injected into the guest when:
4777 * - Guest CPL == 3 (user mode)
4778 * - Guest has #AC detection enabled in CR0
4779 * - Guest EFLAGS has AC bit set
4781 static inline bool guest_inject_ac(struct kvm_vcpu *vcpu)
4783 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4786 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4787 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4790 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4792 struct vcpu_vmx *vmx = to_vmx(vcpu);
4793 struct kvm_run *kvm_run = vcpu->run;
4794 u32 intr_info, ex_no, error_code;
4795 unsigned long cr2, rip, dr6;
4798 vect_info = vmx->idt_vectoring_info;
4799 intr_info = vmx_get_intr_info(vcpu);
4801 if (is_machine_check(intr_info) || is_nmi(intr_info))
4802 return 1; /* handled by handle_exception_nmi_irqoff() */
4804 if (is_invalid_opcode(intr_info))
4805 return handle_ud(vcpu);
4808 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4809 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4811 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4812 WARN_ON_ONCE(!enable_vmware_backdoor);
4815 * VMware backdoor emulation on #GP interception only handles
4816 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4817 * error code on #GP.
4820 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4823 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4827 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4828 * MMIO, it is better to report an internal error.
4829 * See the comments in vmx_handle_exit.
4831 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4832 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4833 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4834 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4835 vcpu->run->internal.ndata = 4;
4836 vcpu->run->internal.data[0] = vect_info;
4837 vcpu->run->internal.data[1] = intr_info;
4838 vcpu->run->internal.data[2] = error_code;
4839 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
4843 if (is_page_fault(intr_info)) {
4844 cr2 = vmx_get_exit_qual(vcpu);
4845 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
4847 * EPT will cause page fault only if we need to
4848 * detect illegal GPAs.
4850 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
4851 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
4854 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4857 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4859 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4860 return handle_rmode_exception(vcpu, ex_no, error_code);
4864 dr6 = vmx_get_exit_qual(vcpu);
4865 if (!(vcpu->guest_debug &
4866 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4867 if (is_icebp(intr_info))
4868 WARN_ON(!skip_emulated_instruction(vcpu));
4870 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
4873 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
4874 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4878 * Update instruction length as we may reinject #BP from
4879 * user space while in guest debugging mode. Reading it for
4880 * #DB as well causes no harm, it is not used in that case.
4882 vmx->vcpu.arch.event_exit_inst_len =
4883 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4884 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4885 rip = kvm_rip_read(vcpu);
4886 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4887 kvm_run->debug.arch.exception = ex_no;
4890 if (guest_inject_ac(vcpu)) {
4891 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4896 * Handle split lock. Depending on detection mode this will
4897 * either warn and disable split lock detection for this
4898 * task or force SIGBUS on it.
4900 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4904 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4905 kvm_run->ex.exception = ex_no;
4906 kvm_run->ex.error_code = error_code;
4912 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4914 ++vcpu->stat.irq_exits;
4918 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4920 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4921 vcpu->mmio_needed = 0;
4925 static int handle_io(struct kvm_vcpu *vcpu)
4927 unsigned long exit_qualification;
4928 int size, in, string;
4931 exit_qualification = vmx_get_exit_qual(vcpu);
4932 string = (exit_qualification & 16) != 0;
4934 ++vcpu->stat.io_exits;
4937 return kvm_emulate_instruction(vcpu, 0);
4939 port = exit_qualification >> 16;
4940 size = (exit_qualification & 7) + 1;
4941 in = (exit_qualification & 8) != 0;
4943 return kvm_fast_pio(vcpu, size, port, in);
4947 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4950 * Patch in the VMCALL instruction:
4952 hypercall[0] = 0x0f;
4953 hypercall[1] = 0x01;
4954 hypercall[2] = 0xc1;
4957 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4958 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4960 if (is_guest_mode(vcpu)) {
4961 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4962 unsigned long orig_val = val;
4965 * We get here when L2 changed cr0 in a way that did not change
4966 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4967 * but did change L0 shadowed bits. So we first calculate the
4968 * effective cr0 value that L1 would like to write into the
4969 * hardware. It consists of the L2-owned bits from the new
4970 * value combined with the L1-owned bits from L1's guest_cr0.
4972 val = (val & ~vmcs12->cr0_guest_host_mask) |
4973 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4975 if (!nested_guest_cr0_valid(vcpu, val))
4978 if (kvm_set_cr0(vcpu, val))
4980 vmcs_writel(CR0_READ_SHADOW, orig_val);
4983 if (to_vmx(vcpu)->nested.vmxon &&
4984 !nested_host_cr0_valid(vcpu, val))
4987 return kvm_set_cr0(vcpu, val);
4991 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4993 if (is_guest_mode(vcpu)) {
4994 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4995 unsigned long orig_val = val;
4997 /* analogously to handle_set_cr0 */
4998 val = (val & ~vmcs12->cr4_guest_host_mask) |
4999 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5000 if (kvm_set_cr4(vcpu, val))
5002 vmcs_writel(CR4_READ_SHADOW, orig_val);
5005 return kvm_set_cr4(vcpu, val);
5008 static int handle_desc(struct kvm_vcpu *vcpu)
5010 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
5011 return kvm_emulate_instruction(vcpu, 0);
5014 static int handle_cr(struct kvm_vcpu *vcpu)
5016 unsigned long exit_qualification, val;
5022 exit_qualification = vmx_get_exit_qual(vcpu);
5023 cr = exit_qualification & 15;
5024 reg = (exit_qualification >> 8) & 15;
5025 switch ((exit_qualification >> 4) & 3) {
5026 case 0: /* mov to cr */
5027 val = kvm_register_readl(vcpu, reg);
5028 trace_kvm_cr_write(cr, val);
5031 err = handle_set_cr0(vcpu, val);
5032 return kvm_complete_insn_gp(vcpu, err);
5034 WARN_ON_ONCE(enable_unrestricted_guest);
5035 err = kvm_set_cr3(vcpu, val);
5036 return kvm_complete_insn_gp(vcpu, err);
5038 err = handle_set_cr4(vcpu, val);
5039 return kvm_complete_insn_gp(vcpu, err);
5041 u8 cr8_prev = kvm_get_cr8(vcpu);
5043 err = kvm_set_cr8(vcpu, cr8);
5044 ret = kvm_complete_insn_gp(vcpu, err);
5045 if (lapic_in_kernel(vcpu))
5047 if (cr8_prev <= cr8)
5050 * TODO: we might be squashing a
5051 * KVM_GUESTDBG_SINGLESTEP-triggered
5052 * KVM_EXIT_DEBUG here.
5054 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5060 WARN_ONCE(1, "Guest should always own CR0.TS");
5061 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5062 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5063 return kvm_skip_emulated_instruction(vcpu);
5064 case 1: /*mov from cr*/
5067 WARN_ON_ONCE(enable_unrestricted_guest);
5068 val = kvm_read_cr3(vcpu);
5069 kvm_register_write(vcpu, reg, val);
5070 trace_kvm_cr_read(cr, val);
5071 return kvm_skip_emulated_instruction(vcpu);
5073 val = kvm_get_cr8(vcpu);
5074 kvm_register_write(vcpu, reg, val);
5075 trace_kvm_cr_read(cr, val);
5076 return kvm_skip_emulated_instruction(vcpu);
5080 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5081 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5082 kvm_lmsw(vcpu, val);
5084 return kvm_skip_emulated_instruction(vcpu);
5088 vcpu->run->exit_reason = 0;
5089 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5090 (int)(exit_qualification >> 4) & 3, cr);
5094 static int handle_dr(struct kvm_vcpu *vcpu)
5096 unsigned long exit_qualification;
5099 exit_qualification = vmx_get_exit_qual(vcpu);
5100 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5102 /* First, if DR does not exist, trigger UD */
5103 if (!kvm_require_dr(vcpu, dr))
5106 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
5107 if (!kvm_require_cpl(vcpu, 0))
5109 dr7 = vmcs_readl(GUEST_DR7);
5112 * As the vm-exit takes precedence over the debug trap, we
5113 * need to emulate the latter, either for the host or the
5114 * guest debugging itself.
5116 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5117 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5118 vcpu->run->debug.arch.dr7 = dr7;
5119 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5120 vcpu->run->debug.arch.exception = DB_VECTOR;
5121 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5124 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5129 if (vcpu->guest_debug == 0) {
5130 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5133 * No more DR vmexits; force a reload of the debug registers
5134 * and reenter on this instruction. The next vmexit will
5135 * retrieve the full state of the debug registers.
5137 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5141 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5142 if (exit_qualification & TYPE_MOV_FROM_DR) {
5145 kvm_get_dr(vcpu, dr, &val);
5146 kvm_register_write(vcpu, reg, val);
5148 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
5151 return kvm_skip_emulated_instruction(vcpu);
5154 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5156 get_debugreg(vcpu->arch.db[0], 0);
5157 get_debugreg(vcpu->arch.db[1], 1);
5158 get_debugreg(vcpu->arch.db[2], 2);
5159 get_debugreg(vcpu->arch.db[3], 3);
5160 get_debugreg(vcpu->arch.dr6, 6);
5161 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5163 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5164 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5167 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5169 vmcs_writel(GUEST_DR7, val);
5172 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5174 kvm_apic_update_ppr(vcpu);
5178 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5180 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5182 kvm_make_request(KVM_REQ_EVENT, vcpu);
5184 ++vcpu->stat.irq_window_exits;
5188 static int handle_vmcall(struct kvm_vcpu *vcpu)
5190 return kvm_emulate_hypercall(vcpu);
5193 static int handle_invd(struct kvm_vcpu *vcpu)
5195 /* Treat an INVD instruction as a NOP and just skip it. */
5196 return kvm_skip_emulated_instruction(vcpu);
5199 static int handle_invlpg(struct kvm_vcpu *vcpu)
5201 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5203 kvm_mmu_invlpg(vcpu, exit_qualification);
5204 return kvm_skip_emulated_instruction(vcpu);
5207 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5211 err = kvm_rdpmc(vcpu);
5212 return kvm_complete_insn_gp(vcpu, err);
5215 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5217 return kvm_emulate_wbinvd(vcpu);
5220 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5222 u64 new_bv = kvm_read_edx_eax(vcpu);
5223 u32 index = kvm_rcx_read(vcpu);
5225 int err = kvm_set_xcr(vcpu, index, new_bv);
5226 return kvm_complete_insn_gp(vcpu, err);
5229 static int handle_apic_access(struct kvm_vcpu *vcpu)
5231 if (likely(fasteoi)) {
5232 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5233 int access_type, offset;
5235 access_type = exit_qualification & APIC_ACCESS_TYPE;
5236 offset = exit_qualification & APIC_ACCESS_OFFSET;
5238 * Sane guest uses MOV to write EOI, with written value
5239 * not cared. So make a short-circuit here by avoiding
5240 * heavy instruction emulation.
5242 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5243 (offset == APIC_EOI)) {
5244 kvm_lapic_set_eoi(vcpu);
5245 return kvm_skip_emulated_instruction(vcpu);
5248 return kvm_emulate_instruction(vcpu, 0);
5251 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5253 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5254 int vector = exit_qualification & 0xff;
5256 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5257 kvm_apic_set_eoi_accelerated(vcpu, vector);
5261 static int handle_apic_write(struct kvm_vcpu *vcpu)
5263 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5264 u32 offset = exit_qualification & 0xfff;
5266 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5267 kvm_apic_write_nodecode(vcpu, offset);
5271 static int handle_task_switch(struct kvm_vcpu *vcpu)
5273 struct vcpu_vmx *vmx = to_vmx(vcpu);
5274 unsigned long exit_qualification;
5275 bool has_error_code = false;
5278 int reason, type, idt_v, idt_index;
5280 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5281 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5282 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5284 exit_qualification = vmx_get_exit_qual(vcpu);
5286 reason = (u32)exit_qualification >> 30;
5287 if (reason == TASK_SWITCH_GATE && idt_v) {
5289 case INTR_TYPE_NMI_INTR:
5290 vcpu->arch.nmi_injected = false;
5291 vmx_set_nmi_mask(vcpu, true);
5293 case INTR_TYPE_EXT_INTR:
5294 case INTR_TYPE_SOFT_INTR:
5295 kvm_clear_interrupt_queue(vcpu);
5297 case INTR_TYPE_HARD_EXCEPTION:
5298 if (vmx->idt_vectoring_info &
5299 VECTORING_INFO_DELIVER_CODE_MASK) {
5300 has_error_code = true;
5302 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5305 case INTR_TYPE_SOFT_EXCEPTION:
5306 kvm_clear_exception_queue(vcpu);
5312 tss_selector = exit_qualification;
5314 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5315 type != INTR_TYPE_EXT_INTR &&
5316 type != INTR_TYPE_NMI_INTR))
5317 WARN_ON(!skip_emulated_instruction(vcpu));
5320 * TODO: What about debug traps on tss switch?
5321 * Are we supposed to inject them and update dr6?
5323 return kvm_task_switch(vcpu, tss_selector,
5324 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5325 reason, has_error_code, error_code);
5328 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5330 unsigned long exit_qualification;
5334 exit_qualification = vmx_get_exit_qual(vcpu);
5337 * EPT violation happened while executing iret from NMI,
5338 * "blocked by NMI" bit has to be set before next VM entry.
5339 * There are errata that may cause this bit to not be set:
5342 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5344 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5345 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5347 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5348 trace_kvm_page_fault(gpa, exit_qualification);
5350 /* Is it a read fault? */
5351 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5352 ? PFERR_USER_MASK : 0;
5353 /* Is it a write fault? */
5354 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5355 ? PFERR_WRITE_MASK : 0;
5356 /* Is it a fetch fault? */
5357 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5358 ? PFERR_FETCH_MASK : 0;
5359 /* ept page table entry is present? */
5360 error_code |= (exit_qualification &
5361 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5362 EPT_VIOLATION_EXECUTABLE))
5363 ? PFERR_PRESENT_MASK : 0;
5365 error_code |= (exit_qualification & 0x100) != 0 ?
5366 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5368 vcpu->arch.exit_qualification = exit_qualification;
5371 * Check that the GPA doesn't exceed physical memory limits, as that is
5372 * a guest page fault. We have to emulate the instruction here, because
5373 * if the illegal address is that of a paging structure, then
5374 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5375 * would also use advanced VM-exit information for EPT violations to
5376 * reconstruct the page fault error code.
5378 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5379 return kvm_emulate_instruction(vcpu, 0);
5381 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5384 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5389 * A nested guest cannot optimize MMIO vmexits, because we have an
5390 * nGPA here instead of the required GPA.
5392 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5393 if (!is_guest_mode(vcpu) &&
5394 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5395 trace_kvm_fast_mmio(gpa);
5396 return kvm_skip_emulated_instruction(vcpu);
5399 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5402 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5404 WARN_ON_ONCE(!enable_vnmi);
5405 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5406 ++vcpu->stat.nmi_window_exits;
5407 kvm_make_request(KVM_REQ_EVENT, vcpu);
5412 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5414 struct vcpu_vmx *vmx = to_vmx(vcpu);
5415 bool intr_window_requested;
5416 unsigned count = 130;
5418 intr_window_requested = exec_controls_get(vmx) &
5419 CPU_BASED_INTR_WINDOW_EXITING;
5421 while (vmx->emulation_required && count-- != 0) {
5422 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5423 return handle_interrupt_window(&vmx->vcpu);
5425 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5428 if (!kvm_emulate_instruction(vcpu, 0))
5431 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5432 vcpu->arch.exception.pending) {
5433 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5434 vcpu->run->internal.suberror =
5435 KVM_INTERNAL_ERROR_EMULATION;
5436 vcpu->run->internal.ndata = 0;
5440 if (vcpu->arch.halt_request) {
5441 vcpu->arch.halt_request = 0;
5442 return kvm_vcpu_halt(vcpu);
5446 * Note, return 1 and not 0, vcpu_run() will invoke
5447 * xfer_to_guest_mode() which will create a proper return
5450 if (__xfer_to_guest_mode_work_pending())
5457 static void grow_ple_window(struct kvm_vcpu *vcpu)
5459 struct vcpu_vmx *vmx = to_vmx(vcpu);
5460 unsigned int old = vmx->ple_window;
5462 vmx->ple_window = __grow_ple_window(old, ple_window,
5466 if (vmx->ple_window != old) {
5467 vmx->ple_window_dirty = true;
5468 trace_kvm_ple_window_update(vcpu->vcpu_id,
5469 vmx->ple_window, old);
5473 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5475 struct vcpu_vmx *vmx = to_vmx(vcpu);
5476 unsigned int old = vmx->ple_window;
5478 vmx->ple_window = __shrink_ple_window(old, ple_window,
5482 if (vmx->ple_window != old) {
5483 vmx->ple_window_dirty = true;
5484 trace_kvm_ple_window_update(vcpu->vcpu_id,
5485 vmx->ple_window, old);
5489 static void vmx_enable_tdp(void)
5491 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5492 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5493 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5494 0ull, VMX_EPT_EXECUTABLE_MASK,
5495 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5496 VMX_EPT_RWX_MASK, 0ull);
5498 ept_set_mmio_spte_mask();
5502 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5503 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5505 static int handle_pause(struct kvm_vcpu *vcpu)
5507 if (!kvm_pause_in_guest(vcpu->kvm))
5508 grow_ple_window(vcpu);
5511 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5512 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5513 * never set PAUSE_EXITING and just set PLE if supported,
5514 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5516 kvm_vcpu_on_spin(vcpu, true);
5517 return kvm_skip_emulated_instruction(vcpu);
5520 static int handle_nop(struct kvm_vcpu *vcpu)
5522 return kvm_skip_emulated_instruction(vcpu);
5525 static int handle_mwait(struct kvm_vcpu *vcpu)
5527 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5528 return handle_nop(vcpu);
5531 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5533 kvm_queue_exception(vcpu, UD_VECTOR);
5537 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5542 static int handle_monitor(struct kvm_vcpu *vcpu)
5544 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5545 return handle_nop(vcpu);
5548 static int handle_invpcid(struct kvm_vcpu *vcpu)
5550 u32 vmx_instruction_info;
5558 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5559 kvm_queue_exception(vcpu, UD_VECTOR);
5563 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5564 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5567 kvm_inject_gp(vcpu, 0);
5571 /* According to the Intel instruction reference, the memory operand
5572 * is read even if it isn't needed (e.g., for type==all)
5574 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5575 vmx_instruction_info, false,
5576 sizeof(operand), &gva))
5579 return kvm_handle_invpcid(vcpu, type, gva);
5582 static int handle_pml_full(struct kvm_vcpu *vcpu)
5584 unsigned long exit_qualification;
5586 trace_kvm_pml_full(vcpu->vcpu_id);
5588 exit_qualification = vmx_get_exit_qual(vcpu);
5591 * PML buffer FULL happened while executing iret from NMI,
5592 * "blocked by NMI" bit has to be set before next VM entry.
5594 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5596 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5597 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5598 GUEST_INTR_STATE_NMI);
5601 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5602 * here.., and there's no userspace involvement needed for PML.
5607 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5609 struct vcpu_vmx *vmx = to_vmx(vcpu);
5611 if (!vmx->req_immediate_exit &&
5612 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5613 kvm_lapic_expired_hv_timer(vcpu);
5614 return EXIT_FASTPATH_REENTER_GUEST;
5617 return EXIT_FASTPATH_NONE;
5620 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5622 handle_fastpath_preemption_timer(vcpu);
5627 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5628 * are overwritten by nested_vmx_setup() when nested=1.
5630 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5632 kvm_queue_exception(vcpu, UD_VECTOR);
5636 static int handle_encls(struct kvm_vcpu *vcpu)
5639 * SGX virtualization is not yet supported. There is no software
5640 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5641 * to prevent the guest from executing ENCLS.
5643 kvm_queue_exception(vcpu, UD_VECTOR);
5647 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
5649 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
5650 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
5655 * The exit handlers return 1 if the exit was handled fully and guest execution
5656 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5657 * to be done to userspace and return 0.
5659 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5660 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5661 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5662 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5663 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5664 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5665 [EXIT_REASON_CR_ACCESS] = handle_cr,
5666 [EXIT_REASON_DR_ACCESS] = handle_dr,
5667 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5668 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5669 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5670 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5671 [EXIT_REASON_HLT] = kvm_emulate_halt,
5672 [EXIT_REASON_INVD] = handle_invd,
5673 [EXIT_REASON_INVLPG] = handle_invlpg,
5674 [EXIT_REASON_RDPMC] = handle_rdpmc,
5675 [EXIT_REASON_VMCALL] = handle_vmcall,
5676 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5677 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5678 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5679 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5680 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5681 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5682 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5683 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5684 [EXIT_REASON_VMON] = handle_vmx_instruction,
5685 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5686 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5687 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5688 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5689 [EXIT_REASON_WBINVD] = handle_wbinvd,
5690 [EXIT_REASON_XSETBV] = handle_xsetbv,
5691 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5692 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5693 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5694 [EXIT_REASON_LDTR_TR] = handle_desc,
5695 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5696 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5697 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5698 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5699 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5700 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5701 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5702 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5703 [EXIT_REASON_RDRAND] = handle_invalid_op,
5704 [EXIT_REASON_RDSEED] = handle_invalid_op,
5705 [EXIT_REASON_PML_FULL] = handle_pml_full,
5706 [EXIT_REASON_INVPCID] = handle_invpcid,
5707 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5708 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5709 [EXIT_REASON_ENCLS] = handle_encls,
5710 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
5713 static const int kvm_vmx_max_exit_handlers =
5714 ARRAY_SIZE(kvm_vmx_exit_handlers);
5716 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2,
5717 u32 *intr_info, u32 *error_code)
5719 struct vcpu_vmx *vmx = to_vmx(vcpu);
5721 *info1 = vmx_get_exit_qual(vcpu);
5722 if (!(vmx->exit_reason.failed_vmentry)) {
5723 *info2 = vmx->idt_vectoring_info;
5724 *intr_info = vmx_get_intr_info(vcpu);
5725 if (is_exception_with_error_code(*intr_info))
5726 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5736 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5739 __free_page(vmx->pml_pg);
5744 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5746 struct vcpu_vmx *vmx = to_vmx(vcpu);
5750 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5752 /* Do nothing if PML buffer is empty */
5753 if (pml_idx == (PML_ENTITY_NUM - 1))
5756 /* PML index always points to next available PML buffer entity */
5757 if (pml_idx >= PML_ENTITY_NUM)
5762 pml_buf = page_address(vmx->pml_pg);
5763 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5766 gpa = pml_buf[pml_idx];
5767 WARN_ON(gpa & (PAGE_SIZE - 1));
5768 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5771 /* reset PML index */
5772 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5776 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5777 * Called before reporting dirty_bitmap to userspace.
5779 static void kvm_flush_pml_buffers(struct kvm *kvm)
5782 struct kvm_vcpu *vcpu;
5784 * We only need to kick vcpu out of guest mode here, as PML buffer
5785 * is flushed at beginning of all VMEXITs, and it's obvious that only
5786 * vcpus running in guest are possible to have unflushed GPAs in PML
5789 kvm_for_each_vcpu(i, vcpu, kvm)
5790 kvm_vcpu_kick(vcpu);
5793 static void vmx_dump_sel(char *name, uint32_t sel)
5795 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5796 name, vmcs_read16(sel),
5797 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5798 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5799 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5802 static void vmx_dump_dtsel(char *name, uint32_t limit)
5804 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5805 name, vmcs_read32(limit),
5806 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5809 void dump_vmcs(void)
5811 u32 vmentry_ctl, vmexit_ctl;
5812 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5816 if (!dump_invalid_vmcs) {
5817 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5821 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5822 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5823 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5824 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5825 cr4 = vmcs_readl(GUEST_CR4);
5826 efer = vmcs_read64(GUEST_IA32_EFER);
5827 secondary_exec_control = 0;
5828 if (cpu_has_secondary_exec_ctrls())
5829 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5831 pr_err("*** Guest State ***\n");
5832 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5833 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5834 vmcs_readl(CR0_GUEST_HOST_MASK));
5835 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5836 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5837 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5838 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5839 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5841 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5842 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5843 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5844 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5846 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5847 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5848 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5849 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5850 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5851 vmcs_readl(GUEST_SYSENTER_ESP),
5852 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5853 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5854 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5855 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5856 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5857 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5858 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5859 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5860 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5861 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5862 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5863 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5864 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5865 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5866 efer, vmcs_read64(GUEST_IA32_PAT));
5867 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5868 vmcs_read64(GUEST_IA32_DEBUGCTL),
5869 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5870 if (cpu_has_load_perf_global_ctrl() &&
5871 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5872 pr_err("PerfGlobCtl = 0x%016llx\n",
5873 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5874 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5875 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5876 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5877 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5878 vmcs_read32(GUEST_ACTIVITY_STATE));
5879 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5880 pr_err("InterruptStatus = %04x\n",
5881 vmcs_read16(GUEST_INTR_STATUS));
5883 pr_err("*** Host State ***\n");
5884 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5885 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5886 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5887 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5888 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5889 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5890 vmcs_read16(HOST_TR_SELECTOR));
5891 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5892 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5893 vmcs_readl(HOST_TR_BASE));
5894 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5895 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5896 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5897 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5898 vmcs_readl(HOST_CR4));
5899 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5900 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5901 vmcs_read32(HOST_IA32_SYSENTER_CS),
5902 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5903 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5904 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5905 vmcs_read64(HOST_IA32_EFER),
5906 vmcs_read64(HOST_IA32_PAT));
5907 if (cpu_has_load_perf_global_ctrl() &&
5908 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5909 pr_err("PerfGlobCtl = 0x%016llx\n",
5910 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5912 pr_err("*** Control State ***\n");
5913 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5914 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5915 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5916 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5917 vmcs_read32(EXCEPTION_BITMAP),
5918 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5919 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5920 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5921 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5922 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5923 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5924 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5925 vmcs_read32(VM_EXIT_INTR_INFO),
5926 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5927 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5928 pr_err(" reason=%08x qualification=%016lx\n",
5929 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5930 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5931 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5932 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5933 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5934 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5935 pr_err("TSC Multiplier = 0x%016llx\n",
5936 vmcs_read64(TSC_MULTIPLIER));
5937 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5938 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5939 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5940 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5942 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5943 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5944 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5945 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5947 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5948 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5949 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5950 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5951 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5952 pr_err("PLE Gap=%08x Window=%08x\n",
5953 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5954 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5955 pr_err("Virtual processor ID = 0x%04x\n",
5956 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5960 * The guest has exited. See if we can fix it or if we need userspace
5963 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
5965 struct vcpu_vmx *vmx = to_vmx(vcpu);
5966 union vmx_exit_reason exit_reason = vmx->exit_reason;
5967 u32 vectoring_info = vmx->idt_vectoring_info;
5968 u16 exit_handler_index;
5971 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5972 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5973 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5974 * mode as if vcpus is in root mode, the PML buffer must has been
5978 vmx_flush_pml_buffer(vcpu);
5981 * We should never reach this point with a pending nested VM-Enter, and
5982 * more specifically emulation of L2 due to invalid guest state (see
5983 * below) should never happen as that means we incorrectly allowed a
5984 * nested VM-Enter with an invalid vmcs12.
5986 WARN_ON_ONCE(vmx->nested.nested_run_pending);
5988 /* If guest state is invalid, start emulating */
5989 if (vmx->emulation_required)
5990 return handle_invalid_guest_state(vcpu);
5992 if (is_guest_mode(vcpu)) {
5994 * The host physical addresses of some pages of guest memory
5995 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
5996 * Page). The CPU may write to these pages via their host
5997 * physical address while L2 is running, bypassing any
5998 * address-translation-based dirty tracking (e.g. EPT write
6001 * Mark them dirty on every exit from L2 to prevent them from
6002 * getting out of sync with dirty tracking.
6004 nested_mark_vmcs12_pages_dirty(vcpu);
6006 if (nested_vmx_reflect_vmexit(vcpu))
6010 if (exit_reason.failed_vmentry) {
6012 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6013 vcpu->run->fail_entry.hardware_entry_failure_reason
6015 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6019 if (unlikely(vmx->fail)) {
6021 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6022 vcpu->run->fail_entry.hardware_entry_failure_reason
6023 = vmcs_read32(VM_INSTRUCTION_ERROR);
6024 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6030 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6031 * delivery event since it indicates guest is accessing MMIO.
6032 * The vm-exit can be triggered again after return to guest that
6033 * will cause infinite loop.
6035 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6036 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6037 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6038 exit_reason.basic != EXIT_REASON_PML_FULL &&
6039 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6040 exit_reason.basic != EXIT_REASON_TASK_SWITCH)) {
6041 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6042 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6043 vcpu->run->internal.ndata = 3;
6044 vcpu->run->internal.data[0] = vectoring_info;
6045 vcpu->run->internal.data[1] = exit_reason.full;
6046 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6047 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6048 vcpu->run->internal.ndata++;
6049 vcpu->run->internal.data[3] =
6050 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6052 vcpu->run->internal.data[vcpu->run->internal.ndata++] =
6053 vcpu->arch.last_vmentry_cpu;
6057 if (unlikely(!enable_vnmi &&
6058 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6059 if (!vmx_interrupt_blocked(vcpu)) {
6060 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6061 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6062 vcpu->arch.nmi_pending) {
6064 * This CPU don't support us in finding the end of an
6065 * NMI-blocked window if the guest runs with IRQs
6066 * disabled. So we pull the trigger after 1 s of
6067 * futile waiting, but inform the user about this.
6069 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6070 "state on VCPU %d after 1 s timeout\n",
6071 __func__, vcpu->vcpu_id);
6072 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6076 if (exit_fastpath != EXIT_FASTPATH_NONE)
6079 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6080 goto unexpected_vmexit;
6081 #ifdef CONFIG_RETPOLINE
6082 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6083 return kvm_emulate_wrmsr(vcpu);
6084 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6085 return handle_preemption_timer(vcpu);
6086 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6087 return handle_interrupt_window(vcpu);
6088 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6089 return handle_external_interrupt(vcpu);
6090 else if (exit_reason.basic == EXIT_REASON_HLT)
6091 return kvm_emulate_halt(vcpu);
6092 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6093 return handle_ept_misconfig(vcpu);
6096 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6097 kvm_vmx_max_exit_handlers);
6098 if (!kvm_vmx_exit_handlers[exit_handler_index])
6099 goto unexpected_vmexit;
6101 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6104 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6107 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6108 vcpu->run->internal.suberror =
6109 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6110 vcpu->run->internal.ndata = 2;
6111 vcpu->run->internal.data[0] = exit_reason.full;
6112 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6116 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6118 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6121 * Even when current exit reason is handled by KVM internally, we
6122 * still need to exit to user space when bus lock detected to inform
6123 * that there is a bus lock in guest.
6125 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6127 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6129 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6136 * Software based L1D cache flush which is used when microcode providing
6137 * the cache control MSR is not loaded.
6139 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6140 * flush it is required to read in 64 KiB because the replacement algorithm
6141 * is not exactly LRU. This could be sized at runtime via topology
6142 * information but as all relevant affected CPUs have 32KiB L1D cache size
6143 * there is no point in doing so.
6145 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6147 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6150 * This code is only executed when the the flush mode is 'cond' or
6153 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6157 * Clear the per-vcpu flush bit, it gets set again
6158 * either from vcpu_run() or from one of the unsafe
6161 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6162 vcpu->arch.l1tf_flush_l1d = false;
6165 * Clear the per-cpu flush bit, it gets set again from
6166 * the interrupt handlers.
6168 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6169 kvm_clear_cpu_l1tf_flush_l1d();
6175 vcpu->stat.l1d_flush++;
6177 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6178 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6183 /* First ensure the pages are in the TLB */
6184 "xorl %%eax, %%eax\n"
6185 ".Lpopulate_tlb:\n\t"
6186 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6187 "addl $4096, %%eax\n\t"
6188 "cmpl %%eax, %[size]\n\t"
6189 "jne .Lpopulate_tlb\n\t"
6190 "xorl %%eax, %%eax\n\t"
6192 /* Now fill the cache */
6193 "xorl %%eax, %%eax\n"
6195 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6196 "addl $64, %%eax\n\t"
6197 "cmpl %%eax, %[size]\n\t"
6198 "jne .Lfill_cache\n\t"
6200 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6202 : "eax", "ebx", "ecx", "edx");
6205 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6207 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6210 if (is_guest_mode(vcpu) &&
6211 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6214 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6215 if (is_guest_mode(vcpu))
6216 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6218 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6221 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6223 struct vcpu_vmx *vmx = to_vmx(vcpu);
6224 u32 sec_exec_control;
6226 if (!lapic_in_kernel(vcpu))
6229 if (!flexpriority_enabled &&
6230 !cpu_has_vmx_virtualize_x2apic_mode())
6233 /* Postpone execution until vmcs01 is the current VMCS. */
6234 if (is_guest_mode(vcpu)) {
6235 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6239 sec_exec_control = secondary_exec_controls_get(vmx);
6240 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6241 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6243 switch (kvm_get_apic_mode(vcpu)) {
6244 case LAPIC_MODE_INVALID:
6245 WARN_ONCE(true, "Invalid local APIC state");
6246 case LAPIC_MODE_DISABLED:
6248 case LAPIC_MODE_XAPIC:
6249 if (flexpriority_enabled) {
6251 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6252 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6255 * Flush the TLB, reloading the APIC access page will
6256 * only do so if its physical address has changed, but
6257 * the guest may have inserted a non-APIC mapping into
6258 * the TLB while the APIC access page was disabled.
6260 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6263 case LAPIC_MODE_X2APIC:
6264 if (cpu_has_vmx_virtualize_x2apic_mode())
6266 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6269 secondary_exec_controls_set(vmx, sec_exec_control);
6271 vmx_update_msr_bitmap(vcpu);
6274 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6278 /* Defer reload until vmcs01 is the current VMCS. */
6279 if (is_guest_mode(vcpu)) {
6280 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6284 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6285 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6288 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6289 if (is_error_page(page))
6292 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6293 vmx_flush_tlb_current(vcpu);
6296 * Do not pin apic access page in memory, the MMU notifier
6297 * will call us again if it is migrated or swapped out.
6302 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6310 status = vmcs_read16(GUEST_INTR_STATUS);
6312 if (max_isr != old) {
6314 status |= max_isr << 8;
6315 vmcs_write16(GUEST_INTR_STATUS, status);
6319 static void vmx_set_rvi(int vector)
6327 status = vmcs_read16(GUEST_INTR_STATUS);
6328 old = (u8)status & 0xff;
6329 if ((u8)vector != old) {
6331 status |= (u8)vector;
6332 vmcs_write16(GUEST_INTR_STATUS, status);
6336 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6339 * When running L2, updating RVI is only relevant when
6340 * vmcs12 virtual-interrupt-delivery enabled.
6341 * However, it can be enabled only when L1 also
6342 * intercepts external-interrupts and in that case
6343 * we should not update vmcs02 RVI but instead intercept
6344 * interrupt. Therefore, do nothing when running L2.
6346 if (!is_guest_mode(vcpu))
6347 vmx_set_rvi(max_irr);
6350 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6352 struct vcpu_vmx *vmx = to_vmx(vcpu);
6354 bool max_irr_updated;
6356 WARN_ON(!vcpu->arch.apicv_active);
6357 if (pi_test_on(&vmx->pi_desc)) {
6358 pi_clear_on(&vmx->pi_desc);
6360 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6361 * But on x86 this is just a compiler barrier anyway.
6363 smp_mb__after_atomic();
6365 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6368 * If we are running L2 and L1 has a new pending interrupt
6369 * which can be injected, we should re-evaluate
6370 * what should be done with this new L1 interrupt.
6371 * If L1 intercepts external-interrupts, we should
6372 * exit from L2 to L1. Otherwise, interrupt should be
6373 * delivered directly to L2.
6375 if (is_guest_mode(vcpu) && max_irr_updated) {
6376 if (nested_exit_on_intr(vcpu))
6377 kvm_vcpu_exiting_guest_mode(vcpu);
6379 kvm_make_request(KVM_REQ_EVENT, vcpu);
6382 max_irr = kvm_lapic_find_highest_irr(vcpu);
6384 vmx_hwapic_irr_update(vcpu, max_irr);
6388 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6390 if (!kvm_vcpu_apicv_active(vcpu))
6393 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6394 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6395 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6396 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6399 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6401 struct vcpu_vmx *vmx = to_vmx(vcpu);
6403 pi_clear_on(&vmx->pi_desc);
6404 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6407 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6409 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu, u32 intr_info)
6411 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6412 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6414 kvm_before_interrupt(vcpu);
6415 vmx_do_interrupt_nmi_irqoff(gate_offset(desc));
6416 kvm_after_interrupt(vcpu);
6419 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6421 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6423 /* if exit due to PF check for async PF */
6424 if (is_page_fault(intr_info))
6425 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6426 /* Handle machine checks before interrupts are enabled */
6427 else if (is_machine_check(intr_info))
6428 kvm_machine_check();
6429 /* We need to handle NMIs before interrupts are enabled */
6430 else if (is_nmi(intr_info))
6431 handle_interrupt_nmi_irqoff(&vmx->vcpu, intr_info);
6434 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6436 u32 intr_info = vmx_get_intr_info(vcpu);
6438 if (WARN_ONCE(!is_external_intr(intr_info),
6439 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6442 handle_interrupt_nmi_irqoff(vcpu, intr_info);
6445 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6447 struct vcpu_vmx *vmx = to_vmx(vcpu);
6449 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6450 handle_external_interrupt_irqoff(vcpu);
6451 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
6452 handle_exception_nmi_irqoff(vmx);
6456 * The kvm parameter can be NULL (module initialization, or invocation before
6457 * VM creation). Be sure to check the kvm parameter before using it.
6459 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
6462 case MSR_IA32_SMBASE:
6464 * We cannot do SMM unless we can run the guest in big
6467 return enable_unrestricted_guest || emulate_invalid_guest_state;
6468 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6470 case MSR_AMD64_VIRT_SPEC_CTRL:
6471 /* This is AMD only. */
6478 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6483 bool idtv_info_valid;
6485 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6488 if (vmx->loaded_vmcs->nmi_known_unmasked)
6491 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6492 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6493 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6495 * SDM 3: 27.7.1.2 (September 2008)
6496 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6497 * a guest IRET fault.
6498 * SDM 3: 23.2.2 (September 2008)
6499 * Bit 12 is undefined in any of the following cases:
6500 * If the VM exit sets the valid bit in the IDT-vectoring
6501 * information field.
6502 * If the VM exit is due to a double fault.
6504 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6505 vector != DF_VECTOR && !idtv_info_valid)
6506 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6507 GUEST_INTR_STATE_NMI);
6509 vmx->loaded_vmcs->nmi_known_unmasked =
6510 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6511 & GUEST_INTR_STATE_NMI);
6512 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6513 vmx->loaded_vmcs->vnmi_blocked_time +=
6514 ktime_to_ns(ktime_sub(ktime_get(),
6515 vmx->loaded_vmcs->entry_time));
6518 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6519 u32 idt_vectoring_info,
6520 int instr_len_field,
6521 int error_code_field)
6525 bool idtv_info_valid;
6527 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6529 vcpu->arch.nmi_injected = false;
6530 kvm_clear_exception_queue(vcpu);
6531 kvm_clear_interrupt_queue(vcpu);
6533 if (!idtv_info_valid)
6536 kvm_make_request(KVM_REQ_EVENT, vcpu);
6538 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6539 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6542 case INTR_TYPE_NMI_INTR:
6543 vcpu->arch.nmi_injected = true;
6545 * SDM 3: 27.7.1.2 (September 2008)
6546 * Clear bit "block by NMI" before VM entry if a NMI
6549 vmx_set_nmi_mask(vcpu, false);
6551 case INTR_TYPE_SOFT_EXCEPTION:
6552 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6554 case INTR_TYPE_HARD_EXCEPTION:
6555 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6556 u32 err = vmcs_read32(error_code_field);
6557 kvm_requeue_exception_e(vcpu, vector, err);
6559 kvm_requeue_exception(vcpu, vector);
6561 case INTR_TYPE_SOFT_INTR:
6562 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6564 case INTR_TYPE_EXT_INTR:
6565 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6572 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6574 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6575 VM_EXIT_INSTRUCTION_LEN,
6576 IDT_VECTORING_ERROR_CODE);
6579 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6581 __vmx_complete_interrupts(vcpu,
6582 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6583 VM_ENTRY_INSTRUCTION_LEN,
6584 VM_ENTRY_EXCEPTION_ERROR_CODE);
6586 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6589 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6592 struct perf_guest_switch_msr *msrs;
6594 msrs = perf_guest_get_msrs(&nr_msrs);
6599 for (i = 0; i < nr_msrs; i++)
6600 if (msrs[i].host == msrs[i].guest)
6601 clear_atomic_switch_msr(vmx, msrs[i].msr);
6603 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6604 msrs[i].host, false);
6607 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6609 struct vcpu_vmx *vmx = to_vmx(vcpu);
6613 if (vmx->req_immediate_exit) {
6614 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6615 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6616 } else if (vmx->hv_deadline_tsc != -1) {
6618 if (vmx->hv_deadline_tsc > tscl)
6619 /* set_hv_timer ensures the delta fits in 32-bits */
6620 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6621 cpu_preemption_timer_multi);
6625 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6626 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6627 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6628 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6629 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6633 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6635 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6636 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6637 vmcs_writel(HOST_RSP, host_rsp);
6641 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6643 switch (to_vmx(vcpu)->exit_reason.basic) {
6644 case EXIT_REASON_MSR_WRITE:
6645 return handle_fastpath_set_msr_irqoff(vcpu);
6646 case EXIT_REASON_PREEMPTION_TIMER:
6647 return handle_fastpath_preemption_timer(vcpu);
6649 return EXIT_FASTPATH_NONE;
6653 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6654 struct vcpu_vmx *vmx)
6657 * VMENTER enables interrupts (host state), but the kernel state is
6658 * interrupts disabled when this is invoked. Also tell RCU about
6659 * it. This is the same logic as for exit_to_user_mode().
6661 * This ensures that e.g. latency analysis on the host observes
6662 * guest mode as interrupt enabled.
6664 * guest_enter_irqoff() informs context tracking about the
6665 * transition to guest mode and if enabled adjusts RCU state
6668 instrumentation_begin();
6669 trace_hardirqs_on_prepare();
6670 lockdep_hardirqs_on_prepare(CALLER_ADDR0);
6671 instrumentation_end();
6673 guest_enter_irqoff();
6674 lockdep_hardirqs_on(CALLER_ADDR0);
6676 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6677 if (static_branch_unlikely(&vmx_l1d_should_flush))
6678 vmx_l1d_flush(vcpu);
6679 else if (static_branch_unlikely(&mds_user_clear))
6680 mds_clear_cpu_buffers();
6682 if (vcpu->arch.cr2 != native_read_cr2())
6683 native_write_cr2(vcpu->arch.cr2);
6685 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6686 vmx->loaded_vmcs->launched);
6688 vcpu->arch.cr2 = native_read_cr2();
6691 * VMEXIT disables interrupts (host state), but tracing and lockdep
6692 * have them in state 'on' as recorded before entering guest mode.
6693 * Same as enter_from_user_mode().
6695 * guest_exit_irqoff() restores host context and reinstates RCU if
6696 * enabled and required.
6698 * This needs to be done before the below as native_read_msr()
6699 * contains a tracepoint and x86_spec_ctrl_restore_host() calls
6700 * into world and some more.
6702 lockdep_hardirqs_off(CALLER_ADDR0);
6703 guest_exit_irqoff();
6705 instrumentation_begin();
6706 trace_hardirqs_off_finish();
6707 instrumentation_end();
6710 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6712 struct vcpu_vmx *vmx = to_vmx(vcpu);
6713 unsigned long cr3, cr4;
6715 /* Record the guest's net vcpu time for enforced NMI injections. */
6716 if (unlikely(!enable_vnmi &&
6717 vmx->loaded_vmcs->soft_vnmi_blocked))
6718 vmx->loaded_vmcs->entry_time = ktime_get();
6720 /* Don't enter VMX if guest state is invalid, let the exit handler
6721 start emulation until we arrive back to a valid state */
6722 if (vmx->emulation_required)
6723 return EXIT_FASTPATH_NONE;
6725 trace_kvm_entry(vcpu);
6727 if (vmx->ple_window_dirty) {
6728 vmx->ple_window_dirty = false;
6729 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6733 * We did this in prepare_switch_to_guest, because it needs to
6734 * be within srcu_read_lock.
6736 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6738 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6739 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6740 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6741 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6743 cr3 = __get_current_cr3_fast();
6744 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6745 vmcs_writel(HOST_CR3, cr3);
6746 vmx->loaded_vmcs->host_state.cr3 = cr3;
6749 cr4 = cr4_read_shadow();
6750 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6751 vmcs_writel(HOST_CR4, cr4);
6752 vmx->loaded_vmcs->host_state.cr4 = cr4;
6755 /* When single-stepping over STI and MOV SS, we must clear the
6756 * corresponding interruptibility bits in the guest state. Otherwise
6757 * vmentry fails as it then expects bit 14 (BS) in pending debug
6758 * exceptions being set, but that's not correct for the guest debugging
6760 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6761 vmx_set_interrupt_shadow(vcpu, 0);
6763 kvm_load_guest_xsave_state(vcpu);
6765 pt_guest_enter(vmx);
6767 atomic_switch_perf_msrs(vmx);
6768 if (intel_pmu_lbr_is_enabled(vcpu))
6769 vmx_passthrough_lbr_msrs(vcpu);
6771 if (enable_preemption_timer)
6772 vmx_update_hv_timer(vcpu);
6774 kvm_wait_lapic_expire(vcpu);
6777 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6778 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6779 * is no need to worry about the conditional branch over the wrmsr
6780 * being speculatively taken.
6782 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6784 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6785 vmx_vcpu_enter_exit(vcpu, vmx);
6788 * We do not use IBRS in the kernel. If this vCPU has used the
6789 * SPEC_CTRL MSR it may have left it on; save the value and
6790 * turn it off. This is much more efficient than blindly adding
6791 * it to the atomic save/restore list. Especially as the former
6792 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6794 * For non-nested case:
6795 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6799 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6802 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6803 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6805 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6807 /* All fields are clean at this point */
6808 if (static_branch_unlikely(&enable_evmcs))
6809 current_evmcs->hv_clean_fields |=
6810 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6812 if (static_branch_unlikely(&enable_evmcs))
6813 current_evmcs->hv_vp_id = vcpu->arch.hyperv.vp_index;
6815 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6816 if (vmx->host_debugctlmsr)
6817 update_debugctlmsr(vmx->host_debugctlmsr);
6819 #ifndef CONFIG_X86_64
6821 * The sysexit path does not restore ds/es, so we must set them to
6822 * a reasonable value ourselves.
6824 * We can't defer this to vmx_prepare_switch_to_host() since that
6825 * function may be executed in interrupt context, which saves and
6826 * restore segments around it, nullifying its effect.
6828 loadsegment(ds, __USER_DS);
6829 loadsegment(es, __USER_DS);
6832 vmx_register_cache_reset(vcpu);
6836 kvm_load_host_xsave_state(vcpu);
6838 vmx->nested.nested_run_pending = 0;
6839 vmx->idt_vectoring_info = 0;
6841 if (unlikely(vmx->fail)) {
6842 vmx->exit_reason.full = 0xdead;
6843 return EXIT_FASTPATH_NONE;
6846 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
6847 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
6848 kvm_machine_check();
6850 trace_kvm_exit(vmx->exit_reason.full, vcpu, KVM_ISA_VMX);
6852 if (unlikely(vmx->exit_reason.failed_vmentry))
6853 return EXIT_FASTPATH_NONE;
6855 vmx->loaded_vmcs->launched = 1;
6856 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6858 vmx_recover_nmi_blocking(vmx);
6859 vmx_complete_interrupts(vmx);
6861 if (is_guest_mode(vcpu))
6862 return EXIT_FASTPATH_NONE;
6864 return vmx_exit_handlers_fastpath(vcpu);
6867 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6869 struct vcpu_vmx *vmx = to_vmx(vcpu);
6872 vmx_destroy_pml_buffer(vmx);
6873 free_vpid(vmx->vpid);
6874 nested_vmx_free_vcpu(vcpu);
6875 free_loaded_vmcs(vmx->loaded_vmcs);
6878 static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
6880 struct vcpu_vmx *vmx;
6883 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6888 vmx->vpid = allocate_vpid();
6891 * If PML is turned on, failure on enabling PML just results in failure
6892 * of creating the vcpu, therefore we can simplify PML logic (by
6893 * avoiding dealing with cases, such as enabling PML partially on vcpus
6894 * for the guest), etc.
6897 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6902 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
6904 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i) {
6905 u32 index = vmx_uret_msrs_list[i];
6906 u32 data_low, data_high;
6907 int j = vmx->nr_uret_msrs;
6909 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6911 if (wrmsr_safe(index, data_low, data_high) < 0)
6914 vmx->guest_uret_msrs[j].slot = i;
6915 vmx->guest_uret_msrs[j].data = 0;
6917 case MSR_IA32_TSX_CTRL:
6919 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID
6920 * interception. Keep the host value unchanged to avoid
6921 * changing CPUID bits under the host kernel's feet.
6923 * hle=0, rtm=0, tsx_ctrl=1 can be found with some
6924 * combinations of new kernel and old userspace. If
6925 * those guests run on a tsx=off host, do allow guests
6926 * to use TSX_CTRL, but do not change the value on the
6927 * host so that TSX remains always disabled.
6929 if (boot_cpu_has(X86_FEATURE_RTM))
6930 vmx->guest_uret_msrs[j].mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6932 vmx->guest_uret_msrs[j].mask = 0;
6935 vmx->guest_uret_msrs[j].mask = -1ull;
6938 ++vmx->nr_uret_msrs;
6941 err = alloc_loaded_vmcs(&vmx->vmcs01);
6945 /* The MSR bitmap starts with all ones */
6946 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6947 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6949 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
6950 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
6951 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
6952 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6953 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6954 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6955 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6956 if (kvm_cstate_in_guest(vcpu->kvm)) {
6957 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
6958 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6959 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6960 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6962 vmx->msr_bitmap_mode = 0;
6964 vmx->loaded_vmcs = &vmx->vmcs01;
6966 vmx_vcpu_load(vcpu, cpu);
6971 if (cpu_need_virtualize_apic_accesses(vcpu)) {
6972 err = alloc_apic_access_page(vcpu->kvm);
6977 if (enable_ept && !enable_unrestricted_guest) {
6978 err = init_rmode_identity_map(vcpu->kvm);
6984 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
6986 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6988 vmx->nested.posted_intr_nv = -1;
6989 vmx->nested.current_vmptr = -1ull;
6991 vcpu->arch.microcode_version = 0x100000000ULL;
6992 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
6995 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6996 * or POSTED_INTR_WAKEUP_VECTOR.
6998 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6999 vmx->pi_desc.sn = 1;
7001 vmx->ept_pointer = INVALID_PAGE;
7006 free_loaded_vmcs(vmx->loaded_vmcs);
7008 vmx_destroy_pml_buffer(vmx);
7010 free_vpid(vmx->vpid);
7014 #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"
7015 #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"
7017 static int vmx_vm_init(struct kvm *kvm)
7019 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
7022 kvm->arch.pause_in_guest = true;
7024 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7025 switch (l1tf_mitigation) {
7026 case L1TF_MITIGATION_OFF:
7027 case L1TF_MITIGATION_FLUSH_NOWARN:
7028 /* 'I explicitly don't care' is set */
7030 case L1TF_MITIGATION_FLUSH:
7031 case L1TF_MITIGATION_FLUSH_NOSMT:
7032 case L1TF_MITIGATION_FULL:
7034 * Warn upon starting the first VM in a potentially
7035 * insecure environment.
7037 if (sched_smt_active())
7038 pr_warn_once(L1TF_MSG_SMT);
7039 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7040 pr_warn_once(L1TF_MSG_L1D);
7042 case L1TF_MITIGATION_FULL_FORCE:
7043 /* Flush is enforced */
7047 kvm_apicv_init(kvm, enable_apicv);
7051 static int __init vmx_check_processor_compat(void)
7053 struct vmcs_config vmcs_conf;
7054 struct vmx_capability vmx_cap;
7056 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7057 !this_cpu_has(X86_FEATURE_VMX)) {
7058 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7062 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7065 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
7066 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7067 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7068 smp_processor_id());
7074 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7079 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7080 * memory aliases with conflicting memory types and sometimes MCEs.
7081 * We have to be careful as to what are honored and when.
7083 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7084 * UC. The effective memory type is UC or WC depending on guest PAT.
7085 * This was historically the source of MCEs and we want to be
7088 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7089 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7090 * EPT memory type is set to WB. The effective memory type is forced
7093 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7094 * EPT memory type is used to emulate guest CD/MTRR.
7098 cache = MTRR_TYPE_UNCACHABLE;
7102 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7103 ipat = VMX_EPT_IPAT_BIT;
7104 cache = MTRR_TYPE_WRBACK;
7108 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7109 ipat = VMX_EPT_IPAT_BIT;
7110 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7111 cache = MTRR_TYPE_WRBACK;
7113 cache = MTRR_TYPE_UNCACHABLE;
7117 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
7120 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7123 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
7126 * These bits in the secondary execution controls field
7127 * are dynamic, the others are mostly based on the hypervisor
7128 * architecture and the guest's CPUID. Do not touch the
7132 SECONDARY_EXEC_SHADOW_VMCS |
7133 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7134 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7135 SECONDARY_EXEC_DESC;
7137 u32 new_ctl = vmx->secondary_exec_control;
7138 u32 cur_ctl = secondary_exec_controls_get(vmx);
7140 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7144 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7145 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7147 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7149 struct vcpu_vmx *vmx = to_vmx(vcpu);
7150 struct kvm_cpuid_entry2 *entry;
7152 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7153 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7155 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7156 if (entry && (entry->_reg & (_cpuid_mask))) \
7157 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7160 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7161 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7162 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7163 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7164 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7165 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7166 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7167 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7168 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7169 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7170 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7171 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7172 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7173 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7174 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7176 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7177 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7178 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7179 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7180 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7181 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7182 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7184 #undef cr4_fixed1_update
7187 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7189 struct vcpu_vmx *vmx = to_vmx(vcpu);
7191 if (kvm_mpx_supported()) {
7192 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7195 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7196 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7198 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7199 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7204 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7206 struct vcpu_vmx *vmx = to_vmx(vcpu);
7207 struct kvm_cpuid_entry2 *best = NULL;
7210 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7211 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7214 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7215 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7216 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7217 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7220 /* Get the number of configurable Address Ranges for filtering */
7221 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7222 PT_CAP_num_address_ranges);
7224 /* Initialize and clear the no dependency bits */
7225 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7226 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7229 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7230 * will inject an #GP
7232 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7233 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7236 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7237 * PSBFreq can be set
7239 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7240 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7241 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7244 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7245 * MTCFreq can be set
7247 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7248 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7249 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7251 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7252 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7253 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7256 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7257 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7258 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7260 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7261 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7262 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7264 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
7265 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7266 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7268 /* unmask address range configure area */
7269 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7270 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7273 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7275 struct vcpu_vmx *vmx = to_vmx(vcpu);
7277 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7278 vcpu->arch.xsaves_enabled = false;
7280 if (cpu_has_secondary_exec_ctrls()) {
7281 vmx_compute_secondary_exec_control(vmx);
7282 vmcs_set_secondary_exec_control(vmx);
7285 if (nested_vmx_allowed(vcpu))
7286 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7287 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7288 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7290 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7291 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7292 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7294 if (nested_vmx_allowed(vcpu)) {
7295 nested_vmx_cr_fixed1_bits_update(vcpu);
7296 nested_vmx_entry_exit_ctls_update(vcpu);
7299 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7300 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7301 update_intel_pt_cfg(vcpu);
7303 if (boot_cpu_has(X86_FEATURE_RTM)) {
7304 struct vmx_uret_msr *msr;
7305 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7307 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7308 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7312 set_cr4_guest_host_mask(vmx);
7314 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7315 vmx_update_exception_bitmap(vcpu);
7318 static __init void vmx_set_cpu_caps(void)
7324 kvm_cpu_cap_set(X86_FEATURE_VMX);
7327 if (kvm_mpx_supported())
7328 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7329 if (cpu_has_vmx_invpcid())
7330 kvm_cpu_cap_check_and_set(X86_FEATURE_INVPCID);
7331 if (vmx_pt_mode_is_host_guest())
7332 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7334 if (vmx_umip_emulated())
7335 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7339 if (!cpu_has_vmx_xsaves())
7340 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7342 /* CPUID 0x80000001 */
7343 if (!cpu_has_vmx_rdtscp())
7344 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7346 if (cpu_has_vmx_waitpkg())
7347 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7350 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7352 to_vmx(vcpu)->req_immediate_exit = true;
7355 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7356 struct x86_instruction_info *info)
7358 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7359 unsigned short port;
7363 if (info->intercept == x86_intercept_in ||
7364 info->intercept == x86_intercept_ins) {
7365 port = info->src_val;
7366 size = info->dst_bytes;
7368 port = info->dst_val;
7369 size = info->src_bytes;
7373 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7374 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7377 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7379 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7380 intercept = nested_cpu_has(vmcs12,
7381 CPU_BASED_UNCOND_IO_EXITING);
7383 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7385 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7386 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7389 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7390 struct x86_instruction_info *info,
7391 enum x86_intercept_stage stage,
7392 struct x86_exception *exception)
7394 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7396 switch (info->intercept) {
7398 * RDPID causes #UD if disabled through secondary execution controls.
7399 * Because it is marked as EmulateOnUD, we need to intercept it here.
7401 case x86_intercept_rdtscp:
7402 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7403 exception->vector = UD_VECTOR;
7404 exception->error_code_valid = false;
7405 return X86EMUL_PROPAGATE_FAULT;
7409 case x86_intercept_in:
7410 case x86_intercept_ins:
7411 case x86_intercept_out:
7412 case x86_intercept_outs:
7413 return vmx_check_intercept_io(vcpu, info);
7415 case x86_intercept_lgdt:
7416 case x86_intercept_lidt:
7417 case x86_intercept_lldt:
7418 case x86_intercept_ltr:
7419 case x86_intercept_sgdt:
7420 case x86_intercept_sidt:
7421 case x86_intercept_sldt:
7422 case x86_intercept_str:
7423 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7424 return X86EMUL_CONTINUE;
7426 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7429 /* TODO: check more intercepts... */
7434 return X86EMUL_UNHANDLEABLE;
7437 #ifdef CONFIG_X86_64
7438 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7439 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7440 u64 divisor, u64 *result)
7442 u64 low = a << shift, high = a >> (64 - shift);
7444 /* To avoid the overflow on divq */
7445 if (high >= divisor)
7448 /* Low hold the result, high hold rem which is discarded */
7449 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7450 "rm" (divisor), "0" (low), "1" (high));
7456 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7459 struct vcpu_vmx *vmx;
7460 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7461 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7465 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7466 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7467 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7468 ktimer->timer_advance_ns);
7470 if (delta_tsc > lapic_timer_advance_cycles)
7471 delta_tsc -= lapic_timer_advance_cycles;
7475 /* Convert to host delta tsc if tsc scaling is enabled */
7476 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7477 delta_tsc && u64_shl_div_u64(delta_tsc,
7478 kvm_tsc_scaling_ratio_frac_bits,
7479 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7483 * If the delta tsc can't fit in the 32 bit after the multi shift,
7484 * we can't use the preemption timer.
7485 * It's possible that it fits on later vmentries, but checking
7486 * on every vmentry is costly so we just use an hrtimer.
7488 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7491 vmx->hv_deadline_tsc = tscl + delta_tsc;
7492 *expired = !delta_tsc;
7496 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7498 to_vmx(vcpu)->hv_deadline_tsc = -1;
7502 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7504 if (!kvm_pause_in_guest(vcpu->kvm))
7505 shrink_ple_window(vcpu);
7508 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7509 struct kvm_memory_slot *slot)
7511 if (!kvm_dirty_log_manual_protect_and_init_set(kvm))
7512 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7513 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7516 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7517 struct kvm_memory_slot *slot)
7519 kvm_mmu_slot_set_dirty(kvm, slot);
7522 static void vmx_flush_log_dirty(struct kvm *kvm)
7524 kvm_flush_pml_buffers(kvm);
7527 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7528 struct kvm_memory_slot *memslot,
7529 gfn_t offset, unsigned long mask)
7531 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7534 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7536 if (pi_pre_block(vcpu))
7539 if (kvm_lapic_hv_timer_in_use(vcpu))
7540 kvm_lapic_switch_to_sw_timer(vcpu);
7545 static void vmx_post_block(struct kvm_vcpu *vcpu)
7547 if (kvm_x86_ops.set_hv_timer)
7548 kvm_lapic_switch_to_hv_timer(vcpu);
7550 pi_post_block(vcpu);
7553 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7555 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7556 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7557 FEAT_CTL_LMCE_ENABLED;
7559 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7560 ~FEAT_CTL_LMCE_ENABLED;
7563 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7565 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7566 if (to_vmx(vcpu)->nested.nested_run_pending)
7568 return !is_smm(vcpu);
7571 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7573 struct vcpu_vmx *vmx = to_vmx(vcpu);
7575 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7576 if (vmx->nested.smm.guest_mode)
7577 nested_vmx_vmexit(vcpu, -1, 0, 0);
7579 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7580 vmx->nested.vmxon = false;
7581 vmx_clear_hlt(vcpu);
7585 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7587 struct vcpu_vmx *vmx = to_vmx(vcpu);
7590 if (vmx->nested.smm.vmxon) {
7591 vmx->nested.vmxon = true;
7592 vmx->nested.smm.vmxon = false;
7595 if (vmx->nested.smm.guest_mode) {
7596 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7600 vmx->nested.smm.guest_mode = false;
7605 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
7607 /* RSM will cause a vmexit anyway. */
7610 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7612 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
7615 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7617 if (is_guest_mode(vcpu)) {
7618 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7620 if (hrtimer_try_to_cancel(timer) == 1)
7621 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7625 static void hardware_unsetup(void)
7628 nested_vmx_hardware_unsetup();
7633 static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7635 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7636 BIT(APICV_INHIBIT_REASON_HYPERV);
7638 return supported & BIT(bit);
7641 static int vmx_cpu_dirty_log_size(void)
7643 return enable_pml ? PML_ENTITY_NUM : 0;
7646 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7647 .hardware_unsetup = hardware_unsetup,
7649 .hardware_enable = hardware_enable,
7650 .hardware_disable = hardware_disable,
7651 .cpu_has_accelerated_tpr = report_flexpriority,
7652 .has_emulated_msr = vmx_has_emulated_msr,
7654 .vm_size = sizeof(struct kvm_vmx),
7655 .vm_init = vmx_vm_init,
7657 .vcpu_create = vmx_create_vcpu,
7658 .vcpu_free = vmx_free_vcpu,
7659 .vcpu_reset = vmx_vcpu_reset,
7661 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7662 .vcpu_load = vmx_vcpu_load,
7663 .vcpu_put = vmx_vcpu_put,
7665 .update_exception_bitmap = vmx_update_exception_bitmap,
7666 .get_msr_feature = vmx_get_msr_feature,
7667 .get_msr = vmx_get_msr,
7668 .set_msr = vmx_set_msr,
7669 .get_segment_base = vmx_get_segment_base,
7670 .get_segment = vmx_get_segment,
7671 .set_segment = vmx_set_segment,
7672 .get_cpl = vmx_get_cpl,
7673 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7674 .set_cr0 = vmx_set_cr0,
7675 .is_valid_cr4 = vmx_is_valid_cr4,
7676 .set_cr4 = vmx_set_cr4,
7677 .set_efer = vmx_set_efer,
7678 .get_idt = vmx_get_idt,
7679 .set_idt = vmx_set_idt,
7680 .get_gdt = vmx_get_gdt,
7681 .set_gdt = vmx_set_gdt,
7682 .set_dr7 = vmx_set_dr7,
7683 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7684 .cache_reg = vmx_cache_reg,
7685 .get_rflags = vmx_get_rflags,
7686 .set_rflags = vmx_set_rflags,
7688 .tlb_flush_all = vmx_flush_tlb_all,
7689 .tlb_flush_current = vmx_flush_tlb_current,
7690 .tlb_flush_gva = vmx_flush_tlb_gva,
7691 .tlb_flush_guest = vmx_flush_tlb_guest,
7693 .run = vmx_vcpu_run,
7694 .handle_exit = vmx_handle_exit,
7695 .skip_emulated_instruction = vmx_skip_emulated_instruction,
7696 .update_emulated_instruction = vmx_update_emulated_instruction,
7697 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7698 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7699 .patch_hypercall = vmx_patch_hypercall,
7700 .set_irq = vmx_inject_irq,
7701 .set_nmi = vmx_inject_nmi,
7702 .queue_exception = vmx_queue_exception,
7703 .cancel_injection = vmx_cancel_injection,
7704 .interrupt_allowed = vmx_interrupt_allowed,
7705 .nmi_allowed = vmx_nmi_allowed,
7706 .get_nmi_mask = vmx_get_nmi_mask,
7707 .set_nmi_mask = vmx_set_nmi_mask,
7708 .enable_nmi_window = vmx_enable_nmi_window,
7709 .enable_irq_window = vmx_enable_irq_window,
7710 .update_cr8_intercept = vmx_update_cr8_intercept,
7711 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7712 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7713 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7714 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7715 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7716 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7717 .hwapic_irr_update = vmx_hwapic_irr_update,
7718 .hwapic_isr_update = vmx_hwapic_isr_update,
7719 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7720 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7721 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7722 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
7724 .set_tss_addr = vmx_set_tss_addr,
7725 .set_identity_map_addr = vmx_set_identity_map_addr,
7726 .get_mt_mask = vmx_get_mt_mask,
7728 .get_exit_info = vmx_get_exit_info,
7730 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
7732 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7734 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7736 .load_mmu_pgd = vmx_load_mmu_pgd,
7738 .check_intercept = vmx_check_intercept,
7739 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7741 .request_immediate_exit = vmx_request_immediate_exit,
7743 .sched_in = vmx_sched_in,
7745 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7746 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7747 .flush_log_dirty = vmx_flush_log_dirty,
7748 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7750 .pre_block = vmx_pre_block,
7751 .post_block = vmx_post_block,
7753 .pmu_ops = &intel_pmu_ops,
7754 .nested_ops = &vmx_nested_ops,
7756 .update_pi_irte = pi_update_irte,
7758 #ifdef CONFIG_X86_64
7759 .set_hv_timer = vmx_set_hv_timer,
7760 .cancel_hv_timer = vmx_cancel_hv_timer,
7763 .setup_mce = vmx_setup_mce,
7765 .smi_allowed = vmx_smi_allowed,
7766 .pre_enter_smm = vmx_pre_enter_smm,
7767 .pre_leave_smm = vmx_pre_leave_smm,
7768 .enable_smi_window = vmx_enable_smi_window,
7770 .can_emulate_instruction = vmx_can_emulate_instruction,
7771 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7772 .migrate_timers = vmx_migrate_timers,
7774 .msr_filter_changed = vmx_msr_filter_changed,
7775 .complete_emulated_msr = kvm_complete_insn_gp,
7776 .cpu_dirty_log_size = vmx_cpu_dirty_log_size,
7778 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
7781 static __init int hardware_setup(void)
7783 unsigned long host_bndcfgs;
7785 int r, i, ept_lpage_level;
7788 host_idt_base = dt.address;
7790 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
7791 kvm_define_user_return_msr(i, vmx_uret_msrs_list[i]);
7793 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7796 if (boot_cpu_has(X86_FEATURE_NX))
7797 kvm_enable_efer_bits(EFER_NX);
7799 if (boot_cpu_has(X86_FEATURE_MPX)) {
7800 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7801 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7804 if (!cpu_has_vmx_mpx())
7805 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
7806 XFEATURE_MASK_BNDCSR);
7808 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7809 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7812 if (!cpu_has_vmx_ept() ||
7813 !cpu_has_vmx_ept_4levels() ||
7814 !cpu_has_vmx_ept_mt_wb() ||
7815 !cpu_has_vmx_invept_global())
7818 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7819 enable_ept_ad_bits = 0;
7821 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7822 enable_unrestricted_guest = 0;
7824 if (!cpu_has_vmx_flexpriority())
7825 flexpriority_enabled = 0;
7827 if (!cpu_has_virtual_nmis())
7831 * set_apic_access_page_addr() is used to reload apic access
7832 * page upon invalidation. No need to do anything if not
7833 * using the APIC_ACCESS_ADDR VMCS field.
7835 if (!flexpriority_enabled)
7836 vmx_x86_ops.set_apic_access_page_addr = NULL;
7838 if (!cpu_has_vmx_tpr_shadow())
7839 vmx_x86_ops.update_cr8_intercept = NULL;
7841 #if IS_ENABLED(CONFIG_HYPERV)
7842 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7844 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
7845 vmx_x86_ops.tlb_remote_flush_with_range =
7846 hv_remote_flush_tlb_with_range;
7850 if (!cpu_has_vmx_ple()) {
7853 ple_window_grow = 0;
7855 ple_window_shrink = 0;
7858 if (!cpu_has_vmx_apicv()) {
7860 vmx_x86_ops.sync_pir_to_irr = NULL;
7863 if (cpu_has_vmx_tsc_scaling()) {
7864 kvm_has_tsc_control = true;
7865 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7866 kvm_tsc_scaling_ratio_frac_bits = 48;
7869 kvm_has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
7871 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7877 ept_lpage_level = 0;
7878 else if (cpu_has_vmx_ept_1g_page())
7879 ept_lpage_level = PG_LEVEL_1G;
7880 else if (cpu_has_vmx_ept_2m_page())
7881 ept_lpage_level = PG_LEVEL_2M;
7883 ept_lpage_level = PG_LEVEL_4K;
7884 kvm_configure_mmu(enable_ept, vmx_get_max_tdp_level(), ept_lpage_level);
7887 * Only enable PML when hardware supports PML feature, and both EPT
7888 * and EPT A/D bit features are enabled -- PML depends on them to work.
7890 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7894 vmx_x86_ops.slot_enable_log_dirty = NULL;
7895 vmx_x86_ops.slot_disable_log_dirty = NULL;
7896 vmx_x86_ops.flush_log_dirty = NULL;
7897 vmx_x86_ops.enable_log_dirty_pt_masked = NULL;
7898 vmx_x86_ops.cpu_dirty_log_size = NULL;
7901 if (!cpu_has_vmx_preemption_timer())
7902 enable_preemption_timer = false;
7904 if (enable_preemption_timer) {
7905 u64 use_timer_freq = 5000ULL * 1000 * 1000;
7908 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7909 cpu_preemption_timer_multi =
7910 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7913 use_timer_freq = (u64)tsc_khz * 1000;
7914 use_timer_freq >>= cpu_preemption_timer_multi;
7917 * KVM "disables" the preemption timer by setting it to its max
7918 * value. Don't use the timer if it might cause spurious exits
7919 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
7921 if (use_timer_freq > 0xffffffffu / 10)
7922 enable_preemption_timer = false;
7925 if (!enable_preemption_timer) {
7926 vmx_x86_ops.set_hv_timer = NULL;
7927 vmx_x86_ops.cancel_hv_timer = NULL;
7928 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
7931 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
7933 kvm_mce_cap_supported |= MCG_LMCE_P;
7935 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7937 if (!enable_ept || !cpu_has_vmx_intel_pt())
7938 pt_mode = PT_MODE_SYSTEM;
7941 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7942 vmx_capability.ept);
7944 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7951 r = alloc_kvm_area();
7953 nested_vmx_hardware_unsetup();
7957 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
7958 .cpu_has_kvm_support = cpu_has_kvm_support,
7959 .disabled_by_bios = vmx_disabled_by_bios,
7960 .check_processor_compatibility = vmx_check_processor_compat,
7961 .hardware_setup = hardware_setup,
7963 .runtime_ops = &vmx_x86_ops,
7966 static void vmx_cleanup_l1d_flush(void)
7968 if (vmx_l1d_flush_pages) {
7969 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7970 vmx_l1d_flush_pages = NULL;
7972 /* Restore state so sysfs ignores VMX */
7973 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
7976 static void vmx_exit(void)
7978 #ifdef CONFIG_KEXEC_CORE
7979 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
7985 #if IS_ENABLED(CONFIG_HYPERV)
7986 if (static_branch_unlikely(&enable_evmcs)) {
7988 struct hv_vp_assist_page *vp_ap;
7990 * Reset everything to support using non-enlightened VMCS
7991 * access later (e.g. when we reload the module with
7992 * enlightened_vmcs=0)
7994 for_each_online_cpu(cpu) {
7995 vp_ap = hv_get_vp_assist_page(cpu);
8000 vp_ap->nested_control.features.directhypercall = 0;
8001 vp_ap->current_nested_vmcs = 0;
8002 vp_ap->enlighten_vmentry = 0;
8005 static_branch_disable(&enable_evmcs);
8008 vmx_cleanup_l1d_flush();
8010 module_exit(vmx_exit);
8012 static int __init vmx_init(void)
8016 #if IS_ENABLED(CONFIG_HYPERV)
8018 * Enlightened VMCS usage should be recommended and the host needs
8019 * to support eVMCS v1 or above. We can also disable eVMCS support
8020 * with module parameter.
8022 if (enlightened_vmcs &&
8023 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8024 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8025 KVM_EVMCS_VERSION) {
8028 /* Check that we have assist pages on all online CPUs */
8029 for_each_online_cpu(cpu) {
8030 if (!hv_get_vp_assist_page(cpu)) {
8031 enlightened_vmcs = false;
8036 if (enlightened_vmcs) {
8037 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8038 static_branch_enable(&enable_evmcs);
8041 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8042 vmx_x86_ops.enable_direct_tlbflush
8043 = hv_enable_direct_tlbflush;
8046 enlightened_vmcs = false;
8050 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8051 __alignof__(struct vcpu_vmx), THIS_MODULE);
8056 * Must be called after kvm_init() so enable_ept is properly set
8057 * up. Hand the parameter mitigation value in which was stored in
8058 * the pre module init parser. If no parameter was given, it will
8059 * contain 'auto' which will be turned into the default 'cond'
8062 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8068 for_each_possible_cpu(cpu) {
8069 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8074 #ifdef CONFIG_KEXEC_CORE
8075 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8076 crash_vmclear_local_loaded_vmcss);
8078 vmx_check_vmcs12_offsets();
8081 * Shadow paging doesn't have a (further) performance penalty
8082 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8086 allow_smaller_maxphyaddr = true;
8090 module_init(vmx_init);