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/frame.h>
17 #include <linux/highmem.h>
18 #include <linux/hrtimer.h>
19 #include <linux/kernel.h>
20 #include <linux/kvm_host.h>
21 #include <linux/module.h>
22 #include <linux/moduleparam.h>
23 #include <linux/mod_devicetable.h>
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>
44 #include <asm/mmu_context.h>
45 #include <asm/mshyperv.h>
46 #include <asm/mwait.h>
47 #include <asm/spec-ctrl.h>
48 #include <asm/virtext.h>
51 #include "capabilities.h"
55 #include "kvm_cache_regs.h"
67 MODULE_AUTHOR("Qumranet");
68 MODULE_LICENSE("GPL");
71 static const struct x86_cpu_id vmx_cpu_id[] = {
72 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
75 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
78 bool __read_mostly enable_vpid = 1;
79 module_param_named(vpid, enable_vpid, bool, 0444);
81 static bool __read_mostly enable_vnmi = 1;
82 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
84 bool __read_mostly flexpriority_enabled = 1;
85 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
87 bool __read_mostly enable_ept = 1;
88 module_param_named(ept, enable_ept, bool, S_IRUGO);
90 bool __read_mostly enable_unrestricted_guest = 1;
91 module_param_named(unrestricted_guest,
92 enable_unrestricted_guest, bool, S_IRUGO);
94 bool __read_mostly enable_ept_ad_bits = 1;
95 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
97 static bool __read_mostly emulate_invalid_guest_state = true;
98 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
100 static bool __read_mostly fasteoi = 1;
101 module_param(fasteoi, bool, S_IRUGO);
103 bool __read_mostly enable_apicv = 1;
104 module_param(enable_apicv, bool, S_IRUGO);
107 * If nested=1, nested virtualization is supported, i.e., guests may use
108 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
109 * use VMX instructions.
111 static bool __read_mostly nested = 1;
112 module_param(nested, bool, S_IRUGO);
114 bool __read_mostly enable_pml = 1;
115 module_param_named(pml, enable_pml, bool, S_IRUGO);
117 static bool __read_mostly dump_invalid_vmcs = 0;
118 module_param(dump_invalid_vmcs, bool, 0644);
120 #define MSR_BITMAP_MODE_X2APIC 1
121 #define MSR_BITMAP_MODE_X2APIC_APICV 2
123 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
125 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
126 static int __read_mostly cpu_preemption_timer_multi;
127 static bool __read_mostly enable_preemption_timer = 1;
129 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
132 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
133 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
134 #define KVM_VM_CR0_ALWAYS_ON \
135 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
136 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
138 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
139 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
140 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
142 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
144 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
145 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
146 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
147 RTIT_STATUS_BYTECNT))
150 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
151 * ple_gap: upper bound on the amount of time between two successive
152 * executions of PAUSE in a loop. Also indicate if ple enabled.
153 * According to test, this time is usually smaller than 128 cycles.
154 * ple_window: upper bound on the amount of time a guest is allowed to execute
155 * in a PAUSE loop. Tests indicate that most spinlocks are held for
156 * less than 2^12 cycles
157 * Time is measured based on a counter that runs at the same rate as the TSC,
158 * refer SDM volume 3b section 21.6.13 & 22.1.3.
160 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
161 module_param(ple_gap, uint, 0444);
163 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
164 module_param(ple_window, uint, 0444);
166 /* Default doubles per-vcpu window every exit. */
167 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
168 module_param(ple_window_grow, uint, 0444);
170 /* Default resets per-vcpu window every exit to ple_window. */
171 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
172 module_param(ple_window_shrink, uint, 0444);
174 /* Default is to compute the maximum so we can never overflow. */
175 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
176 module_param(ple_window_max, uint, 0444);
178 /* Default is SYSTEM mode, 1 for host-guest mode */
179 int __read_mostly pt_mode = PT_MODE_SYSTEM;
180 module_param(pt_mode, int, S_IRUGO);
182 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
183 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
184 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
186 /* Storage for pre module init parameter parsing */
187 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
189 static const struct {
192 } vmentry_l1d_param[] = {
193 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
194 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
195 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
196 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
197 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
198 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
201 #define L1D_CACHE_ORDER 4
202 static void *vmx_l1d_flush_pages;
204 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
209 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
210 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
215 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
219 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
222 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
223 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
224 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
229 /* If set to auto use the default l1tf mitigation method */
230 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
231 switch (l1tf_mitigation) {
232 case L1TF_MITIGATION_OFF:
233 l1tf = VMENTER_L1D_FLUSH_NEVER;
235 case L1TF_MITIGATION_FLUSH_NOWARN:
236 case L1TF_MITIGATION_FLUSH:
237 case L1TF_MITIGATION_FLUSH_NOSMT:
238 l1tf = VMENTER_L1D_FLUSH_COND;
240 case L1TF_MITIGATION_FULL:
241 case L1TF_MITIGATION_FULL_FORCE:
242 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
245 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
246 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
249 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
250 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
252 * This allocation for vmx_l1d_flush_pages is not tied to a VM
253 * lifetime and so should not be charged to a memcg.
255 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
258 vmx_l1d_flush_pages = page_address(page);
261 * Initialize each page with a different pattern in
262 * order to protect against KSM in the nested
263 * virtualization case.
265 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
266 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
271 l1tf_vmx_mitigation = l1tf;
273 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
274 static_branch_enable(&vmx_l1d_should_flush);
276 static_branch_disable(&vmx_l1d_should_flush);
278 if (l1tf == VMENTER_L1D_FLUSH_COND)
279 static_branch_enable(&vmx_l1d_flush_cond);
281 static_branch_disable(&vmx_l1d_flush_cond);
285 static int vmentry_l1d_flush_parse(const char *s)
290 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
291 if (vmentry_l1d_param[i].for_parse &&
292 sysfs_streq(s, vmentry_l1d_param[i].option))
299 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
303 l1tf = vmentry_l1d_flush_parse(s);
307 if (!boot_cpu_has(X86_BUG_L1TF))
311 * Has vmx_init() run already? If not then this is the pre init
312 * parameter parsing. In that case just store the value and let
313 * vmx_init() do the proper setup after enable_ept has been
316 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
317 vmentry_l1d_flush_param = l1tf;
321 mutex_lock(&vmx_l1d_flush_mutex);
322 ret = vmx_setup_l1d_flush(l1tf);
323 mutex_unlock(&vmx_l1d_flush_mutex);
327 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
329 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
330 return sprintf(s, "???\n");
332 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
335 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
336 .set = vmentry_l1d_flush_set,
337 .get = vmentry_l1d_flush_get,
339 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
341 static bool guest_state_valid(struct kvm_vcpu *vcpu);
342 static u32 vmx_segment_access_rights(struct kvm_segment *var);
343 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
346 void vmx_vmexit(void);
348 #define vmx_insn_failed(fmt...) \
351 pr_warn_ratelimited(fmt); \
354 asmlinkage void vmread_error(unsigned long field, bool fault)
357 kvm_spurious_fault();
359 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
362 noinline void vmwrite_error(unsigned long field, unsigned long value)
364 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
365 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
368 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
370 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
373 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
375 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
378 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
380 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
384 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
386 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
390 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
391 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
393 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
394 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
396 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
399 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
400 * can find which vCPU should be waken up.
402 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
403 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
405 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
406 static DEFINE_SPINLOCK(vmx_vpid_lock);
408 struct vmcs_config vmcs_config;
409 struct vmx_capability vmx_capability;
411 #define VMX_SEGMENT_FIELD(seg) \
412 [VCPU_SREG_##seg] = { \
413 .selector = GUEST_##seg##_SELECTOR, \
414 .base = GUEST_##seg##_BASE, \
415 .limit = GUEST_##seg##_LIMIT, \
416 .ar_bytes = GUEST_##seg##_AR_BYTES, \
419 static const struct kvm_vmx_segment_field {
424 } kvm_vmx_segment_fields[] = {
425 VMX_SEGMENT_FIELD(CS),
426 VMX_SEGMENT_FIELD(DS),
427 VMX_SEGMENT_FIELD(ES),
428 VMX_SEGMENT_FIELD(FS),
429 VMX_SEGMENT_FIELD(GS),
430 VMX_SEGMENT_FIELD(SS),
431 VMX_SEGMENT_FIELD(TR),
432 VMX_SEGMENT_FIELD(LDTR),
435 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
437 vmx->segment_cache.bitmask = 0;
440 static unsigned long host_idt_base;
443 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
444 * will emulate SYSCALL in legacy mode if the vendor string in guest
445 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
446 * support this emulation, IA32_STAR must always be included in
447 * vmx_msr_index[], even in i386 builds.
449 const u32 vmx_msr_index[] = {
451 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
453 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
457 #if IS_ENABLED(CONFIG_HYPERV)
458 static bool __read_mostly enlightened_vmcs = true;
459 module_param(enlightened_vmcs, bool, 0444);
461 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
462 static void check_ept_pointer_match(struct kvm *kvm)
464 struct kvm_vcpu *vcpu;
465 u64 tmp_eptp = INVALID_PAGE;
468 kvm_for_each_vcpu(i, vcpu, kvm) {
469 if (!VALID_PAGE(tmp_eptp)) {
470 tmp_eptp = to_vmx(vcpu)->ept_pointer;
471 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
472 to_kvm_vmx(kvm)->ept_pointers_match
473 = EPT_POINTERS_MISMATCH;
478 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
481 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
484 struct kvm_tlb_range *range = data;
486 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
490 static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
491 struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
493 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
496 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
497 * of the base of EPT PML4 table, strip off EPT configuration
501 return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
502 kvm_fill_hv_flush_list_func, (void *)range);
504 return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
507 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
508 struct kvm_tlb_range *range)
510 struct kvm_vcpu *vcpu;
513 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
515 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
516 check_ept_pointer_match(kvm);
518 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
519 kvm_for_each_vcpu(i, vcpu, kvm) {
520 /* If ept_pointer is invalid pointer, bypass flush request. */
521 if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
522 ret |= __hv_remote_flush_tlb_with_range(
526 ret = __hv_remote_flush_tlb_with_range(kvm,
527 kvm_get_vcpu(kvm, 0), range);
530 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
533 static int hv_remote_flush_tlb(struct kvm *kvm)
535 return hv_remote_flush_tlb_with_range(kvm, NULL);
538 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
540 struct hv_enlightened_vmcs *evmcs;
541 struct hv_partition_assist_pg **p_hv_pa_pg =
542 &vcpu->kvm->arch.hyperv.hv_pa_pg;
544 * Synthetic VM-Exit is not enabled in current code and so All
545 * evmcs in singe VM shares same assist page.
548 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL);
553 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
555 evmcs->partition_assist_page =
557 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
558 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
563 #endif /* IS_ENABLED(CONFIG_HYPERV) */
566 * Comment's format: document - errata name - stepping - processor name.
568 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
570 static u32 vmx_preemption_cpu_tfms[] = {
571 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
573 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
574 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
575 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
577 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
579 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
580 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
582 * 320767.pdf - AAP86 - B1 -
583 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
586 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
588 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
590 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
592 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
593 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
594 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
596 /* Xeon E3-1220 V2 */
600 static inline bool cpu_has_broken_vmx_preemption_timer(void)
602 u32 eax = cpuid_eax(0x00000001), i;
604 /* Clear the reserved bits */
605 eax &= ~(0x3U << 14 | 0xfU << 28);
606 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
607 if (eax == vmx_preemption_cpu_tfms[i])
613 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
615 return flexpriority_enabled && lapic_in_kernel(vcpu);
618 static inline bool report_flexpriority(void)
620 return flexpriority_enabled;
623 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
627 for (i = 0; i < vmx->nmsrs; ++i)
628 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
633 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
637 i = __find_msr_index(vmx, msr);
639 return &vmx->guest_msrs[i];
643 static int vmx_set_guest_msr(struct vcpu_vmx *vmx, struct shared_msr_entry *msr, u64 data)
647 u64 old_msr_data = msr->data;
649 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
651 ret = kvm_set_shared_msr(msr->index, msr->data,
655 msr->data = old_msr_data;
660 #ifdef CONFIG_KEXEC_CORE
661 static void crash_vmclear_local_loaded_vmcss(void)
663 int cpu = raw_smp_processor_id();
664 struct loaded_vmcs *v;
666 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
667 loaded_vmcss_on_cpu_link)
670 #endif /* CONFIG_KEXEC_CORE */
672 static void __loaded_vmcs_clear(void *arg)
674 struct loaded_vmcs *loaded_vmcs = arg;
675 int cpu = raw_smp_processor_id();
677 if (loaded_vmcs->cpu != cpu)
678 return; /* vcpu migration can race with cpu offline */
679 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
680 per_cpu(current_vmcs, cpu) = NULL;
682 vmcs_clear(loaded_vmcs->vmcs);
683 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
684 vmcs_clear(loaded_vmcs->shadow_vmcs);
686 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
689 * Ensure all writes to loaded_vmcs, including deleting it from its
690 * current percpu list, complete before setting loaded_vmcs->vcpu to
691 * -1, otherwise a different cpu can see vcpu == -1 first and add
692 * loaded_vmcs to its percpu list before it's deleted from this cpu's
693 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
697 loaded_vmcs->cpu = -1;
698 loaded_vmcs->launched = 0;
701 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
703 int cpu = loaded_vmcs->cpu;
706 smp_call_function_single(cpu,
707 __loaded_vmcs_clear, loaded_vmcs, 1);
710 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
714 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
716 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
717 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
718 vmx->segment_cache.bitmask = 0;
720 ret = vmx->segment_cache.bitmask & mask;
721 vmx->segment_cache.bitmask |= mask;
725 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
727 u16 *p = &vmx->segment_cache.seg[seg].selector;
729 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
730 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
734 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
736 ulong *p = &vmx->segment_cache.seg[seg].base;
738 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
739 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
743 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
745 u32 *p = &vmx->segment_cache.seg[seg].limit;
747 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
748 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
752 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
754 u32 *p = &vmx->segment_cache.seg[seg].ar;
756 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
757 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
761 void update_exception_bitmap(struct kvm_vcpu *vcpu)
765 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
766 (1u << DB_VECTOR) | (1u << AC_VECTOR);
768 * Guest access to VMware backdoor ports could legitimately
769 * trigger #GP because of TSS I/O permission bitmap.
770 * We intercept those #GP and allow access to them anyway
773 if (enable_vmware_backdoor)
774 eb |= (1u << GP_VECTOR);
775 if ((vcpu->guest_debug &
776 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
777 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
778 eb |= 1u << BP_VECTOR;
779 if (to_vmx(vcpu)->rmode.vm86_active)
781 if (!vmx_need_pf_intercept(vcpu))
782 eb &= ~(1u << PF_VECTOR);
784 /* When we are running a nested L2 guest and L1 specified for it a
785 * certain exception bitmap, we must trap the same exceptions and pass
786 * them to L1. When running L2, we will only handle the exceptions
787 * specified above if L1 did not want them.
789 if (is_guest_mode(vcpu))
790 eb |= get_vmcs12(vcpu)->exception_bitmap;
792 vmcs_write32(EXCEPTION_BITMAP, eb);
796 * Check if MSR is intercepted for currently loaded MSR bitmap.
798 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
800 unsigned long *msr_bitmap;
801 int f = sizeof(unsigned long);
803 if (!cpu_has_vmx_msr_bitmap())
806 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
809 return !!test_bit(msr, msr_bitmap + 0x800 / f);
810 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
812 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
818 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
819 unsigned long entry, unsigned long exit)
821 vm_entry_controls_clearbit(vmx, entry);
822 vm_exit_controls_clearbit(vmx, exit);
825 int vmx_find_msr_index(struct vmx_msrs *m, u32 msr)
829 for (i = 0; i < m->nr; ++i) {
830 if (m->val[i].index == msr)
836 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
839 struct msr_autoload *m = &vmx->msr_autoload;
843 if (cpu_has_load_ia32_efer()) {
844 clear_atomic_switch_msr_special(vmx,
845 VM_ENTRY_LOAD_IA32_EFER,
846 VM_EXIT_LOAD_IA32_EFER);
850 case MSR_CORE_PERF_GLOBAL_CTRL:
851 if (cpu_has_load_perf_global_ctrl()) {
852 clear_atomic_switch_msr_special(vmx,
853 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
854 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
859 i = vmx_find_msr_index(&m->guest, msr);
863 m->guest.val[i] = m->guest.val[m->guest.nr];
864 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
867 i = vmx_find_msr_index(&m->host, msr);
872 m->host.val[i] = m->host.val[m->host.nr];
873 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
876 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
877 unsigned long entry, unsigned long exit,
878 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
879 u64 guest_val, u64 host_val)
881 vmcs_write64(guest_val_vmcs, guest_val);
882 if (host_val_vmcs != HOST_IA32_EFER)
883 vmcs_write64(host_val_vmcs, host_val);
884 vm_entry_controls_setbit(vmx, entry);
885 vm_exit_controls_setbit(vmx, exit);
888 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
889 u64 guest_val, u64 host_val, bool entry_only)
892 struct msr_autoload *m = &vmx->msr_autoload;
896 if (cpu_has_load_ia32_efer()) {
897 add_atomic_switch_msr_special(vmx,
898 VM_ENTRY_LOAD_IA32_EFER,
899 VM_EXIT_LOAD_IA32_EFER,
902 guest_val, host_val);
906 case MSR_CORE_PERF_GLOBAL_CTRL:
907 if (cpu_has_load_perf_global_ctrl()) {
908 add_atomic_switch_msr_special(vmx,
909 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
910 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
911 GUEST_IA32_PERF_GLOBAL_CTRL,
912 HOST_IA32_PERF_GLOBAL_CTRL,
913 guest_val, host_val);
917 case MSR_IA32_PEBS_ENABLE:
918 /* PEBS needs a quiescent period after being disabled (to write
919 * a record). Disabling PEBS through VMX MSR swapping doesn't
920 * provide that period, so a CPU could write host's record into
923 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
926 i = vmx_find_msr_index(&m->guest, msr);
928 j = vmx_find_msr_index(&m->host, msr);
930 if ((i < 0 && m->guest.nr == NR_LOADSTORE_MSRS) ||
931 (j < 0 && m->host.nr == NR_LOADSTORE_MSRS)) {
932 printk_once(KERN_WARNING "Not enough msr switch entries. "
933 "Can't add msr %x\n", msr);
938 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
940 m->guest.val[i].index = msr;
941 m->guest.val[i].value = guest_val;
948 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
950 m->host.val[j].index = msr;
951 m->host.val[j].value = host_val;
954 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
956 u64 guest_efer = vmx->vcpu.arch.efer;
959 /* Shadow paging assumes NX to be available. */
961 guest_efer |= EFER_NX;
964 * LMA and LME handled by hardware; SCE meaningless outside long mode.
966 ignore_bits |= EFER_SCE;
968 ignore_bits |= EFER_LMA | EFER_LME;
969 /* SCE is meaningful only in long mode on Intel */
970 if (guest_efer & EFER_LMA)
971 ignore_bits &= ~(u64)EFER_SCE;
975 * On EPT, we can't emulate NX, so we must switch EFER atomically.
976 * On CPUs that support "load IA32_EFER", always switch EFER
977 * atomically, since it's faster than switching it manually.
979 if (cpu_has_load_ia32_efer() ||
980 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
981 if (!(guest_efer & EFER_LMA))
982 guest_efer &= ~EFER_LME;
983 if (guest_efer != host_efer)
984 add_atomic_switch_msr(vmx, MSR_EFER,
985 guest_efer, host_efer, false);
987 clear_atomic_switch_msr(vmx, MSR_EFER);
990 clear_atomic_switch_msr(vmx, MSR_EFER);
992 guest_efer &= ~ignore_bits;
993 guest_efer |= host_efer & ignore_bits;
995 vmx->guest_msrs[efer_offset].data = guest_efer;
996 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1002 #ifdef CONFIG_X86_32
1004 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1005 * VMCS rather than the segment table. KVM uses this helper to figure
1006 * out the current bases to poke them into the VMCS before entry.
1008 static unsigned long segment_base(u16 selector)
1010 struct desc_struct *table;
1013 if (!(selector & ~SEGMENT_RPL_MASK))
1016 table = get_current_gdt_ro();
1018 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1019 u16 ldt_selector = kvm_read_ldt();
1021 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1024 table = (struct desc_struct *)segment_base(ldt_selector);
1026 v = get_desc_base(&table[selector >> 3]);
1031 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1033 return vmx_pt_mode_is_host_guest() &&
1034 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1037 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1039 /* The base must be 128-byte aligned and a legal physical address. */
1040 return !kvm_vcpu_is_illegal_gpa(vcpu, base) && !(base & 0x7f);
1043 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1047 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1048 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1049 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1050 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1051 for (i = 0; i < addr_range; i++) {
1052 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1053 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1057 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1061 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1062 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1063 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1064 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1065 for (i = 0; i < addr_range; i++) {
1066 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1067 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1071 static void pt_guest_enter(struct vcpu_vmx *vmx)
1073 if (vmx_pt_mode_is_system())
1077 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1078 * Save host state before VM entry.
1080 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1081 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1082 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1083 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1084 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1088 static void pt_guest_exit(struct vcpu_vmx *vmx)
1090 if (vmx_pt_mode_is_system())
1093 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1094 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1095 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1098 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1099 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1102 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1103 unsigned long fs_base, unsigned long gs_base)
1105 if (unlikely(fs_sel != host->fs_sel)) {
1107 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1109 vmcs_write16(HOST_FS_SELECTOR, 0);
1110 host->fs_sel = fs_sel;
1112 if (unlikely(gs_sel != host->gs_sel)) {
1114 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1116 vmcs_write16(HOST_GS_SELECTOR, 0);
1117 host->gs_sel = gs_sel;
1119 if (unlikely(fs_base != host->fs_base)) {
1120 vmcs_writel(HOST_FS_BASE, fs_base);
1121 host->fs_base = fs_base;
1123 if (unlikely(gs_base != host->gs_base)) {
1124 vmcs_writel(HOST_GS_BASE, gs_base);
1125 host->gs_base = gs_base;
1129 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1131 struct vcpu_vmx *vmx = to_vmx(vcpu);
1132 struct vmcs_host_state *host_state;
1133 #ifdef CONFIG_X86_64
1134 int cpu = raw_smp_processor_id();
1136 unsigned long fs_base, gs_base;
1140 vmx->req_immediate_exit = false;
1143 * Note that guest MSRs to be saved/restored can also be changed
1144 * when guest state is loaded. This happens when guest transitions
1145 * to/from long-mode by setting MSR_EFER.LMA.
1147 if (!vmx->guest_msrs_ready) {
1148 vmx->guest_msrs_ready = true;
1149 for (i = 0; i < vmx->save_nmsrs; ++i)
1150 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1151 vmx->guest_msrs[i].data,
1152 vmx->guest_msrs[i].mask);
1156 if (vmx->nested.need_vmcs12_to_shadow_sync)
1157 nested_sync_vmcs12_to_shadow(vcpu);
1159 if (vmx->guest_state_loaded)
1162 host_state = &vmx->loaded_vmcs->host_state;
1165 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1166 * allow segment selectors with cpl > 0 or ti == 1.
1168 host_state->ldt_sel = kvm_read_ldt();
1170 #ifdef CONFIG_X86_64
1171 savesegment(ds, host_state->ds_sel);
1172 savesegment(es, host_state->es_sel);
1174 gs_base = cpu_kernelmode_gs_base(cpu);
1175 if (likely(is_64bit_mm(current->mm))) {
1176 current_save_fsgs();
1177 fs_sel = current->thread.fsindex;
1178 gs_sel = current->thread.gsindex;
1179 fs_base = current->thread.fsbase;
1180 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1182 savesegment(fs, fs_sel);
1183 savesegment(gs, gs_sel);
1184 fs_base = read_msr(MSR_FS_BASE);
1185 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1188 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1190 savesegment(fs, fs_sel);
1191 savesegment(gs, gs_sel);
1192 fs_base = segment_base(fs_sel);
1193 gs_base = segment_base(gs_sel);
1196 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1197 vmx->guest_state_loaded = true;
1200 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1202 struct vmcs_host_state *host_state;
1204 if (!vmx->guest_state_loaded)
1207 host_state = &vmx->loaded_vmcs->host_state;
1209 ++vmx->vcpu.stat.host_state_reload;
1211 #ifdef CONFIG_X86_64
1212 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1214 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1215 kvm_load_ldt(host_state->ldt_sel);
1216 #ifdef CONFIG_X86_64
1217 load_gs_index(host_state->gs_sel);
1219 loadsegment(gs, host_state->gs_sel);
1222 if (host_state->fs_sel & 7)
1223 loadsegment(fs, host_state->fs_sel);
1224 #ifdef CONFIG_X86_64
1225 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1226 loadsegment(ds, host_state->ds_sel);
1227 loadsegment(es, host_state->es_sel);
1230 invalidate_tss_limit();
1231 #ifdef CONFIG_X86_64
1232 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1234 load_fixmap_gdt(raw_smp_processor_id());
1235 vmx->guest_state_loaded = false;
1236 vmx->guest_msrs_ready = false;
1239 #ifdef CONFIG_X86_64
1240 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1243 if (vmx->guest_state_loaded)
1244 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1246 return vmx->msr_guest_kernel_gs_base;
1249 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1252 if (vmx->guest_state_loaded)
1253 wrmsrl(MSR_KERNEL_GS_BASE, data);
1255 vmx->msr_guest_kernel_gs_base = data;
1259 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1261 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1262 struct pi_desc old, new;
1266 * In case of hot-plug or hot-unplug, we may have to undo
1267 * vmx_vcpu_pi_put even if there is no assigned device. And we
1268 * always keep PI.NDST up to date for simplicity: it makes the
1269 * code easier, and CPU migration is not a fast path.
1271 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1275 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
1276 * PI.NDST: pi_post_block is the one expected to change PID.NDST and the
1277 * wakeup handler expects the vCPU to be on the blocked_vcpu_list that
1278 * matches PI.NDST. Otherwise, a vcpu may not be able to be woken up
1281 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR || vcpu->cpu == cpu) {
1282 pi_clear_sn(pi_desc);
1283 goto after_clear_sn;
1286 /* The full case. */
1288 old.control = new.control = pi_desc->control;
1290 dest = cpu_physical_id(cpu);
1292 if (x2apic_enabled())
1295 new.ndst = (dest << 8) & 0xFF00;
1298 } while (cmpxchg64(&pi_desc->control, old.control,
1299 new.control) != old.control);
1304 * Clear SN before reading the bitmap. The VT-d firmware
1305 * writes the bitmap and reads SN atomically (5.2.3 in the
1306 * spec), so it doesn't really have a memory barrier that
1307 * pairs with this, but we cannot do that and we need one.
1309 smp_mb__after_atomic();
1311 if (!pi_is_pir_empty(pi_desc))
1315 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1316 struct loaded_vmcs *buddy)
1318 struct vcpu_vmx *vmx = to_vmx(vcpu);
1319 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1322 if (!already_loaded) {
1323 loaded_vmcs_clear(vmx->loaded_vmcs);
1324 local_irq_disable();
1327 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1328 * this cpu's percpu list, otherwise it may not yet be deleted
1329 * from its previous cpu's percpu list. Pairs with the
1330 * smb_wmb() in __loaded_vmcs_clear().
1334 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1335 &per_cpu(loaded_vmcss_on_cpu, cpu));
1339 prev = per_cpu(current_vmcs, cpu);
1340 if (prev != vmx->loaded_vmcs->vmcs) {
1341 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1342 vmcs_load(vmx->loaded_vmcs->vmcs);
1345 * No indirect branch prediction barrier needed when switching
1346 * the active VMCS within a guest, e.g. on nested VM-Enter.
1347 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1349 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1350 indirect_branch_prediction_barrier();
1353 if (!already_loaded) {
1354 void *gdt = get_current_gdt_ro();
1355 unsigned long sysenter_esp;
1358 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1359 * TLB entries from its previous association with the vCPU.
1361 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1364 * Linux uses per-cpu TSS and GDT, so set these when switching
1365 * processors. See 22.2.4.
1367 vmcs_writel(HOST_TR_BASE,
1368 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1369 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1371 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1372 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1374 vmx->loaded_vmcs->cpu = cpu;
1377 /* Setup TSC multiplier */
1378 if (kvm_has_tsc_control &&
1379 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1380 decache_tsc_multiplier(vmx);
1384 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1385 * vcpu mutex is already taken.
1387 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1389 struct vcpu_vmx *vmx = to_vmx(vcpu);
1391 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1393 vmx_vcpu_pi_load(vcpu, cpu);
1395 vmx->host_debugctlmsr = get_debugctlmsr();
1398 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1400 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1402 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1403 !irq_remapping_cap(IRQ_POSTING_CAP) ||
1404 !kvm_vcpu_apicv_active(vcpu))
1407 /* Set SN when the vCPU is preempted */
1408 if (vcpu->preempted)
1412 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1414 vmx_vcpu_pi_put(vcpu);
1416 vmx_prepare_switch_to_host(to_vmx(vcpu));
1419 static bool emulation_required(struct kvm_vcpu *vcpu)
1421 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1424 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1426 struct vcpu_vmx *vmx = to_vmx(vcpu);
1427 unsigned long rflags, save_rflags;
1429 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1430 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1431 rflags = vmcs_readl(GUEST_RFLAGS);
1432 if (vmx->rmode.vm86_active) {
1433 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1434 save_rflags = vmx->rmode.save_rflags;
1435 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1437 vmx->rflags = rflags;
1442 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1444 struct vcpu_vmx *vmx = to_vmx(vcpu);
1445 unsigned long old_rflags;
1447 if (is_unrestricted_guest(vcpu)) {
1448 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1449 vmx->rflags = rflags;
1450 vmcs_writel(GUEST_RFLAGS, rflags);
1454 old_rflags = vmx_get_rflags(vcpu);
1455 vmx->rflags = rflags;
1456 if (vmx->rmode.vm86_active) {
1457 vmx->rmode.save_rflags = rflags;
1458 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1460 vmcs_writel(GUEST_RFLAGS, rflags);
1462 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1463 vmx->emulation_required = emulation_required(vcpu);
1466 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1468 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1471 if (interruptibility & GUEST_INTR_STATE_STI)
1472 ret |= KVM_X86_SHADOW_INT_STI;
1473 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1474 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1479 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1481 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1482 u32 interruptibility = interruptibility_old;
1484 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1486 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1487 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1488 else if (mask & KVM_X86_SHADOW_INT_STI)
1489 interruptibility |= GUEST_INTR_STATE_STI;
1491 if ((interruptibility != interruptibility_old))
1492 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1495 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1497 struct vcpu_vmx *vmx = to_vmx(vcpu);
1498 unsigned long value;
1501 * Any MSR write that attempts to change bits marked reserved will
1504 if (data & vmx->pt_desc.ctl_bitmask)
1508 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1509 * result in a #GP unless the same write also clears TraceEn.
1511 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1512 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1516 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1517 * and FabricEn would cause #GP, if
1518 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1520 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1521 !(data & RTIT_CTL_FABRIC_EN) &&
1522 !intel_pt_validate_cap(vmx->pt_desc.caps,
1523 PT_CAP_single_range_output))
1527 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1528 * utilize encodings marked reserved will casue a #GP fault.
1530 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1531 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1532 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1533 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1535 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1536 PT_CAP_cycle_thresholds);
1537 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1538 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1539 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1541 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1542 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1543 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1544 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1548 * If ADDRx_CFG is reserved or the encodings is >2 will
1549 * cause a #GP fault.
1551 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1552 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1554 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1555 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1557 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1558 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1560 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1561 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1567 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
1572 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1574 unsigned long rip, orig_rip;
1577 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1578 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1579 * set when EPT misconfig occurs. In practice, real hardware updates
1580 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1581 * (namely Hyper-V) don't set it due to it being undefined behavior,
1582 * i.e. we end up advancing IP with some random value.
1584 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1585 to_vmx(vcpu)->exit_reason != EXIT_REASON_EPT_MISCONFIG) {
1586 orig_rip = kvm_rip_read(vcpu);
1587 rip = orig_rip + vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1588 #ifdef CONFIG_X86_64
1590 * We need to mask out the high 32 bits of RIP if not in 64-bit
1591 * mode, but just finding out that we are in 64-bit mode is
1592 * quite expensive. Only do it if there was a carry.
1594 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1597 kvm_rip_write(vcpu, rip);
1599 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1603 /* skipping an emulated instruction also counts */
1604 vmx_set_interrupt_shadow(vcpu, 0);
1610 * Recognizes a pending MTF VM-exit and records the nested state for later
1613 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1615 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1616 struct vcpu_vmx *vmx = to_vmx(vcpu);
1618 if (!is_guest_mode(vcpu))
1622 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1623 * T-bit traps. As instruction emulation is completed (i.e. at the
1624 * instruction boundary), any #DB exception pending delivery must be a
1625 * debug-trap. Record the pending MTF state to be delivered in
1626 * vmx_check_nested_events().
1628 if (nested_cpu_has_mtf(vmcs12) &&
1629 (!vcpu->arch.exception.pending ||
1630 vcpu->arch.exception.nr == DB_VECTOR))
1631 vmx->nested.mtf_pending = true;
1633 vmx->nested.mtf_pending = false;
1636 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1638 vmx_update_emulated_instruction(vcpu);
1639 return skip_emulated_instruction(vcpu);
1642 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1645 * Ensure that we clear the HLT state in the VMCS. We don't need to
1646 * explicitly skip the instruction because if the HLT state is set,
1647 * then the instruction is already executing and RIP has already been
1650 if (kvm_hlt_in_guest(vcpu->kvm) &&
1651 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1652 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1655 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1657 struct vcpu_vmx *vmx = to_vmx(vcpu);
1658 unsigned nr = vcpu->arch.exception.nr;
1659 bool has_error_code = vcpu->arch.exception.has_error_code;
1660 u32 error_code = vcpu->arch.exception.error_code;
1661 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1663 kvm_deliver_exception_payload(vcpu);
1665 if (has_error_code) {
1666 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1667 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1670 if (vmx->rmode.vm86_active) {
1672 if (kvm_exception_is_soft(nr))
1673 inc_eip = vcpu->arch.event_exit_inst_len;
1674 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1678 WARN_ON_ONCE(vmx->emulation_required);
1680 if (kvm_exception_is_soft(nr)) {
1681 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1682 vmx->vcpu.arch.event_exit_inst_len);
1683 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1685 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1687 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1689 vmx_clear_hlt(vcpu);
1693 * Swap MSR entry in host/guest MSR entry array.
1695 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1697 struct shared_msr_entry tmp;
1699 tmp = vmx->guest_msrs[to];
1700 vmx->guest_msrs[to] = vmx->guest_msrs[from];
1701 vmx->guest_msrs[from] = tmp;
1705 * Set up the vmcs to automatically save and restore system
1706 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1707 * mode, as fiddling with msrs is very expensive.
1709 static void setup_msrs(struct vcpu_vmx *vmx)
1711 int save_nmsrs, index;
1714 #ifdef CONFIG_X86_64
1716 * The SYSCALL MSRs are only needed on long mode guests, and only
1717 * when EFER.SCE is set.
1719 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1720 index = __find_msr_index(vmx, MSR_STAR);
1722 move_msr_up(vmx, index, save_nmsrs++);
1723 index = __find_msr_index(vmx, MSR_LSTAR);
1725 move_msr_up(vmx, index, save_nmsrs++);
1726 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1728 move_msr_up(vmx, index, save_nmsrs++);
1731 index = __find_msr_index(vmx, MSR_EFER);
1732 if (index >= 0 && update_transition_efer(vmx, index))
1733 move_msr_up(vmx, index, save_nmsrs++);
1734 index = __find_msr_index(vmx, MSR_TSC_AUX);
1735 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1736 move_msr_up(vmx, index, save_nmsrs++);
1737 index = __find_msr_index(vmx, MSR_IA32_TSX_CTRL);
1739 move_msr_up(vmx, index, save_nmsrs++);
1741 vmx->save_nmsrs = save_nmsrs;
1742 vmx->guest_msrs_ready = false;
1744 if (cpu_has_vmx_msr_bitmap())
1745 vmx_update_msr_bitmap(&vmx->vcpu);
1748 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1750 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1751 u64 g_tsc_offset = 0;
1754 * We're here if L1 chose not to trap WRMSR to TSC. According
1755 * to the spec, this should set L1's TSC; The offset that L1
1756 * set for L2 remains unchanged, and still needs to be added
1757 * to the newly set TSC to get L2's TSC.
1759 if (is_guest_mode(vcpu) &&
1760 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
1761 g_tsc_offset = vmcs12->tsc_offset;
1763 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1764 vcpu->arch.tsc_offset - g_tsc_offset,
1766 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1767 return offset + g_tsc_offset;
1771 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1772 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1773 * all guests if the "nested" module option is off, and can also be disabled
1774 * for a single guest by disabling its VMX cpuid bit.
1776 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1778 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1781 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1784 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1786 return !(val & ~valid_bits);
1789 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1791 switch (msr->index) {
1792 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1795 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1796 case MSR_IA32_PERF_CAPABILITIES:
1797 msr->data = vmx_get_perf_capabilities();
1800 return KVM_MSR_RET_INVALID;
1805 * Reads an msr value (of 'msr_index') into 'pdata'.
1806 * Returns 0 on success, non-0 otherwise.
1807 * Assumes vcpu_load() was already called.
1809 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1811 struct vcpu_vmx *vmx = to_vmx(vcpu);
1812 struct shared_msr_entry *msr;
1815 switch (msr_info->index) {
1816 #ifdef CONFIG_X86_64
1818 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1821 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1823 case MSR_KERNEL_GS_BASE:
1824 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1828 return kvm_get_msr_common(vcpu, msr_info);
1829 case MSR_IA32_TSX_CTRL:
1830 if (!msr_info->host_initiated &&
1831 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1833 goto find_shared_msr;
1834 case MSR_IA32_UMWAIT_CONTROL:
1835 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1838 msr_info->data = vmx->msr_ia32_umwait_control;
1840 case MSR_IA32_SPEC_CTRL:
1841 if (!msr_info->host_initiated &&
1842 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1845 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1847 case MSR_IA32_SYSENTER_CS:
1848 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1850 case MSR_IA32_SYSENTER_EIP:
1851 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1853 case MSR_IA32_SYSENTER_ESP:
1854 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1856 case MSR_IA32_BNDCFGS:
1857 if (!kvm_mpx_supported() ||
1858 (!msr_info->host_initiated &&
1859 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1861 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1863 case MSR_IA32_MCG_EXT_CTL:
1864 if (!msr_info->host_initiated &&
1865 !(vmx->msr_ia32_feature_control &
1866 FEAT_CTL_LMCE_ENABLED))
1868 msr_info->data = vcpu->arch.mcg_ext_ctl;
1870 case MSR_IA32_FEAT_CTL:
1871 msr_info->data = vmx->msr_ia32_feature_control;
1873 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1874 if (!nested_vmx_allowed(vcpu))
1876 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1880 * Enlightened VMCS v1 doesn't have certain fields, but buggy
1881 * Hyper-V versions are still trying to use corresponding
1882 * features when they are exposed. Filter out the essential
1885 if (!msr_info->host_initiated &&
1886 vmx->nested.enlightened_vmcs_enabled)
1887 nested_evmcs_filter_control_msr(msr_info->index,
1890 case MSR_IA32_RTIT_CTL:
1891 if (!vmx_pt_mode_is_host_guest())
1893 msr_info->data = vmx->pt_desc.guest.ctl;
1895 case MSR_IA32_RTIT_STATUS:
1896 if (!vmx_pt_mode_is_host_guest())
1898 msr_info->data = vmx->pt_desc.guest.status;
1900 case MSR_IA32_RTIT_CR3_MATCH:
1901 if (!vmx_pt_mode_is_host_guest() ||
1902 !intel_pt_validate_cap(vmx->pt_desc.caps,
1903 PT_CAP_cr3_filtering))
1905 msr_info->data = vmx->pt_desc.guest.cr3_match;
1907 case MSR_IA32_RTIT_OUTPUT_BASE:
1908 if (!vmx_pt_mode_is_host_guest() ||
1909 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1910 PT_CAP_topa_output) &&
1911 !intel_pt_validate_cap(vmx->pt_desc.caps,
1912 PT_CAP_single_range_output)))
1914 msr_info->data = vmx->pt_desc.guest.output_base;
1916 case MSR_IA32_RTIT_OUTPUT_MASK:
1917 if (!vmx_pt_mode_is_host_guest() ||
1918 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1919 PT_CAP_topa_output) &&
1920 !intel_pt_validate_cap(vmx->pt_desc.caps,
1921 PT_CAP_single_range_output)))
1923 msr_info->data = vmx->pt_desc.guest.output_mask;
1925 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1926 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1927 if (!vmx_pt_mode_is_host_guest() ||
1928 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1929 PT_CAP_num_address_ranges)))
1932 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1934 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1937 if (!msr_info->host_initiated &&
1938 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1940 goto find_shared_msr;
1943 msr = find_msr_entry(vmx, msr_info->index);
1945 msr_info->data = msr->data;
1948 return kvm_get_msr_common(vcpu, msr_info);
1954 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
1957 #ifdef CONFIG_X86_64
1958 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
1961 return (unsigned long)data;
1965 * Writes msr value into the appropriate "register".
1966 * Returns 0 on success, non-0 otherwise.
1967 * Assumes vcpu_load() was already called.
1969 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1971 struct vcpu_vmx *vmx = to_vmx(vcpu);
1972 struct shared_msr_entry *msr;
1974 u32 msr_index = msr_info->index;
1975 u64 data = msr_info->data;
1978 switch (msr_index) {
1980 ret = kvm_set_msr_common(vcpu, msr_info);
1982 #ifdef CONFIG_X86_64
1984 vmx_segment_cache_clear(vmx);
1985 vmcs_writel(GUEST_FS_BASE, data);
1988 vmx_segment_cache_clear(vmx);
1989 vmcs_writel(GUEST_GS_BASE, data);
1991 case MSR_KERNEL_GS_BASE:
1992 vmx_write_guest_kernel_gs_base(vmx, data);
1995 case MSR_IA32_SYSENTER_CS:
1996 if (is_guest_mode(vcpu))
1997 get_vmcs12(vcpu)->guest_sysenter_cs = data;
1998 vmcs_write32(GUEST_SYSENTER_CS, data);
2000 case MSR_IA32_SYSENTER_EIP:
2001 if (is_guest_mode(vcpu)) {
2002 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2003 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2005 vmcs_writel(GUEST_SYSENTER_EIP, data);
2007 case MSR_IA32_SYSENTER_ESP:
2008 if (is_guest_mode(vcpu)) {
2009 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2010 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2012 vmcs_writel(GUEST_SYSENTER_ESP, data);
2014 case MSR_IA32_DEBUGCTLMSR:
2015 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2016 VM_EXIT_SAVE_DEBUG_CONTROLS)
2017 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2019 ret = kvm_set_msr_common(vcpu, msr_info);
2022 case MSR_IA32_BNDCFGS:
2023 if (!kvm_mpx_supported() ||
2024 (!msr_info->host_initiated &&
2025 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2027 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2028 (data & MSR_IA32_BNDCFGS_RSVD))
2030 vmcs_write64(GUEST_BNDCFGS, data);
2032 case MSR_IA32_UMWAIT_CONTROL:
2033 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2036 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2037 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2040 vmx->msr_ia32_umwait_control = data;
2042 case MSR_IA32_SPEC_CTRL:
2043 if (!msr_info->host_initiated &&
2044 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
2047 if (kvm_spec_ctrl_test_value(data))
2050 vmx->spec_ctrl = data;
2056 * When it's written (to non-zero) for the first time, pass
2060 * The handling of the MSR bitmap for L2 guests is done in
2061 * nested_vmx_prepare_msr_bitmap. We should not touch the
2062 * vmcs02.msr_bitmap here since it gets completely overwritten
2063 * in the merging. We update the vmcs01 here for L1 as well
2064 * since it will end up touching the MSR anyway now.
2066 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
2070 case MSR_IA32_TSX_CTRL:
2071 if (!msr_info->host_initiated &&
2072 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2074 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2076 goto find_shared_msr;
2077 case MSR_IA32_PRED_CMD:
2078 if (!msr_info->host_initiated &&
2079 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
2082 if (data & ~PRED_CMD_IBPB)
2084 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL))
2089 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2093 * When it's written (to non-zero) for the first time, pass
2097 * The handling of the MSR bitmap for L2 guests is done in
2098 * nested_vmx_prepare_msr_bitmap. We should not touch the
2099 * vmcs02.msr_bitmap here since it gets completely overwritten
2102 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
2105 case MSR_IA32_CR_PAT:
2106 if (!kvm_pat_valid(data))
2109 if (is_guest_mode(vcpu) &&
2110 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2111 get_vmcs12(vcpu)->guest_ia32_pat = data;
2113 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2114 vmcs_write64(GUEST_IA32_PAT, data);
2115 vcpu->arch.pat = data;
2118 ret = kvm_set_msr_common(vcpu, msr_info);
2120 case MSR_IA32_TSC_ADJUST:
2121 ret = kvm_set_msr_common(vcpu, msr_info);
2123 case MSR_IA32_MCG_EXT_CTL:
2124 if ((!msr_info->host_initiated &&
2125 !(to_vmx(vcpu)->msr_ia32_feature_control &
2126 FEAT_CTL_LMCE_ENABLED)) ||
2127 (data & ~MCG_EXT_CTL_LMCE_EN))
2129 vcpu->arch.mcg_ext_ctl = data;
2131 case MSR_IA32_FEAT_CTL:
2132 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2133 (to_vmx(vcpu)->msr_ia32_feature_control &
2134 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2136 vmx->msr_ia32_feature_control = data;
2137 if (msr_info->host_initiated && data == 0)
2138 vmx_leave_nested(vcpu);
2140 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2141 if (!msr_info->host_initiated)
2142 return 1; /* they are read-only */
2143 if (!nested_vmx_allowed(vcpu))
2145 return vmx_set_vmx_msr(vcpu, msr_index, data);
2146 case MSR_IA32_RTIT_CTL:
2147 if (!vmx_pt_mode_is_host_guest() ||
2148 vmx_rtit_ctl_check(vcpu, data) ||
2151 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2152 vmx->pt_desc.guest.ctl = data;
2153 pt_update_intercept_for_msr(vmx);
2155 case MSR_IA32_RTIT_STATUS:
2156 if (!pt_can_write_msr(vmx))
2158 if (data & MSR_IA32_RTIT_STATUS_MASK)
2160 vmx->pt_desc.guest.status = data;
2162 case MSR_IA32_RTIT_CR3_MATCH:
2163 if (!pt_can_write_msr(vmx))
2165 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2166 PT_CAP_cr3_filtering))
2168 vmx->pt_desc.guest.cr3_match = data;
2170 case MSR_IA32_RTIT_OUTPUT_BASE:
2171 if (!pt_can_write_msr(vmx))
2173 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2174 PT_CAP_topa_output) &&
2175 !intel_pt_validate_cap(vmx->pt_desc.caps,
2176 PT_CAP_single_range_output))
2178 if (!pt_output_base_valid(vcpu, data))
2180 vmx->pt_desc.guest.output_base = data;
2182 case MSR_IA32_RTIT_OUTPUT_MASK:
2183 if (!pt_can_write_msr(vmx))
2185 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2186 PT_CAP_topa_output) &&
2187 !intel_pt_validate_cap(vmx->pt_desc.caps,
2188 PT_CAP_single_range_output))
2190 vmx->pt_desc.guest.output_mask = data;
2192 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2193 if (!pt_can_write_msr(vmx))
2195 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2196 if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2197 PT_CAP_num_address_ranges))
2199 if (is_noncanonical_address(data, vcpu))
2202 vmx->pt_desc.guest.addr_b[index / 2] = data;
2204 vmx->pt_desc.guest.addr_a[index / 2] = data;
2207 if (!msr_info->host_initiated &&
2208 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2210 /* Check reserved bit, higher 32 bits should be zero */
2211 if ((data >> 32) != 0)
2213 goto find_shared_msr;
2217 msr = find_msr_entry(vmx, msr_index);
2219 ret = vmx_set_guest_msr(vmx, msr, data);
2221 ret = kvm_set_msr_common(vcpu, msr_info);
2227 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2229 unsigned long guest_owned_bits;
2231 kvm_register_mark_available(vcpu, reg);
2235 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2238 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2240 case VCPU_EXREG_PDPTR:
2242 ept_save_pdptrs(vcpu);
2244 case VCPU_EXREG_CR0:
2245 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2247 vcpu->arch.cr0 &= ~guest_owned_bits;
2248 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2250 case VCPU_EXREG_CR3:
2251 if (is_unrestricted_guest(vcpu) ||
2252 (enable_ept && is_paging(vcpu)))
2253 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2255 case VCPU_EXREG_CR4:
2256 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2258 vcpu->arch.cr4 &= ~guest_owned_bits;
2259 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2267 static __init int cpu_has_kvm_support(void)
2269 return cpu_has_vmx();
2272 static __init int vmx_disabled_by_bios(void)
2274 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2275 !boot_cpu_has(X86_FEATURE_VMX);
2278 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2282 cr4_set_bits(X86_CR4_VMXE);
2283 intel_pt_handle_vmx(1);
2285 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2286 _ASM_EXTABLE(1b, %l[fault])
2287 : : [vmxon_pointer] "m"(vmxon_pointer)
2292 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2293 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2294 intel_pt_handle_vmx(0);
2295 cr4_clear_bits(X86_CR4_VMXE);
2300 static int hardware_enable(void)
2302 int cpu = raw_smp_processor_id();
2303 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2306 if (cr4_read_shadow() & X86_CR4_VMXE)
2310 * This can happen if we hot-added a CPU but failed to allocate
2311 * VP assist page for it.
2313 if (static_branch_unlikely(&enable_evmcs) &&
2314 !hv_get_vp_assist_page(cpu))
2317 r = kvm_cpu_vmxon(phys_addr);
2327 static void vmclear_local_loaded_vmcss(void)
2329 int cpu = raw_smp_processor_id();
2330 struct loaded_vmcs *v, *n;
2332 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2333 loaded_vmcss_on_cpu_link)
2334 __loaded_vmcs_clear(v);
2338 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2341 static void kvm_cpu_vmxoff(void)
2343 asm volatile (__ex("vmxoff"));
2345 intel_pt_handle_vmx(0);
2346 cr4_clear_bits(X86_CR4_VMXE);
2349 static void hardware_disable(void)
2351 vmclear_local_loaded_vmcss();
2356 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2357 * directly instead of going through cpu_has(), to ensure KVM is trapping
2358 * ENCLS whenever it's supported in hardware. It does not matter whether
2359 * the host OS supports or has enabled SGX.
2361 static bool cpu_has_sgx(void)
2363 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2366 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2367 u32 msr, u32 *result)
2369 u32 vmx_msr_low, vmx_msr_high;
2370 u32 ctl = ctl_min | ctl_opt;
2372 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2374 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2375 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2377 /* Ensure minimum (required) set of control bits are supported. */
2385 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2386 struct vmx_capability *vmx_cap)
2388 u32 vmx_msr_low, vmx_msr_high;
2389 u32 min, opt, min2, opt2;
2390 u32 _pin_based_exec_control = 0;
2391 u32 _cpu_based_exec_control = 0;
2392 u32 _cpu_based_2nd_exec_control = 0;
2393 u32 _vmexit_control = 0;
2394 u32 _vmentry_control = 0;
2396 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2397 min = CPU_BASED_HLT_EXITING |
2398 #ifdef CONFIG_X86_64
2399 CPU_BASED_CR8_LOAD_EXITING |
2400 CPU_BASED_CR8_STORE_EXITING |
2402 CPU_BASED_CR3_LOAD_EXITING |
2403 CPU_BASED_CR3_STORE_EXITING |
2404 CPU_BASED_UNCOND_IO_EXITING |
2405 CPU_BASED_MOV_DR_EXITING |
2406 CPU_BASED_USE_TSC_OFFSETTING |
2407 CPU_BASED_MWAIT_EXITING |
2408 CPU_BASED_MONITOR_EXITING |
2409 CPU_BASED_INVLPG_EXITING |
2410 CPU_BASED_RDPMC_EXITING;
2412 opt = CPU_BASED_TPR_SHADOW |
2413 CPU_BASED_USE_MSR_BITMAPS |
2414 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2415 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2416 &_cpu_based_exec_control) < 0)
2418 #ifdef CONFIG_X86_64
2419 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2420 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2421 ~CPU_BASED_CR8_STORE_EXITING;
2423 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2425 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2426 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2427 SECONDARY_EXEC_WBINVD_EXITING |
2428 SECONDARY_EXEC_ENABLE_VPID |
2429 SECONDARY_EXEC_ENABLE_EPT |
2430 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2431 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2432 SECONDARY_EXEC_DESC |
2433 SECONDARY_EXEC_ENABLE_RDTSCP |
2434 SECONDARY_EXEC_ENABLE_INVPCID |
2435 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2436 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2437 SECONDARY_EXEC_SHADOW_VMCS |
2438 SECONDARY_EXEC_XSAVES |
2439 SECONDARY_EXEC_RDSEED_EXITING |
2440 SECONDARY_EXEC_RDRAND_EXITING |
2441 SECONDARY_EXEC_ENABLE_PML |
2442 SECONDARY_EXEC_TSC_SCALING |
2443 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2444 SECONDARY_EXEC_PT_USE_GPA |
2445 SECONDARY_EXEC_PT_CONCEAL_VMX |
2446 SECONDARY_EXEC_ENABLE_VMFUNC;
2448 opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2449 if (adjust_vmx_controls(min2, opt2,
2450 MSR_IA32_VMX_PROCBASED_CTLS2,
2451 &_cpu_based_2nd_exec_control) < 0)
2454 #ifndef CONFIG_X86_64
2455 if (!(_cpu_based_2nd_exec_control &
2456 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2457 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2460 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2461 _cpu_based_2nd_exec_control &= ~(
2462 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2463 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2464 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2466 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2467 &vmx_cap->ept, &vmx_cap->vpid);
2469 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2470 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2472 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2473 CPU_BASED_CR3_STORE_EXITING |
2474 CPU_BASED_INVLPG_EXITING);
2475 } else if (vmx_cap->ept) {
2477 pr_warn_once("EPT CAP should not exist if not support "
2478 "1-setting enable EPT VM-execution control\n");
2480 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2483 pr_warn_once("VPID CAP should not exist if not support "
2484 "1-setting enable VPID VM-execution control\n");
2487 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2488 #ifdef CONFIG_X86_64
2489 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2491 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2492 VM_EXIT_LOAD_IA32_PAT |
2493 VM_EXIT_LOAD_IA32_EFER |
2494 VM_EXIT_CLEAR_BNDCFGS |
2495 VM_EXIT_PT_CONCEAL_PIP |
2496 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2497 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2498 &_vmexit_control) < 0)
2501 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2502 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2503 PIN_BASED_VMX_PREEMPTION_TIMER;
2504 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2505 &_pin_based_exec_control) < 0)
2508 if (cpu_has_broken_vmx_preemption_timer())
2509 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2510 if (!(_cpu_based_2nd_exec_control &
2511 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2512 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2514 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2515 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2516 VM_ENTRY_LOAD_IA32_PAT |
2517 VM_ENTRY_LOAD_IA32_EFER |
2518 VM_ENTRY_LOAD_BNDCFGS |
2519 VM_ENTRY_PT_CONCEAL_PIP |
2520 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2521 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2522 &_vmentry_control) < 0)
2526 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2527 * can't be used due to an errata where VM Exit may incorrectly clear
2528 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2529 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2531 if (boot_cpu_data.x86 == 0x6) {
2532 switch (boot_cpu_data.x86_model) {
2533 case 26: /* AAK155 */
2534 case 30: /* AAP115 */
2535 case 37: /* AAT100 */
2536 case 44: /* BC86,AAY89,BD102 */
2538 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2539 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2540 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2541 "does not work properly. Using workaround\n");
2549 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2551 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2552 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2555 #ifdef CONFIG_X86_64
2556 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2557 if (vmx_msr_high & (1u<<16))
2561 /* Require Write-Back (WB) memory type for VMCS accesses. */
2562 if (((vmx_msr_high >> 18) & 15) != 6)
2565 vmcs_conf->size = vmx_msr_high & 0x1fff;
2566 vmcs_conf->order = get_order(vmcs_conf->size);
2567 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2569 vmcs_conf->revision_id = vmx_msr_low;
2571 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2572 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2573 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2574 vmcs_conf->vmexit_ctrl = _vmexit_control;
2575 vmcs_conf->vmentry_ctrl = _vmentry_control;
2577 if (static_branch_unlikely(&enable_evmcs))
2578 evmcs_sanitize_exec_ctrls(vmcs_conf);
2583 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2585 int node = cpu_to_node(cpu);
2589 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2592 vmcs = page_address(pages);
2593 memset(vmcs, 0, vmcs_config.size);
2595 /* KVM supports Enlightened VMCS v1 only */
2596 if (static_branch_unlikely(&enable_evmcs))
2597 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2599 vmcs->hdr.revision_id = vmcs_config.revision_id;
2602 vmcs->hdr.shadow_vmcs = 1;
2606 void free_vmcs(struct vmcs *vmcs)
2608 free_pages((unsigned long)vmcs, vmcs_config.order);
2612 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2614 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2616 if (!loaded_vmcs->vmcs)
2618 loaded_vmcs_clear(loaded_vmcs);
2619 free_vmcs(loaded_vmcs->vmcs);
2620 loaded_vmcs->vmcs = NULL;
2621 if (loaded_vmcs->msr_bitmap)
2622 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2623 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2626 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2628 loaded_vmcs->vmcs = alloc_vmcs(false);
2629 if (!loaded_vmcs->vmcs)
2632 vmcs_clear(loaded_vmcs->vmcs);
2634 loaded_vmcs->shadow_vmcs = NULL;
2635 loaded_vmcs->hv_timer_soft_disabled = false;
2636 loaded_vmcs->cpu = -1;
2637 loaded_vmcs->launched = 0;
2639 if (cpu_has_vmx_msr_bitmap()) {
2640 loaded_vmcs->msr_bitmap = (unsigned long *)
2641 __get_free_page(GFP_KERNEL_ACCOUNT);
2642 if (!loaded_vmcs->msr_bitmap)
2644 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2646 if (IS_ENABLED(CONFIG_HYPERV) &&
2647 static_branch_unlikely(&enable_evmcs) &&
2648 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2649 struct hv_enlightened_vmcs *evmcs =
2650 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2652 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2656 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2657 memset(&loaded_vmcs->controls_shadow, 0,
2658 sizeof(struct vmcs_controls_shadow));
2663 free_loaded_vmcs(loaded_vmcs);
2667 static void free_kvm_area(void)
2671 for_each_possible_cpu(cpu) {
2672 free_vmcs(per_cpu(vmxarea, cpu));
2673 per_cpu(vmxarea, cpu) = NULL;
2677 static __init int alloc_kvm_area(void)
2681 for_each_possible_cpu(cpu) {
2684 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2691 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2692 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2693 * revision_id reported by MSR_IA32_VMX_BASIC.
2695 * However, even though not explicitly documented by
2696 * TLFS, VMXArea passed as VMXON argument should
2697 * still be marked with revision_id reported by
2700 if (static_branch_unlikely(&enable_evmcs))
2701 vmcs->hdr.revision_id = vmcs_config.revision_id;
2703 per_cpu(vmxarea, cpu) = vmcs;
2708 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2709 struct kvm_segment *save)
2711 if (!emulate_invalid_guest_state) {
2713 * CS and SS RPL should be equal during guest entry according
2714 * to VMX spec, but in reality it is not always so. Since vcpu
2715 * is in the middle of the transition from real mode to
2716 * protected mode it is safe to assume that RPL 0 is a good
2719 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2720 save->selector &= ~SEGMENT_RPL_MASK;
2721 save->dpl = save->selector & SEGMENT_RPL_MASK;
2724 vmx_set_segment(vcpu, save, seg);
2727 static void enter_pmode(struct kvm_vcpu *vcpu)
2729 unsigned long flags;
2730 struct vcpu_vmx *vmx = to_vmx(vcpu);
2733 * Update real mode segment cache. It may be not up-to-date if sement
2734 * register was written while vcpu was in a guest mode.
2736 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2737 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2738 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2739 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2740 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2741 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2743 vmx->rmode.vm86_active = 0;
2745 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2747 flags = vmcs_readl(GUEST_RFLAGS);
2748 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2749 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2750 vmcs_writel(GUEST_RFLAGS, flags);
2752 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2753 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2755 update_exception_bitmap(vcpu);
2757 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2758 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2759 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2760 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2761 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2762 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2765 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2767 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2768 struct kvm_segment var = *save;
2771 if (seg == VCPU_SREG_CS)
2774 if (!emulate_invalid_guest_state) {
2775 var.selector = var.base >> 4;
2776 var.base = var.base & 0xffff0;
2786 if (save->base & 0xf)
2787 printk_once(KERN_WARNING "kvm: segment base is not "
2788 "paragraph aligned when entering "
2789 "protected mode (seg=%d)", seg);
2792 vmcs_write16(sf->selector, var.selector);
2793 vmcs_writel(sf->base, var.base);
2794 vmcs_write32(sf->limit, var.limit);
2795 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2798 static void enter_rmode(struct kvm_vcpu *vcpu)
2800 unsigned long flags;
2801 struct vcpu_vmx *vmx = to_vmx(vcpu);
2802 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2804 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2805 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2806 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2807 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2808 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2809 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2810 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2812 vmx->rmode.vm86_active = 1;
2815 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2816 * vcpu. Warn the user that an update is overdue.
2818 if (!kvm_vmx->tss_addr)
2819 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2820 "called before entering vcpu\n");
2822 vmx_segment_cache_clear(vmx);
2824 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2825 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2826 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2828 flags = vmcs_readl(GUEST_RFLAGS);
2829 vmx->rmode.save_rflags = flags;
2831 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2833 vmcs_writel(GUEST_RFLAGS, flags);
2834 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2835 update_exception_bitmap(vcpu);
2837 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2838 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2839 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2840 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2841 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2842 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2844 kvm_mmu_reset_context(vcpu);
2847 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2849 struct vcpu_vmx *vmx = to_vmx(vcpu);
2850 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2855 vcpu->arch.efer = efer;
2856 if (efer & EFER_LMA) {
2857 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2860 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2862 msr->data = efer & ~EFER_LME;
2867 #ifdef CONFIG_X86_64
2869 static void enter_lmode(struct kvm_vcpu *vcpu)
2873 vmx_segment_cache_clear(to_vmx(vcpu));
2875 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2876 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2877 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2879 vmcs_write32(GUEST_TR_AR_BYTES,
2880 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2881 | VMX_AR_TYPE_BUSY_64_TSS);
2883 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2886 static void exit_lmode(struct kvm_vcpu *vcpu)
2888 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2889 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2894 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
2896 struct vcpu_vmx *vmx = to_vmx(vcpu);
2899 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
2900 * the CPU is not required to invalidate guest-physical mappings on
2901 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
2902 * associated with the root EPT structure and not any particular VPID
2903 * (INVVPID also isn't required to invalidate guest-physical mappings).
2907 } else if (enable_vpid) {
2908 if (cpu_has_vmx_invvpid_global()) {
2909 vpid_sync_vcpu_global();
2911 vpid_sync_vcpu_single(vmx->vpid);
2912 vpid_sync_vcpu_single(vmx->nested.vpid02);
2917 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
2919 struct kvm_mmu *mmu = vcpu->arch.mmu;
2920 u64 root_hpa = mmu->root_hpa;
2922 /* No flush required if the current context is invalid. */
2923 if (!VALID_PAGE(root_hpa))
2927 ept_sync_context(construct_eptp(vcpu, root_hpa,
2928 mmu->shadow_root_level));
2929 else if (!is_guest_mode(vcpu))
2930 vpid_sync_context(to_vmx(vcpu)->vpid);
2932 vpid_sync_context(nested_get_vpid02(vcpu));
2935 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2938 * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
2939 * vmx_flush_tlb_guest() for an explanation of why this is ok.
2941 vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
2944 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
2947 * vpid_sync_context() is a nop if vmx->vpid==0, e.g. if enable_vpid==0
2948 * or a vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit
2949 * are required to flush GVA->{G,H}PA mappings from the TLB if vpid is
2950 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
2951 * i.e. no explicit INVVPID is necessary.
2953 vpid_sync_context(to_vmx(vcpu)->vpid);
2956 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
2958 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2960 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
2963 if (is_pae_paging(vcpu)) {
2964 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2965 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2966 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2967 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2971 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2973 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2975 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
2978 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2979 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2980 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2981 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2983 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
2986 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2988 struct kvm_vcpu *vcpu)
2990 struct vcpu_vmx *vmx = to_vmx(vcpu);
2992 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
2993 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
2994 if (!(cr0 & X86_CR0_PG)) {
2995 /* From paging/starting to nonpaging */
2996 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
2997 CPU_BASED_CR3_STORE_EXITING);
2998 vcpu->arch.cr0 = cr0;
2999 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3000 } else if (!is_paging(vcpu)) {
3001 /* From nonpaging to paging */
3002 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3003 CPU_BASED_CR3_STORE_EXITING);
3004 vcpu->arch.cr0 = cr0;
3005 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3008 if (!(cr0 & X86_CR0_WP))
3009 *hw_cr0 &= ~X86_CR0_WP;
3012 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3014 struct vcpu_vmx *vmx = to_vmx(vcpu);
3015 unsigned long hw_cr0;
3017 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3018 if (is_unrestricted_guest(vcpu))
3019 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3021 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3023 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3026 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3030 #ifdef CONFIG_X86_64
3031 if (vcpu->arch.efer & EFER_LME) {
3032 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3034 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3039 if (enable_ept && !is_unrestricted_guest(vcpu))
3040 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3042 vmcs_writel(CR0_READ_SHADOW, cr0);
3043 vmcs_writel(GUEST_CR0, hw_cr0);
3044 vcpu->arch.cr0 = cr0;
3045 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3047 /* depends on vcpu->arch.cr0 to be set to a new value */
3048 vmx->emulation_required = emulation_required(vcpu);
3051 static int vmx_get_max_tdp_level(void)
3053 if (cpu_has_vmx_ept_5levels())
3058 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa,
3061 u64 eptp = VMX_EPTP_MT_WB;
3063 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3065 if (enable_ept_ad_bits &&
3066 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3067 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3068 eptp |= (root_hpa & PAGE_MASK);
3073 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, unsigned long pgd,
3076 struct kvm *kvm = vcpu->kvm;
3077 bool update_guest_cr3 = true;
3078 unsigned long guest_cr3;
3082 eptp = construct_eptp(vcpu, pgd, pgd_level);
3083 vmcs_write64(EPT_POINTER, eptp);
3085 if (kvm_x86_ops.tlb_remote_flush) {
3086 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3087 to_vmx(vcpu)->ept_pointer = eptp;
3088 to_kvm_vmx(kvm)->ept_pointers_match
3089 = EPT_POINTERS_CHECK;
3090 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3093 if (!enable_unrestricted_guest && !is_paging(vcpu))
3094 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3095 else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3096 guest_cr3 = vcpu->arch.cr3;
3097 else /* vmcs01.GUEST_CR3 is already up-to-date. */
3098 update_guest_cr3 = false;
3099 vmx_ept_load_pdptrs(vcpu);
3104 if (update_guest_cr3)
3105 vmcs_writel(GUEST_CR3, guest_cr3);
3108 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3110 struct vcpu_vmx *vmx = to_vmx(vcpu);
3112 * Pass through host's Machine Check Enable value to hw_cr4, which
3113 * is in force while we are in guest mode. Do not let guests control
3114 * this bit, even if host CR4.MCE == 0.
3116 unsigned long hw_cr4;
3118 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3119 if (is_unrestricted_guest(vcpu))
3120 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3121 else if (vmx->rmode.vm86_active)
3122 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3124 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3126 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3127 if (cr4 & X86_CR4_UMIP) {
3128 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3129 hw_cr4 &= ~X86_CR4_UMIP;
3130 } else if (!is_guest_mode(vcpu) ||
3131 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3132 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3136 if (cr4 & X86_CR4_VMXE) {
3138 * To use VMXON (and later other VMX instructions), a guest
3139 * must first be able to turn on cr4.VMXE (see handle_vmon()).
3140 * So basically the check on whether to allow nested VMX
3141 * is here. We operate under the default treatment of SMM,
3142 * so VMX cannot be enabled under SMM.
3144 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
3148 if (vmx->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3151 vcpu->arch.cr4 = cr4;
3152 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3154 if (!is_unrestricted_guest(vcpu)) {
3156 if (!is_paging(vcpu)) {
3157 hw_cr4 &= ~X86_CR4_PAE;
3158 hw_cr4 |= X86_CR4_PSE;
3159 } else if (!(cr4 & X86_CR4_PAE)) {
3160 hw_cr4 &= ~X86_CR4_PAE;
3165 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3166 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3167 * to be manually disabled when guest switches to non-paging
3170 * If !enable_unrestricted_guest, the CPU is always running
3171 * with CR0.PG=1 and CR4 needs to be modified.
3172 * If enable_unrestricted_guest, the CPU automatically
3173 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3175 if (!is_paging(vcpu))
3176 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3179 vmcs_writel(CR4_READ_SHADOW, cr4);
3180 vmcs_writel(GUEST_CR4, hw_cr4);
3184 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3186 struct vcpu_vmx *vmx = to_vmx(vcpu);
3189 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3190 *var = vmx->rmode.segs[seg];
3191 if (seg == VCPU_SREG_TR
3192 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3194 var->base = vmx_read_guest_seg_base(vmx, seg);
3195 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3198 var->base = vmx_read_guest_seg_base(vmx, seg);
3199 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3200 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3201 ar = vmx_read_guest_seg_ar(vmx, seg);
3202 var->unusable = (ar >> 16) & 1;
3203 var->type = ar & 15;
3204 var->s = (ar >> 4) & 1;
3205 var->dpl = (ar >> 5) & 3;
3207 * Some userspaces do not preserve unusable property. Since usable
3208 * segment has to be present according to VMX spec we can use present
3209 * property to amend userspace bug by making unusable segment always
3210 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3211 * segment as unusable.
3213 var->present = !var->unusable;
3214 var->avl = (ar >> 12) & 1;
3215 var->l = (ar >> 13) & 1;
3216 var->db = (ar >> 14) & 1;
3217 var->g = (ar >> 15) & 1;
3220 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3222 struct kvm_segment s;
3224 if (to_vmx(vcpu)->rmode.vm86_active) {
3225 vmx_get_segment(vcpu, &s, seg);
3228 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3231 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3233 struct vcpu_vmx *vmx = to_vmx(vcpu);
3235 if (unlikely(vmx->rmode.vm86_active))
3238 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3239 return VMX_AR_DPL(ar);
3243 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3247 if (var->unusable || !var->present)
3250 ar = var->type & 15;
3251 ar |= (var->s & 1) << 4;
3252 ar |= (var->dpl & 3) << 5;
3253 ar |= (var->present & 1) << 7;
3254 ar |= (var->avl & 1) << 12;
3255 ar |= (var->l & 1) << 13;
3256 ar |= (var->db & 1) << 14;
3257 ar |= (var->g & 1) << 15;
3263 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3265 struct vcpu_vmx *vmx = to_vmx(vcpu);
3266 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3268 vmx_segment_cache_clear(vmx);
3270 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3271 vmx->rmode.segs[seg] = *var;
3272 if (seg == VCPU_SREG_TR)
3273 vmcs_write16(sf->selector, var->selector);
3275 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3279 vmcs_writel(sf->base, var->base);
3280 vmcs_write32(sf->limit, var->limit);
3281 vmcs_write16(sf->selector, var->selector);
3284 * Fix the "Accessed" bit in AR field of segment registers for older
3286 * IA32 arch specifies that at the time of processor reset the
3287 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3288 * is setting it to 0 in the userland code. This causes invalid guest
3289 * state vmexit when "unrestricted guest" mode is turned on.
3290 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3291 * tree. Newer qemu binaries with that qemu fix would not need this
3294 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3295 var->type |= 0x1; /* Accessed */
3297 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3300 vmx->emulation_required = emulation_required(vcpu);
3303 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3305 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3307 *db = (ar >> 14) & 1;
3308 *l = (ar >> 13) & 1;
3311 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3313 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3314 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3317 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3319 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3320 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3323 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3325 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3326 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3329 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3331 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3332 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3335 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3337 struct kvm_segment var;
3340 vmx_get_segment(vcpu, &var, seg);
3342 if (seg == VCPU_SREG_CS)
3344 ar = vmx_segment_access_rights(&var);
3346 if (var.base != (var.selector << 4))
3348 if (var.limit != 0xffff)
3356 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3358 struct kvm_segment cs;
3359 unsigned int cs_rpl;
3361 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3362 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3366 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3370 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3371 if (cs.dpl > cs_rpl)
3374 if (cs.dpl != cs_rpl)
3380 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3384 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3386 struct kvm_segment ss;
3387 unsigned int ss_rpl;
3389 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3390 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3394 if (ss.type != 3 && ss.type != 7)
3398 if (ss.dpl != ss_rpl) /* DPL != RPL */
3406 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3408 struct kvm_segment var;
3411 vmx_get_segment(vcpu, &var, seg);
3412 rpl = var.selector & SEGMENT_RPL_MASK;
3420 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3421 if (var.dpl < rpl) /* DPL < RPL */
3425 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3431 static bool tr_valid(struct kvm_vcpu *vcpu)
3433 struct kvm_segment tr;
3435 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3439 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3441 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3449 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3451 struct kvm_segment ldtr;
3453 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3457 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3467 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3469 struct kvm_segment cs, ss;
3471 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3472 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3474 return ((cs.selector & SEGMENT_RPL_MASK) ==
3475 (ss.selector & SEGMENT_RPL_MASK));
3479 * Check if guest state is valid. Returns true if valid, false if
3481 * We assume that registers are always usable
3483 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3485 if (is_unrestricted_guest(vcpu))
3488 /* real mode guest state checks */
3489 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3490 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3492 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3494 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3496 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3498 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3500 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3503 /* protected mode guest state checks */
3504 if (!cs_ss_rpl_check(vcpu))
3506 if (!code_segment_valid(vcpu))
3508 if (!stack_segment_valid(vcpu))
3510 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3512 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3514 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3516 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3518 if (!tr_valid(vcpu))
3520 if (!ldtr_valid(vcpu))
3524 * - Add checks on RIP
3525 * - Add checks on RFLAGS
3531 static int init_rmode_tss(struct kvm *kvm)
3537 idx = srcu_read_lock(&kvm->srcu);
3538 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3539 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3542 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3543 r = kvm_write_guest_page(kvm, fn++, &data,
3544 TSS_IOPB_BASE_OFFSET, sizeof(u16));
3547 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3550 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3554 r = kvm_write_guest_page(kvm, fn, &data,
3555 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3558 srcu_read_unlock(&kvm->srcu, idx);
3562 static int init_rmode_identity_map(struct kvm *kvm)
3564 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3566 kvm_pfn_t identity_map_pfn;
3569 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3570 mutex_lock(&kvm->slots_lock);
3572 if (likely(kvm_vmx->ept_identity_pagetable_done))
3575 if (!kvm_vmx->ept_identity_map_addr)
3576 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3577 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3579 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3580 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3584 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3587 /* Set up identity-mapping pagetable for EPT in real mode */
3588 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3589 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3590 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3591 r = kvm_write_guest_page(kvm, identity_map_pfn,
3592 &tmp, i * sizeof(tmp), sizeof(tmp));
3596 kvm_vmx->ept_identity_pagetable_done = true;
3599 mutex_unlock(&kvm->slots_lock);
3603 static void seg_setup(int seg)
3605 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3608 vmcs_write16(sf->selector, 0);
3609 vmcs_writel(sf->base, 0);
3610 vmcs_write32(sf->limit, 0xffff);
3612 if (seg == VCPU_SREG_CS)
3613 ar |= 0x08; /* code segment */
3615 vmcs_write32(sf->ar_bytes, ar);
3618 static int alloc_apic_access_page(struct kvm *kvm)
3623 mutex_lock(&kvm->slots_lock);
3624 if (kvm->arch.apic_access_page_done)
3626 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3627 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3631 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3632 if (is_error_page(page)) {
3638 * Do not pin the page in memory, so that memory hot-unplug
3639 * is able to migrate it.
3642 kvm->arch.apic_access_page_done = true;
3644 mutex_unlock(&kvm->slots_lock);
3648 int allocate_vpid(void)
3654 spin_lock(&vmx_vpid_lock);
3655 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3656 if (vpid < VMX_NR_VPIDS)
3657 __set_bit(vpid, vmx_vpid_bitmap);
3660 spin_unlock(&vmx_vpid_lock);
3664 void free_vpid(int vpid)
3666 if (!enable_vpid || vpid == 0)
3668 spin_lock(&vmx_vpid_lock);
3669 __clear_bit(vpid, vmx_vpid_bitmap);
3670 spin_unlock(&vmx_vpid_lock);
3673 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3676 int f = sizeof(unsigned long);
3678 if (!cpu_has_vmx_msr_bitmap())
3681 if (static_branch_unlikely(&enable_evmcs))
3682 evmcs_touch_msr_bitmap();
3685 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3686 * have the write-low and read-high bitmap offsets the wrong way round.
3687 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3689 if (msr <= 0x1fff) {
3690 if (type & MSR_TYPE_R)
3692 __clear_bit(msr, msr_bitmap + 0x000 / f);
3694 if (type & MSR_TYPE_W)
3696 __clear_bit(msr, msr_bitmap + 0x800 / f);
3698 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3700 if (type & MSR_TYPE_R)
3702 __clear_bit(msr, msr_bitmap + 0x400 / f);
3704 if (type & MSR_TYPE_W)
3706 __clear_bit(msr, msr_bitmap + 0xc00 / f);
3711 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3714 int f = sizeof(unsigned long);
3716 if (!cpu_has_vmx_msr_bitmap())
3719 if (static_branch_unlikely(&enable_evmcs))
3720 evmcs_touch_msr_bitmap();
3723 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3724 * have the write-low and read-high bitmap offsets the wrong way round.
3725 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3727 if (msr <= 0x1fff) {
3728 if (type & MSR_TYPE_R)
3730 __set_bit(msr, msr_bitmap + 0x000 / f);
3732 if (type & MSR_TYPE_W)
3734 __set_bit(msr, msr_bitmap + 0x800 / f);
3736 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3738 if (type & MSR_TYPE_R)
3740 __set_bit(msr, msr_bitmap + 0x400 / f);
3742 if (type & MSR_TYPE_W)
3744 __set_bit(msr, msr_bitmap + 0xc00 / f);
3749 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3750 u32 msr, int type, bool value)
3753 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3755 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3758 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3762 if (cpu_has_secondary_exec_ctrls() &&
3763 (secondary_exec_controls_get(to_vmx(vcpu)) &
3764 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3765 mode |= MSR_BITMAP_MODE_X2APIC;
3766 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3767 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3773 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3778 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3779 unsigned word = msr / BITS_PER_LONG;
3780 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3781 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3784 if (mode & MSR_BITMAP_MODE_X2APIC) {
3786 * TPR reads and writes can be virtualized even if virtual interrupt
3787 * delivery is not in use.
3789 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3790 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3791 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3792 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3793 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3798 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3800 struct vcpu_vmx *vmx = to_vmx(vcpu);
3801 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3802 u8 mode = vmx_msr_bitmap_mode(vcpu);
3803 u8 changed = mode ^ vmx->msr_bitmap_mode;
3808 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3809 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3811 vmx->msr_bitmap_mode = mode;
3814 void pt_update_intercept_for_msr(struct vcpu_vmx *vmx)
3816 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3817 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3820 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_STATUS,
3822 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_BASE,
3824 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_MASK,
3826 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_CR3_MATCH,
3828 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3829 vmx_set_intercept_for_msr(msr_bitmap,
3830 MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3831 vmx_set_intercept_for_msr(msr_bitmap,
3832 MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3836 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3838 struct vcpu_vmx *vmx = to_vmx(vcpu);
3843 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3844 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3845 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3848 rvi = vmx_get_rvi();
3850 vapic_page = vmx->nested.virtual_apic_map.hva;
3851 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3853 return ((rvi & 0xf0) > (vppr & 0xf0));
3856 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3860 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3862 if (vcpu->mode == IN_GUEST_MODE) {
3864 * The vector of interrupt to be delivered to vcpu had
3865 * been set in PIR before this function.
3867 * Following cases will be reached in this block, and
3868 * we always send a notification event in all cases as
3871 * Case 1: vcpu keeps in non-root mode. Sending a
3872 * notification event posts the interrupt to vcpu.
3874 * Case 2: vcpu exits to root mode and is still
3875 * runnable. PIR will be synced to vIRR before the
3876 * next vcpu entry. Sending a notification event in
3877 * this case has no effect, as vcpu is not in root
3880 * Case 3: vcpu exits to root mode and is blocked.
3881 * vcpu_block() has already synced PIR to vIRR and
3882 * never blocks vcpu if vIRR is not cleared. Therefore,
3883 * a blocked vcpu here does not wait for any requested
3884 * interrupts in PIR, and sending a notification event
3885 * which has no effect is safe here.
3888 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3895 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3898 struct vcpu_vmx *vmx = to_vmx(vcpu);
3900 if (is_guest_mode(vcpu) &&
3901 vector == vmx->nested.posted_intr_nv) {
3903 * If a posted intr is not recognized by hardware,
3904 * we will accomplish it in the next vmentry.
3906 vmx->nested.pi_pending = true;
3907 kvm_make_request(KVM_REQ_EVENT, vcpu);
3908 /* the PIR and ON have been set by L1. */
3909 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3910 kvm_vcpu_kick(vcpu);
3916 * Send interrupt to vcpu via posted interrupt way.
3917 * 1. If target vcpu is running(non-root mode), send posted interrupt
3918 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3919 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3920 * interrupt from PIR in next vmentry.
3922 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3924 struct vcpu_vmx *vmx = to_vmx(vcpu);
3927 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3931 if (!vcpu->arch.apicv_active)
3934 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3937 /* If a previous notification has sent the IPI, nothing to do. */
3938 if (pi_test_and_set_on(&vmx->pi_desc))
3941 if (vcpu != kvm_get_running_vcpu() &&
3942 !kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3943 kvm_vcpu_kick(vcpu);
3949 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3950 * will not change in the lifetime of the guest.
3951 * Note that host-state that does change is set elsewhere. E.g., host-state
3952 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3954 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3958 unsigned long cr0, cr3, cr4;
3961 WARN_ON(cr0 & X86_CR0_TS);
3962 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
3965 * Save the most likely value for this task's CR3 in the VMCS.
3966 * We can't use __get_current_cr3_fast() because we're not atomic.
3969 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
3970 vmx->loaded_vmcs->host_state.cr3 = cr3;
3972 /* Save the most likely value for this task's CR4 in the VMCS. */
3973 cr4 = cr4_read_shadow();
3974 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
3975 vmx->loaded_vmcs->host_state.cr4 = cr4;
3977 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
3978 #ifdef CONFIG_X86_64
3980 * Load null selectors, so we can avoid reloading them in
3981 * vmx_prepare_switch_to_host(), in case userspace uses
3982 * the null selectors too (the expected case).
3984 vmcs_write16(HOST_DS_SELECTOR, 0);
3985 vmcs_write16(HOST_ES_SELECTOR, 0);
3987 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3988 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3990 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3991 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
3993 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
3995 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
3997 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3998 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3999 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4000 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4002 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4003 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4004 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4007 if (cpu_has_load_ia32_efer())
4008 vmcs_write64(HOST_IA32_EFER, host_efer);
4011 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4013 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS;
4015 vmx->vcpu.arch.cr4_guest_owned_bits &= ~X86_CR4_PGE;
4016 if (is_guest_mode(&vmx->vcpu))
4017 vmx->vcpu.arch.cr4_guest_owned_bits &=
4018 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
4019 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
4022 u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4024 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4026 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4027 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4030 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4032 if (!enable_preemption_timer)
4033 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4035 return pin_based_exec_ctrl;
4038 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4040 struct vcpu_vmx *vmx = to_vmx(vcpu);
4042 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4043 if (cpu_has_secondary_exec_ctrls()) {
4044 if (kvm_vcpu_apicv_active(vcpu))
4045 secondary_exec_controls_setbit(vmx,
4046 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4047 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4049 secondary_exec_controls_clearbit(vmx,
4050 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4051 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4054 if (cpu_has_vmx_msr_bitmap())
4055 vmx_update_msr_bitmap(vcpu);
4058 u32 vmx_exec_control(struct vcpu_vmx *vmx)
4060 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4062 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4063 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4065 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4066 exec_control &= ~CPU_BASED_TPR_SHADOW;
4067 #ifdef CONFIG_X86_64
4068 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4069 CPU_BASED_CR8_LOAD_EXITING;
4073 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4074 CPU_BASED_CR3_LOAD_EXITING |
4075 CPU_BASED_INVLPG_EXITING;
4076 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4077 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4078 CPU_BASED_MONITOR_EXITING);
4079 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4080 exec_control &= ~CPU_BASED_HLT_EXITING;
4081 return exec_control;
4085 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
4087 struct kvm_vcpu *vcpu = &vmx->vcpu;
4089 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4091 if (vmx_pt_mode_is_system())
4092 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4093 if (!cpu_need_virtualize_apic_accesses(vcpu))
4094 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4096 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4098 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4099 enable_unrestricted_guest = 0;
4101 if (!enable_unrestricted_guest)
4102 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4103 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4104 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4105 if (!kvm_vcpu_apicv_active(vcpu))
4106 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4107 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4108 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4110 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4111 * in vmx_set_cr4. */
4112 exec_control &= ~SECONDARY_EXEC_DESC;
4114 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4116 We can NOT enable shadow_vmcs here because we don't have yet
4119 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4122 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4124 if (cpu_has_vmx_xsaves()) {
4125 /* Exposing XSAVES only when XSAVE is exposed */
4126 bool xsaves_enabled =
4127 boot_cpu_has(X86_FEATURE_XSAVE) &&
4128 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4129 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4131 vcpu->arch.xsaves_enabled = xsaves_enabled;
4133 if (!xsaves_enabled)
4134 exec_control &= ~SECONDARY_EXEC_XSAVES;
4138 vmx->nested.msrs.secondary_ctls_high |=
4139 SECONDARY_EXEC_XSAVES;
4141 vmx->nested.msrs.secondary_ctls_high &=
4142 ~SECONDARY_EXEC_XSAVES;
4146 if (cpu_has_vmx_rdtscp()) {
4147 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
4148 if (!rdtscp_enabled)
4149 exec_control &= ~SECONDARY_EXEC_ENABLE_RDTSCP;
4153 vmx->nested.msrs.secondary_ctls_high |=
4154 SECONDARY_EXEC_ENABLE_RDTSCP;
4156 vmx->nested.msrs.secondary_ctls_high &=
4157 ~SECONDARY_EXEC_ENABLE_RDTSCP;
4162 * Expose INVPCID if and only if PCID is also exposed to the guest.
4163 * INVPCID takes a #UD when it's disabled in the VMCS, but a #GP or #PF
4164 * if CR4.PCIDE=0. Enumerating CPUID.INVPCID=1 would lead to incorrect
4165 * behavior from the guest perspective (it would expect #GP or #PF).
4167 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
4168 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
4170 if (cpu_has_vmx_invpcid()) {
4171 /* Exposing INVPCID only when PCID is exposed */
4172 bool invpcid_enabled =
4173 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID);
4175 if (!invpcid_enabled)
4176 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
4179 if (invpcid_enabled)
4180 vmx->nested.msrs.secondary_ctls_high |=
4181 SECONDARY_EXEC_ENABLE_INVPCID;
4183 vmx->nested.msrs.secondary_ctls_high &=
4184 ~SECONDARY_EXEC_ENABLE_INVPCID;
4188 if (cpu_has_vmx_rdrand()) {
4189 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
4191 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
4195 vmx->nested.msrs.secondary_ctls_high |=
4196 SECONDARY_EXEC_RDRAND_EXITING;
4198 vmx->nested.msrs.secondary_ctls_high &=
4199 ~SECONDARY_EXEC_RDRAND_EXITING;
4203 if (cpu_has_vmx_rdseed()) {
4204 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
4206 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
4210 vmx->nested.msrs.secondary_ctls_high |=
4211 SECONDARY_EXEC_RDSEED_EXITING;
4213 vmx->nested.msrs.secondary_ctls_high &=
4214 ~SECONDARY_EXEC_RDSEED_EXITING;
4218 if (cpu_has_vmx_waitpkg()) {
4219 bool waitpkg_enabled =
4220 guest_cpuid_has(vcpu, X86_FEATURE_WAITPKG);
4222 if (!waitpkg_enabled)
4223 exec_control &= ~SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4226 if (waitpkg_enabled)
4227 vmx->nested.msrs.secondary_ctls_high |=
4228 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4230 vmx->nested.msrs.secondary_ctls_high &=
4231 ~SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4235 vmx->secondary_exec_control = exec_control;
4238 static void ept_set_mmio_spte_mask(void)
4241 * EPT Misconfigurations can be generated if the value of bits 2:0
4242 * of an EPT paging-structure entry is 110b (write/execute).
4244 kvm_mmu_set_mmio_spte_mask(VMX_EPT_MISCONFIG_WX_VALUE, 0);
4247 #define VMX_XSS_EXIT_BITMAP 0
4250 * Noting that the initialization of Guest-state Area of VMCS is in
4253 static void init_vmcs(struct vcpu_vmx *vmx)
4256 nested_vmx_set_vmcs_shadowing_bitmap();
4258 if (cpu_has_vmx_msr_bitmap())
4259 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4261 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4264 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4266 exec_controls_set(vmx, vmx_exec_control(vmx));
4268 if (cpu_has_secondary_exec_ctrls()) {
4269 vmx_compute_secondary_exec_control(vmx);
4270 secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
4273 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4274 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4275 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4276 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4277 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4279 vmcs_write16(GUEST_INTR_STATUS, 0);
4281 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4282 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4285 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4286 vmcs_write32(PLE_GAP, ple_gap);
4287 vmx->ple_window = ple_window;
4288 vmx->ple_window_dirty = true;
4291 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4292 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4293 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4295 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4296 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4297 vmx_set_constant_host_state(vmx);
4298 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4299 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4301 if (cpu_has_vmx_vmfunc())
4302 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4304 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4305 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4306 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4307 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4308 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4310 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4311 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4313 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4315 /* 22.2.1, 20.8.1 */
4316 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4318 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4319 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4321 set_cr4_guest_host_mask(vmx);
4324 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4326 if (cpu_has_vmx_xsaves())
4327 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4330 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4331 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4334 if (cpu_has_vmx_encls_vmexit())
4335 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
4337 if (vmx_pt_mode_is_host_guest()) {
4338 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4339 /* Bit[6~0] are forced to 1, writes are ignored. */
4340 vmx->pt_desc.guest.output_mask = 0x7F;
4341 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4345 * If EPT is enabled, #PF is only trapped if MAXPHYADDR is mismatched
4346 * between guest and host. In that case we only care about present
4350 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, PFERR_PRESENT_MASK);
4351 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, PFERR_PRESENT_MASK);
4355 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4357 struct vcpu_vmx *vmx = to_vmx(vcpu);
4358 struct msr_data apic_base_msr;
4361 vmx->rmode.vm86_active = 0;
4364 vmx->msr_ia32_umwait_control = 0;
4366 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4367 vmx->hv_deadline_tsc = -1;
4368 kvm_set_cr8(vcpu, 0);
4371 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4372 MSR_IA32_APICBASE_ENABLE;
4373 if (kvm_vcpu_is_reset_bsp(vcpu))
4374 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4375 apic_base_msr.host_initiated = true;
4376 kvm_set_apic_base(vcpu, &apic_base_msr);
4379 vmx_segment_cache_clear(vmx);
4381 seg_setup(VCPU_SREG_CS);
4382 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4383 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4385 seg_setup(VCPU_SREG_DS);
4386 seg_setup(VCPU_SREG_ES);
4387 seg_setup(VCPU_SREG_FS);
4388 seg_setup(VCPU_SREG_GS);
4389 seg_setup(VCPU_SREG_SS);
4391 vmcs_write16(GUEST_TR_SELECTOR, 0);
4392 vmcs_writel(GUEST_TR_BASE, 0);
4393 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4394 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4396 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4397 vmcs_writel(GUEST_LDTR_BASE, 0);
4398 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4399 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4402 vmcs_write32(GUEST_SYSENTER_CS, 0);
4403 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4404 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4405 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4408 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4409 kvm_rip_write(vcpu, 0xfff0);
4411 vmcs_writel(GUEST_GDTR_BASE, 0);
4412 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4414 vmcs_writel(GUEST_IDTR_BASE, 0);
4415 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4417 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4418 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4419 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4420 if (kvm_mpx_supported())
4421 vmcs_write64(GUEST_BNDCFGS, 0);
4425 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4427 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4428 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4429 if (cpu_need_tpr_shadow(vcpu))
4430 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4431 __pa(vcpu->arch.apic->regs));
4432 vmcs_write32(TPR_THRESHOLD, 0);
4435 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4437 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4438 vmx->vcpu.arch.cr0 = cr0;
4439 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4440 vmx_set_cr4(vcpu, 0);
4441 vmx_set_efer(vcpu, 0);
4443 update_exception_bitmap(vcpu);
4445 vpid_sync_context(vmx->vpid);
4447 vmx_clear_hlt(vcpu);
4450 static void enable_irq_window(struct kvm_vcpu *vcpu)
4452 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4455 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4458 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4459 enable_irq_window(vcpu);
4463 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4466 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4468 struct vcpu_vmx *vmx = to_vmx(vcpu);
4470 int irq = vcpu->arch.interrupt.nr;
4472 trace_kvm_inj_virq(irq);
4474 ++vcpu->stat.irq_injections;
4475 if (vmx->rmode.vm86_active) {
4477 if (vcpu->arch.interrupt.soft)
4478 inc_eip = vcpu->arch.event_exit_inst_len;
4479 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4482 intr = irq | INTR_INFO_VALID_MASK;
4483 if (vcpu->arch.interrupt.soft) {
4484 intr |= INTR_TYPE_SOFT_INTR;
4485 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4486 vmx->vcpu.arch.event_exit_inst_len);
4488 intr |= INTR_TYPE_EXT_INTR;
4489 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4491 vmx_clear_hlt(vcpu);
4494 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4496 struct vcpu_vmx *vmx = to_vmx(vcpu);
4500 * Tracking the NMI-blocked state in software is built upon
4501 * finding the next open IRQ window. This, in turn, depends on
4502 * well-behaving guests: They have to keep IRQs disabled at
4503 * least as long as the NMI handler runs. Otherwise we may
4504 * cause NMI nesting, maybe breaking the guest. But as this is
4505 * highly unlikely, we can live with the residual risk.
4507 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4508 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4511 ++vcpu->stat.nmi_injections;
4512 vmx->loaded_vmcs->nmi_known_unmasked = false;
4514 if (vmx->rmode.vm86_active) {
4515 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4519 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4520 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4522 vmx_clear_hlt(vcpu);
4525 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4527 struct vcpu_vmx *vmx = to_vmx(vcpu);
4531 return vmx->loaded_vmcs->soft_vnmi_blocked;
4532 if (vmx->loaded_vmcs->nmi_known_unmasked)
4534 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4535 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4539 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4541 struct vcpu_vmx *vmx = to_vmx(vcpu);
4544 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4545 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4546 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4549 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4551 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4552 GUEST_INTR_STATE_NMI);
4554 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4555 GUEST_INTR_STATE_NMI);
4559 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4561 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4564 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4567 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4568 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4569 GUEST_INTR_STATE_NMI));
4572 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4574 if (to_vmx(vcpu)->nested.nested_run_pending)
4577 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4578 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4581 return !vmx_nmi_blocked(vcpu);
4584 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4586 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4589 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4590 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4591 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4594 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4596 if (to_vmx(vcpu)->nested.nested_run_pending)
4600 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4601 * e.g. if the IRQ arrived asynchronously after checking nested events.
4603 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4606 return !vmx_interrupt_blocked(vcpu);
4609 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4613 if (enable_unrestricted_guest)
4616 mutex_lock(&kvm->slots_lock);
4617 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4619 mutex_unlock(&kvm->slots_lock);
4623 to_kvm_vmx(kvm)->tss_addr = addr;
4624 return init_rmode_tss(kvm);
4627 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4629 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4633 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4638 * Update instruction length as we may reinject the exception
4639 * from user space while in guest debugging mode.
4641 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4642 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4643 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4647 return !(vcpu->guest_debug &
4648 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4662 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4663 int vec, u32 err_code)
4666 * Instruction with address size override prefix opcode 0x67
4667 * Cause the #SS fault with 0 error code in VM86 mode.
4669 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4670 if (kvm_emulate_instruction(vcpu, 0)) {
4671 if (vcpu->arch.halt_request) {
4672 vcpu->arch.halt_request = 0;
4673 return kvm_vcpu_halt(vcpu);
4681 * Forward all other exceptions that are valid in real mode.
4682 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4683 * the required debugging infrastructure rework.
4685 kvm_queue_exception(vcpu, vec);
4690 * Trigger machine check on the host. We assume all the MSRs are already set up
4691 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4692 * We pass a fake environment to the machine check handler because we want
4693 * the guest to be always treated like user space, no matter what context
4694 * it used internally.
4696 static void kvm_machine_check(void)
4698 #if defined(CONFIG_X86_MCE)
4699 struct pt_regs regs = {
4700 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4701 .flags = X86_EFLAGS_IF,
4704 do_machine_check(®s);
4708 static int handle_machine_check(struct kvm_vcpu *vcpu)
4710 /* handled by vmx_vcpu_run() */
4715 * If the host has split lock detection disabled, then #AC is
4716 * unconditionally injected into the guest, which is the pre split lock
4717 * detection behaviour.
4719 * If the host has split lock detection enabled then #AC is
4720 * only injected into the guest when:
4721 * - Guest CPL == 3 (user mode)
4722 * - Guest has #AC detection enabled in CR0
4723 * - Guest EFLAGS has AC bit set
4725 static inline bool guest_inject_ac(struct kvm_vcpu *vcpu)
4727 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4730 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4731 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4734 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4736 struct vcpu_vmx *vmx = to_vmx(vcpu);
4737 struct kvm_run *kvm_run = vcpu->run;
4738 u32 intr_info, ex_no, error_code;
4739 unsigned long cr2, rip, dr6;
4742 vect_info = vmx->idt_vectoring_info;
4743 intr_info = vmx_get_intr_info(vcpu);
4745 if (is_machine_check(intr_info) || is_nmi(intr_info))
4746 return 1; /* handled by handle_exception_nmi_irqoff() */
4748 if (is_invalid_opcode(intr_info))
4749 return handle_ud(vcpu);
4752 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4753 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4755 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4756 WARN_ON_ONCE(!enable_vmware_backdoor);
4759 * VMware backdoor emulation on #GP interception only handles
4760 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4761 * error code on #GP.
4764 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4767 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4771 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4772 * MMIO, it is better to report an internal error.
4773 * See the comments in vmx_handle_exit.
4775 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4776 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4777 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4778 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4779 vcpu->run->internal.ndata = 4;
4780 vcpu->run->internal.data[0] = vect_info;
4781 vcpu->run->internal.data[1] = intr_info;
4782 vcpu->run->internal.data[2] = error_code;
4783 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
4787 if (is_page_fault(intr_info)) {
4788 cr2 = vmx_get_exit_qual(vcpu);
4789 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
4791 * EPT will cause page fault only if we need to
4792 * detect illegal GPAs.
4794 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
4797 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4800 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4802 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4803 return handle_rmode_exception(vcpu, ex_no, error_code);
4807 dr6 = vmx_get_exit_qual(vcpu);
4808 if (!(vcpu->guest_debug &
4809 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4810 if (is_icebp(intr_info))
4811 WARN_ON(!skip_emulated_instruction(vcpu));
4813 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
4816 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
4817 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4821 * Update instruction length as we may reinject #BP from
4822 * user space while in guest debugging mode. Reading it for
4823 * #DB as well causes no harm, it is not used in that case.
4825 vmx->vcpu.arch.event_exit_inst_len =
4826 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4827 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4828 rip = kvm_rip_read(vcpu);
4829 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4830 kvm_run->debug.arch.exception = ex_no;
4833 if (guest_inject_ac(vcpu)) {
4834 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4839 * Handle split lock. Depending on detection mode this will
4840 * either warn and disable split lock detection for this
4841 * task or force SIGBUS on it.
4843 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4847 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4848 kvm_run->ex.exception = ex_no;
4849 kvm_run->ex.error_code = error_code;
4855 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4857 ++vcpu->stat.irq_exits;
4861 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4863 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4864 vcpu->mmio_needed = 0;
4868 static int handle_io(struct kvm_vcpu *vcpu)
4870 unsigned long exit_qualification;
4871 int size, in, string;
4874 exit_qualification = vmx_get_exit_qual(vcpu);
4875 string = (exit_qualification & 16) != 0;
4877 ++vcpu->stat.io_exits;
4880 return kvm_emulate_instruction(vcpu, 0);
4882 port = exit_qualification >> 16;
4883 size = (exit_qualification & 7) + 1;
4884 in = (exit_qualification & 8) != 0;
4886 return kvm_fast_pio(vcpu, size, port, in);
4890 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4893 * Patch in the VMCALL instruction:
4895 hypercall[0] = 0x0f;
4896 hypercall[1] = 0x01;
4897 hypercall[2] = 0xc1;
4900 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4901 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4903 if (is_guest_mode(vcpu)) {
4904 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4905 unsigned long orig_val = val;
4908 * We get here when L2 changed cr0 in a way that did not change
4909 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4910 * but did change L0 shadowed bits. So we first calculate the
4911 * effective cr0 value that L1 would like to write into the
4912 * hardware. It consists of the L2-owned bits from the new
4913 * value combined with the L1-owned bits from L1's guest_cr0.
4915 val = (val & ~vmcs12->cr0_guest_host_mask) |
4916 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4918 if (!nested_guest_cr0_valid(vcpu, val))
4921 if (kvm_set_cr0(vcpu, val))
4923 vmcs_writel(CR0_READ_SHADOW, orig_val);
4926 if (to_vmx(vcpu)->nested.vmxon &&
4927 !nested_host_cr0_valid(vcpu, val))
4930 return kvm_set_cr0(vcpu, val);
4934 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4936 if (is_guest_mode(vcpu)) {
4937 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4938 unsigned long orig_val = val;
4940 /* analogously to handle_set_cr0 */
4941 val = (val & ~vmcs12->cr4_guest_host_mask) |
4942 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4943 if (kvm_set_cr4(vcpu, val))
4945 vmcs_writel(CR4_READ_SHADOW, orig_val);
4948 return kvm_set_cr4(vcpu, val);
4951 static int handle_desc(struct kvm_vcpu *vcpu)
4953 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4954 return kvm_emulate_instruction(vcpu, 0);
4957 static int handle_cr(struct kvm_vcpu *vcpu)
4959 unsigned long exit_qualification, val;
4965 exit_qualification = vmx_get_exit_qual(vcpu);
4966 cr = exit_qualification & 15;
4967 reg = (exit_qualification >> 8) & 15;
4968 switch ((exit_qualification >> 4) & 3) {
4969 case 0: /* mov to cr */
4970 val = kvm_register_readl(vcpu, reg);
4971 trace_kvm_cr_write(cr, val);
4974 err = handle_set_cr0(vcpu, val);
4975 return kvm_complete_insn_gp(vcpu, err);
4977 WARN_ON_ONCE(enable_unrestricted_guest);
4978 err = kvm_set_cr3(vcpu, val);
4979 return kvm_complete_insn_gp(vcpu, err);
4981 err = handle_set_cr4(vcpu, val);
4982 return kvm_complete_insn_gp(vcpu, err);
4984 u8 cr8_prev = kvm_get_cr8(vcpu);
4986 err = kvm_set_cr8(vcpu, cr8);
4987 ret = kvm_complete_insn_gp(vcpu, err);
4988 if (lapic_in_kernel(vcpu))
4990 if (cr8_prev <= cr8)
4993 * TODO: we might be squashing a
4994 * KVM_GUESTDBG_SINGLESTEP-triggered
4995 * KVM_EXIT_DEBUG here.
4997 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5003 WARN_ONCE(1, "Guest should always own CR0.TS");
5004 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5005 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5006 return kvm_skip_emulated_instruction(vcpu);
5007 case 1: /*mov from cr*/
5010 WARN_ON_ONCE(enable_unrestricted_guest);
5011 val = kvm_read_cr3(vcpu);
5012 kvm_register_write(vcpu, reg, val);
5013 trace_kvm_cr_read(cr, val);
5014 return kvm_skip_emulated_instruction(vcpu);
5016 val = kvm_get_cr8(vcpu);
5017 kvm_register_write(vcpu, reg, val);
5018 trace_kvm_cr_read(cr, val);
5019 return kvm_skip_emulated_instruction(vcpu);
5023 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5024 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5025 kvm_lmsw(vcpu, val);
5027 return kvm_skip_emulated_instruction(vcpu);
5031 vcpu->run->exit_reason = 0;
5032 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5033 (int)(exit_qualification >> 4) & 3, cr);
5037 static int handle_dr(struct kvm_vcpu *vcpu)
5039 unsigned long exit_qualification;
5042 exit_qualification = vmx_get_exit_qual(vcpu);
5043 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5045 /* First, if DR does not exist, trigger UD */
5046 if (!kvm_require_dr(vcpu, dr))
5049 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
5050 if (!kvm_require_cpl(vcpu, 0))
5052 dr7 = vmcs_readl(GUEST_DR7);
5055 * As the vm-exit takes precedence over the debug trap, we
5056 * need to emulate the latter, either for the host or the
5057 * guest debugging itself.
5059 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5060 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_RTM | DR6_FIXED_1;
5061 vcpu->run->debug.arch.dr7 = dr7;
5062 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5063 vcpu->run->debug.arch.exception = DB_VECTOR;
5064 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5067 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5072 if (vcpu->guest_debug == 0) {
5073 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5076 * No more DR vmexits; force a reload of the debug registers
5077 * and reenter on this instruction. The next vmexit will
5078 * retrieve the full state of the debug registers.
5080 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5084 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5085 if (exit_qualification & TYPE_MOV_FROM_DR) {
5088 if (kvm_get_dr(vcpu, dr, &val))
5090 kvm_register_write(vcpu, reg, val);
5092 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
5095 return kvm_skip_emulated_instruction(vcpu);
5098 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5100 get_debugreg(vcpu->arch.db[0], 0);
5101 get_debugreg(vcpu->arch.db[1], 1);
5102 get_debugreg(vcpu->arch.db[2], 2);
5103 get_debugreg(vcpu->arch.db[3], 3);
5104 get_debugreg(vcpu->arch.dr6, 6);
5105 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5107 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5108 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5111 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5113 vmcs_writel(GUEST_DR7, val);
5116 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5118 kvm_apic_update_ppr(vcpu);
5122 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5124 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5126 kvm_make_request(KVM_REQ_EVENT, vcpu);
5128 ++vcpu->stat.irq_window_exits;
5132 static int handle_vmcall(struct kvm_vcpu *vcpu)
5134 return kvm_emulate_hypercall(vcpu);
5137 static int handle_invd(struct kvm_vcpu *vcpu)
5139 /* Treat an INVD instruction as a NOP and just skip it. */
5140 return kvm_skip_emulated_instruction(vcpu);
5143 static int handle_invlpg(struct kvm_vcpu *vcpu)
5145 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5147 kvm_mmu_invlpg(vcpu, exit_qualification);
5148 return kvm_skip_emulated_instruction(vcpu);
5151 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5155 err = kvm_rdpmc(vcpu);
5156 return kvm_complete_insn_gp(vcpu, err);
5159 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5161 return kvm_emulate_wbinvd(vcpu);
5164 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5166 u64 new_bv = kvm_read_edx_eax(vcpu);
5167 u32 index = kvm_rcx_read(vcpu);
5169 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5170 return kvm_skip_emulated_instruction(vcpu);
5174 static int handle_apic_access(struct kvm_vcpu *vcpu)
5176 if (likely(fasteoi)) {
5177 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5178 int access_type, offset;
5180 access_type = exit_qualification & APIC_ACCESS_TYPE;
5181 offset = exit_qualification & APIC_ACCESS_OFFSET;
5183 * Sane guest uses MOV to write EOI, with written value
5184 * not cared. So make a short-circuit here by avoiding
5185 * heavy instruction emulation.
5187 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5188 (offset == APIC_EOI)) {
5189 kvm_lapic_set_eoi(vcpu);
5190 return kvm_skip_emulated_instruction(vcpu);
5193 return kvm_emulate_instruction(vcpu, 0);
5196 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5198 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5199 int vector = exit_qualification & 0xff;
5201 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5202 kvm_apic_set_eoi_accelerated(vcpu, vector);
5206 static int handle_apic_write(struct kvm_vcpu *vcpu)
5208 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5209 u32 offset = exit_qualification & 0xfff;
5211 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5212 kvm_apic_write_nodecode(vcpu, offset);
5216 static int handle_task_switch(struct kvm_vcpu *vcpu)
5218 struct vcpu_vmx *vmx = to_vmx(vcpu);
5219 unsigned long exit_qualification;
5220 bool has_error_code = false;
5223 int reason, type, idt_v, idt_index;
5225 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5226 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5227 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5229 exit_qualification = vmx_get_exit_qual(vcpu);
5231 reason = (u32)exit_qualification >> 30;
5232 if (reason == TASK_SWITCH_GATE && idt_v) {
5234 case INTR_TYPE_NMI_INTR:
5235 vcpu->arch.nmi_injected = false;
5236 vmx_set_nmi_mask(vcpu, true);
5238 case INTR_TYPE_EXT_INTR:
5239 case INTR_TYPE_SOFT_INTR:
5240 kvm_clear_interrupt_queue(vcpu);
5242 case INTR_TYPE_HARD_EXCEPTION:
5243 if (vmx->idt_vectoring_info &
5244 VECTORING_INFO_DELIVER_CODE_MASK) {
5245 has_error_code = true;
5247 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5250 case INTR_TYPE_SOFT_EXCEPTION:
5251 kvm_clear_exception_queue(vcpu);
5257 tss_selector = exit_qualification;
5259 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5260 type != INTR_TYPE_EXT_INTR &&
5261 type != INTR_TYPE_NMI_INTR))
5262 WARN_ON(!skip_emulated_instruction(vcpu));
5265 * TODO: What about debug traps on tss switch?
5266 * Are we supposed to inject them and update dr6?
5268 return kvm_task_switch(vcpu, tss_selector,
5269 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5270 reason, has_error_code, error_code);
5273 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5275 unsigned long exit_qualification;
5279 exit_qualification = vmx_get_exit_qual(vcpu);
5282 * EPT violation happened while executing iret from NMI,
5283 * "blocked by NMI" bit has to be set before next VM entry.
5284 * There are errata that may cause this bit to not be set:
5287 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5289 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5290 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5292 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5293 trace_kvm_page_fault(gpa, exit_qualification);
5295 /* Is it a read fault? */
5296 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5297 ? PFERR_USER_MASK : 0;
5298 /* Is it a write fault? */
5299 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5300 ? PFERR_WRITE_MASK : 0;
5301 /* Is it a fetch fault? */
5302 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5303 ? PFERR_FETCH_MASK : 0;
5304 /* ept page table entry is present? */
5305 error_code |= (exit_qualification &
5306 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5307 EPT_VIOLATION_EXECUTABLE))
5308 ? PFERR_PRESENT_MASK : 0;
5310 error_code |= (exit_qualification & 0x100) != 0 ?
5311 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5313 vcpu->arch.exit_qualification = exit_qualification;
5316 * Check that the GPA doesn't exceed physical memory limits, as that is
5317 * a guest page fault. We have to emulate the instruction here, because
5318 * if the illegal address is that of a paging structure, then
5319 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5320 * would also use advanced VM-exit information for EPT violations to
5321 * reconstruct the page fault error code.
5323 if (unlikely(kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5324 return kvm_emulate_instruction(vcpu, 0);
5326 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5329 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5334 * A nested guest cannot optimize MMIO vmexits, because we have an
5335 * nGPA here instead of the required GPA.
5337 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5338 if (!is_guest_mode(vcpu) &&
5339 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5340 trace_kvm_fast_mmio(gpa);
5341 return kvm_skip_emulated_instruction(vcpu);
5344 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5347 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5349 WARN_ON_ONCE(!enable_vnmi);
5350 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5351 ++vcpu->stat.nmi_window_exits;
5352 kvm_make_request(KVM_REQ_EVENT, vcpu);
5357 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5359 struct vcpu_vmx *vmx = to_vmx(vcpu);
5360 bool intr_window_requested;
5361 unsigned count = 130;
5363 intr_window_requested = exec_controls_get(vmx) &
5364 CPU_BASED_INTR_WINDOW_EXITING;
5366 while (vmx->emulation_required && count-- != 0) {
5367 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5368 return handle_interrupt_window(&vmx->vcpu);
5370 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5373 if (!kvm_emulate_instruction(vcpu, 0))
5376 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5377 vcpu->arch.exception.pending) {
5378 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5379 vcpu->run->internal.suberror =
5380 KVM_INTERNAL_ERROR_EMULATION;
5381 vcpu->run->internal.ndata = 0;
5385 if (vcpu->arch.halt_request) {
5386 vcpu->arch.halt_request = 0;
5387 return kvm_vcpu_halt(vcpu);
5391 * Note, return 1 and not 0, vcpu_run() will invoke
5392 * xfer_to_guest_mode() which will create a proper return
5395 if (__xfer_to_guest_mode_work_pending())
5402 static void grow_ple_window(struct kvm_vcpu *vcpu)
5404 struct vcpu_vmx *vmx = to_vmx(vcpu);
5405 unsigned int old = vmx->ple_window;
5407 vmx->ple_window = __grow_ple_window(old, ple_window,
5411 if (vmx->ple_window != old) {
5412 vmx->ple_window_dirty = true;
5413 trace_kvm_ple_window_update(vcpu->vcpu_id,
5414 vmx->ple_window, old);
5418 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5420 struct vcpu_vmx *vmx = to_vmx(vcpu);
5421 unsigned int old = vmx->ple_window;
5423 vmx->ple_window = __shrink_ple_window(old, ple_window,
5427 if (vmx->ple_window != old) {
5428 vmx->ple_window_dirty = true;
5429 trace_kvm_ple_window_update(vcpu->vcpu_id,
5430 vmx->ple_window, old);
5435 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5437 static void wakeup_handler(void)
5439 struct kvm_vcpu *vcpu;
5440 int cpu = smp_processor_id();
5442 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5443 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5444 blocked_vcpu_list) {
5445 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5447 if (pi_test_on(pi_desc) == 1)
5448 kvm_vcpu_kick(vcpu);
5450 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5453 static void vmx_enable_tdp(void)
5455 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5456 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5457 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5458 0ull, VMX_EPT_EXECUTABLE_MASK,
5459 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5460 VMX_EPT_RWX_MASK, 0ull);
5462 ept_set_mmio_spte_mask();
5466 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5467 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5469 static int handle_pause(struct kvm_vcpu *vcpu)
5471 if (!kvm_pause_in_guest(vcpu->kvm))
5472 grow_ple_window(vcpu);
5475 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5476 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5477 * never set PAUSE_EXITING and just set PLE if supported,
5478 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5480 kvm_vcpu_on_spin(vcpu, true);
5481 return kvm_skip_emulated_instruction(vcpu);
5484 static int handle_nop(struct kvm_vcpu *vcpu)
5486 return kvm_skip_emulated_instruction(vcpu);
5489 static int handle_mwait(struct kvm_vcpu *vcpu)
5491 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5492 return handle_nop(vcpu);
5495 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5497 kvm_queue_exception(vcpu, UD_VECTOR);
5501 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5506 static int handle_monitor(struct kvm_vcpu *vcpu)
5508 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5509 return handle_nop(vcpu);
5512 static int handle_invpcid(struct kvm_vcpu *vcpu)
5514 u32 vmx_instruction_info;
5522 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5523 kvm_queue_exception(vcpu, UD_VECTOR);
5527 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5528 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5531 kvm_inject_gp(vcpu, 0);
5535 /* According to the Intel instruction reference, the memory operand
5536 * is read even if it isn't needed (e.g., for type==all)
5538 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5539 vmx_instruction_info, false,
5540 sizeof(operand), &gva))
5543 return kvm_handle_invpcid(vcpu, type, gva);
5546 static int handle_pml_full(struct kvm_vcpu *vcpu)
5548 unsigned long exit_qualification;
5550 trace_kvm_pml_full(vcpu->vcpu_id);
5552 exit_qualification = vmx_get_exit_qual(vcpu);
5555 * PML buffer FULL happened while executing iret from NMI,
5556 * "blocked by NMI" bit has to be set before next VM entry.
5558 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5560 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5561 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5562 GUEST_INTR_STATE_NMI);
5565 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5566 * here.., and there's no userspace involvement needed for PML.
5571 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5573 struct vcpu_vmx *vmx = to_vmx(vcpu);
5575 if (!vmx->req_immediate_exit &&
5576 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5577 kvm_lapic_expired_hv_timer(vcpu);
5578 return EXIT_FASTPATH_REENTER_GUEST;
5581 return EXIT_FASTPATH_NONE;
5584 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5586 handle_fastpath_preemption_timer(vcpu);
5591 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5592 * are overwritten by nested_vmx_setup() when nested=1.
5594 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5596 kvm_queue_exception(vcpu, UD_VECTOR);
5600 static int handle_encls(struct kvm_vcpu *vcpu)
5603 * SGX virtualization is not yet supported. There is no software
5604 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5605 * to prevent the guest from executing ENCLS.
5607 kvm_queue_exception(vcpu, UD_VECTOR);
5612 * The exit handlers return 1 if the exit was handled fully and guest execution
5613 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5614 * to be done to userspace and return 0.
5616 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5617 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5618 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5619 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5620 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5621 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5622 [EXIT_REASON_CR_ACCESS] = handle_cr,
5623 [EXIT_REASON_DR_ACCESS] = handle_dr,
5624 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5625 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5626 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5627 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5628 [EXIT_REASON_HLT] = kvm_emulate_halt,
5629 [EXIT_REASON_INVD] = handle_invd,
5630 [EXIT_REASON_INVLPG] = handle_invlpg,
5631 [EXIT_REASON_RDPMC] = handle_rdpmc,
5632 [EXIT_REASON_VMCALL] = handle_vmcall,
5633 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5634 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5635 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5636 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5637 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5638 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5639 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5640 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5641 [EXIT_REASON_VMON] = handle_vmx_instruction,
5642 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5643 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5644 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5645 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5646 [EXIT_REASON_WBINVD] = handle_wbinvd,
5647 [EXIT_REASON_XSETBV] = handle_xsetbv,
5648 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5649 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5650 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5651 [EXIT_REASON_LDTR_TR] = handle_desc,
5652 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5653 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5654 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5655 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5656 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5657 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5658 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5659 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5660 [EXIT_REASON_RDRAND] = handle_invalid_op,
5661 [EXIT_REASON_RDSEED] = handle_invalid_op,
5662 [EXIT_REASON_PML_FULL] = handle_pml_full,
5663 [EXIT_REASON_INVPCID] = handle_invpcid,
5664 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5665 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5666 [EXIT_REASON_ENCLS] = handle_encls,
5669 static const int kvm_vmx_max_exit_handlers =
5670 ARRAY_SIZE(kvm_vmx_exit_handlers);
5672 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5674 *info1 = vmx_get_exit_qual(vcpu);
5675 *info2 = vmx_get_intr_info(vcpu);
5678 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5681 __free_page(vmx->pml_pg);
5686 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5688 struct vcpu_vmx *vmx = to_vmx(vcpu);
5692 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5694 /* Do nothing if PML buffer is empty */
5695 if (pml_idx == (PML_ENTITY_NUM - 1))
5698 /* PML index always points to next available PML buffer entity */
5699 if (pml_idx >= PML_ENTITY_NUM)
5704 pml_buf = page_address(vmx->pml_pg);
5705 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5708 gpa = pml_buf[pml_idx];
5709 WARN_ON(gpa & (PAGE_SIZE - 1));
5710 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5713 /* reset PML index */
5714 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5718 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5719 * Called before reporting dirty_bitmap to userspace.
5721 static void kvm_flush_pml_buffers(struct kvm *kvm)
5724 struct kvm_vcpu *vcpu;
5726 * We only need to kick vcpu out of guest mode here, as PML buffer
5727 * is flushed at beginning of all VMEXITs, and it's obvious that only
5728 * vcpus running in guest are possible to have unflushed GPAs in PML
5731 kvm_for_each_vcpu(i, vcpu, kvm)
5732 kvm_vcpu_kick(vcpu);
5735 static void vmx_dump_sel(char *name, uint32_t sel)
5737 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5738 name, vmcs_read16(sel),
5739 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5740 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5741 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5744 static void vmx_dump_dtsel(char *name, uint32_t limit)
5746 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5747 name, vmcs_read32(limit),
5748 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5751 void dump_vmcs(void)
5753 u32 vmentry_ctl, vmexit_ctl;
5754 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5758 if (!dump_invalid_vmcs) {
5759 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5763 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5764 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5765 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5766 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5767 cr4 = vmcs_readl(GUEST_CR4);
5768 efer = vmcs_read64(GUEST_IA32_EFER);
5769 secondary_exec_control = 0;
5770 if (cpu_has_secondary_exec_ctrls())
5771 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5773 pr_err("*** Guest State ***\n");
5774 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5775 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5776 vmcs_readl(CR0_GUEST_HOST_MASK));
5777 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5778 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5779 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5780 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5781 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5783 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5784 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5785 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5786 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5788 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5789 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5790 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5791 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5792 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5793 vmcs_readl(GUEST_SYSENTER_ESP),
5794 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5795 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5796 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5797 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5798 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5799 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5800 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5801 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5802 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5803 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5804 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5805 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5806 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5807 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5808 efer, vmcs_read64(GUEST_IA32_PAT));
5809 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5810 vmcs_read64(GUEST_IA32_DEBUGCTL),
5811 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5812 if (cpu_has_load_perf_global_ctrl() &&
5813 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5814 pr_err("PerfGlobCtl = 0x%016llx\n",
5815 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5816 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5817 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5818 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5819 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5820 vmcs_read32(GUEST_ACTIVITY_STATE));
5821 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5822 pr_err("InterruptStatus = %04x\n",
5823 vmcs_read16(GUEST_INTR_STATUS));
5825 pr_err("*** Host State ***\n");
5826 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5827 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5828 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5829 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5830 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5831 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5832 vmcs_read16(HOST_TR_SELECTOR));
5833 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5834 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5835 vmcs_readl(HOST_TR_BASE));
5836 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5837 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5838 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5839 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5840 vmcs_readl(HOST_CR4));
5841 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5842 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5843 vmcs_read32(HOST_IA32_SYSENTER_CS),
5844 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5845 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5846 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5847 vmcs_read64(HOST_IA32_EFER),
5848 vmcs_read64(HOST_IA32_PAT));
5849 if (cpu_has_load_perf_global_ctrl() &&
5850 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5851 pr_err("PerfGlobCtl = 0x%016llx\n",
5852 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5854 pr_err("*** Control State ***\n");
5855 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5856 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5857 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5858 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5859 vmcs_read32(EXCEPTION_BITMAP),
5860 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5861 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5862 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5863 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5864 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5865 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5866 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5867 vmcs_read32(VM_EXIT_INTR_INFO),
5868 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5869 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5870 pr_err(" reason=%08x qualification=%016lx\n",
5871 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5872 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5873 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5874 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5875 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5876 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5877 pr_err("TSC Multiplier = 0x%016llx\n",
5878 vmcs_read64(TSC_MULTIPLIER));
5879 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5880 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5881 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5882 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5884 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5885 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5886 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5887 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5889 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5890 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5891 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5892 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5893 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5894 pr_err("PLE Gap=%08x Window=%08x\n",
5895 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5896 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5897 pr_err("Virtual processor ID = 0x%04x\n",
5898 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5902 * The guest has exited. See if we can fix it or if we need userspace
5905 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
5907 struct vcpu_vmx *vmx = to_vmx(vcpu);
5908 u32 exit_reason = vmx->exit_reason;
5909 u32 vectoring_info = vmx->idt_vectoring_info;
5912 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5913 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5914 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5915 * mode as if vcpus is in root mode, the PML buffer must has been
5919 vmx_flush_pml_buffer(vcpu);
5922 * We should never reach this point with a pending nested VM-Enter, and
5923 * more specifically emulation of L2 due to invalid guest state (see
5924 * below) should never happen as that means we incorrectly allowed a
5925 * nested VM-Enter with an invalid vmcs12.
5927 WARN_ON_ONCE(vmx->nested.nested_run_pending);
5929 /* If guest state is invalid, start emulating */
5930 if (vmx->emulation_required)
5931 return handle_invalid_guest_state(vcpu);
5933 if (is_guest_mode(vcpu)) {
5935 * The host physical addresses of some pages of guest memory
5936 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
5937 * Page). The CPU may write to these pages via their host
5938 * physical address while L2 is running, bypassing any
5939 * address-translation-based dirty tracking (e.g. EPT write
5942 * Mark them dirty on every exit from L2 to prevent them from
5943 * getting out of sync with dirty tracking.
5945 nested_mark_vmcs12_pages_dirty(vcpu);
5947 if (nested_vmx_reflect_vmexit(vcpu))
5951 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5953 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5954 vcpu->run->fail_entry.hardware_entry_failure_reason
5956 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
5960 if (unlikely(vmx->fail)) {
5962 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5963 vcpu->run->fail_entry.hardware_entry_failure_reason
5964 = vmcs_read32(VM_INSTRUCTION_ERROR);
5965 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
5971 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5972 * delivery event since it indicates guest is accessing MMIO.
5973 * The vm-exit can be triggered again after return to guest that
5974 * will cause infinite loop.
5976 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5977 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5978 exit_reason != EXIT_REASON_EPT_VIOLATION &&
5979 exit_reason != EXIT_REASON_PML_FULL &&
5980 exit_reason != EXIT_REASON_APIC_ACCESS &&
5981 exit_reason != EXIT_REASON_TASK_SWITCH)) {
5982 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5983 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
5984 vcpu->run->internal.ndata = 3;
5985 vcpu->run->internal.data[0] = vectoring_info;
5986 vcpu->run->internal.data[1] = exit_reason;
5987 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
5988 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
5989 vcpu->run->internal.ndata++;
5990 vcpu->run->internal.data[3] =
5991 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5993 vcpu->run->internal.data[vcpu->run->internal.ndata++] =
5994 vcpu->arch.last_vmentry_cpu;
5998 if (unlikely(!enable_vnmi &&
5999 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6000 if (!vmx_interrupt_blocked(vcpu)) {
6001 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6002 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6003 vcpu->arch.nmi_pending) {
6005 * This CPU don't support us in finding the end of an
6006 * NMI-blocked window if the guest runs with IRQs
6007 * disabled. So we pull the trigger after 1 s of
6008 * futile waiting, but inform the user about this.
6010 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6011 "state on VCPU %d after 1 s timeout\n",
6012 __func__, vcpu->vcpu_id);
6013 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6017 if (exit_fastpath != EXIT_FASTPATH_NONE)
6020 if (exit_reason >= kvm_vmx_max_exit_handlers)
6021 goto unexpected_vmexit;
6022 #ifdef CONFIG_RETPOLINE
6023 if (exit_reason == EXIT_REASON_MSR_WRITE)
6024 return kvm_emulate_wrmsr(vcpu);
6025 else if (exit_reason == EXIT_REASON_PREEMPTION_TIMER)
6026 return handle_preemption_timer(vcpu);
6027 else if (exit_reason == EXIT_REASON_INTERRUPT_WINDOW)
6028 return handle_interrupt_window(vcpu);
6029 else if (exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6030 return handle_external_interrupt(vcpu);
6031 else if (exit_reason == EXIT_REASON_HLT)
6032 return kvm_emulate_halt(vcpu);
6033 else if (exit_reason == EXIT_REASON_EPT_MISCONFIG)
6034 return handle_ept_misconfig(vcpu);
6037 exit_reason = array_index_nospec(exit_reason,
6038 kvm_vmx_max_exit_handlers);
6039 if (!kvm_vmx_exit_handlers[exit_reason])
6040 goto unexpected_vmexit;
6042 return kvm_vmx_exit_handlers[exit_reason](vcpu);
6045 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n", exit_reason);
6047 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6048 vcpu->run->internal.suberror =
6049 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6050 vcpu->run->internal.ndata = 2;
6051 vcpu->run->internal.data[0] = exit_reason;
6052 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6057 * Software based L1D cache flush which is used when microcode providing
6058 * the cache control MSR is not loaded.
6060 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6061 * flush it is required to read in 64 KiB because the replacement algorithm
6062 * is not exactly LRU. This could be sized at runtime via topology
6063 * information but as all relevant affected CPUs have 32KiB L1D cache size
6064 * there is no point in doing so.
6066 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6068 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6071 * This code is only executed when the the flush mode is 'cond' or
6074 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6078 * Clear the per-vcpu flush bit, it gets set again
6079 * either from vcpu_run() or from one of the unsafe
6082 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6083 vcpu->arch.l1tf_flush_l1d = false;
6086 * Clear the per-cpu flush bit, it gets set again from
6087 * the interrupt handlers.
6089 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6090 kvm_clear_cpu_l1tf_flush_l1d();
6096 vcpu->stat.l1d_flush++;
6098 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6099 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6104 /* First ensure the pages are in the TLB */
6105 "xorl %%eax, %%eax\n"
6106 ".Lpopulate_tlb:\n\t"
6107 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6108 "addl $4096, %%eax\n\t"
6109 "cmpl %%eax, %[size]\n\t"
6110 "jne .Lpopulate_tlb\n\t"
6111 "xorl %%eax, %%eax\n\t"
6113 /* Now fill the cache */
6114 "xorl %%eax, %%eax\n"
6116 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6117 "addl $64, %%eax\n\t"
6118 "cmpl %%eax, %[size]\n\t"
6119 "jne .Lfill_cache\n\t"
6121 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6123 : "eax", "ebx", "ecx", "edx");
6126 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6128 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6131 if (is_guest_mode(vcpu) &&
6132 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6135 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6136 if (is_guest_mode(vcpu))
6137 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6139 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6142 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6144 struct vcpu_vmx *vmx = to_vmx(vcpu);
6145 u32 sec_exec_control;
6147 if (!lapic_in_kernel(vcpu))
6150 if (!flexpriority_enabled &&
6151 !cpu_has_vmx_virtualize_x2apic_mode())
6154 /* Postpone execution until vmcs01 is the current VMCS. */
6155 if (is_guest_mode(vcpu)) {
6156 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6160 sec_exec_control = secondary_exec_controls_get(vmx);
6161 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6162 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6164 switch (kvm_get_apic_mode(vcpu)) {
6165 case LAPIC_MODE_INVALID:
6166 WARN_ONCE(true, "Invalid local APIC state");
6167 case LAPIC_MODE_DISABLED:
6169 case LAPIC_MODE_XAPIC:
6170 if (flexpriority_enabled) {
6172 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6173 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6176 * Flush the TLB, reloading the APIC access page will
6177 * only do so if its physical address has changed, but
6178 * the guest may have inserted a non-APIC mapping into
6179 * the TLB while the APIC access page was disabled.
6181 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6184 case LAPIC_MODE_X2APIC:
6185 if (cpu_has_vmx_virtualize_x2apic_mode())
6187 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6190 secondary_exec_controls_set(vmx, sec_exec_control);
6192 vmx_update_msr_bitmap(vcpu);
6195 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6199 /* Defer reload until vmcs01 is the current VMCS. */
6200 if (is_guest_mode(vcpu)) {
6201 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6205 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6206 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6209 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6210 if (is_error_page(page))
6213 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6214 vmx_flush_tlb_current(vcpu);
6217 * Do not pin apic access page in memory, the MMU notifier
6218 * will call us again if it is migrated or swapped out.
6223 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6231 status = vmcs_read16(GUEST_INTR_STATUS);
6233 if (max_isr != old) {
6235 status |= max_isr << 8;
6236 vmcs_write16(GUEST_INTR_STATUS, status);
6240 static void vmx_set_rvi(int vector)
6248 status = vmcs_read16(GUEST_INTR_STATUS);
6249 old = (u8)status & 0xff;
6250 if ((u8)vector != old) {
6252 status |= (u8)vector;
6253 vmcs_write16(GUEST_INTR_STATUS, status);
6257 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6260 * When running L2, updating RVI is only relevant when
6261 * vmcs12 virtual-interrupt-delivery enabled.
6262 * However, it can be enabled only when L1 also
6263 * intercepts external-interrupts and in that case
6264 * we should not update vmcs02 RVI but instead intercept
6265 * interrupt. Therefore, do nothing when running L2.
6267 if (!is_guest_mode(vcpu))
6268 vmx_set_rvi(max_irr);
6271 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6273 struct vcpu_vmx *vmx = to_vmx(vcpu);
6275 bool max_irr_updated;
6277 WARN_ON(!vcpu->arch.apicv_active);
6278 if (pi_test_on(&vmx->pi_desc)) {
6279 pi_clear_on(&vmx->pi_desc);
6281 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6282 * But on x86 this is just a compiler barrier anyway.
6284 smp_mb__after_atomic();
6286 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6289 * If we are running L2 and L1 has a new pending interrupt
6290 * which can be injected, we should re-evaluate
6291 * what should be done with this new L1 interrupt.
6292 * If L1 intercepts external-interrupts, we should
6293 * exit from L2 to L1. Otherwise, interrupt should be
6294 * delivered directly to L2.
6296 if (is_guest_mode(vcpu) && max_irr_updated) {
6297 if (nested_exit_on_intr(vcpu))
6298 kvm_vcpu_exiting_guest_mode(vcpu);
6300 kvm_make_request(KVM_REQ_EVENT, vcpu);
6303 max_irr = kvm_lapic_find_highest_irr(vcpu);
6305 vmx_hwapic_irr_update(vcpu, max_irr);
6309 static bool vmx_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
6311 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6313 return pi_test_on(pi_desc) ||
6314 (pi_test_sn(pi_desc) && !pi_is_pir_empty(pi_desc));
6317 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6319 if (!kvm_vcpu_apicv_active(vcpu))
6322 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6323 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6324 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6325 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6328 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6330 struct vcpu_vmx *vmx = to_vmx(vcpu);
6332 pi_clear_on(&vmx->pi_desc);
6333 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6336 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6338 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu, u32 intr_info)
6340 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6341 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6343 kvm_before_interrupt(vcpu);
6344 vmx_do_interrupt_nmi_irqoff(gate_offset(desc));
6345 kvm_after_interrupt(vcpu);
6348 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6350 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6352 /* if exit due to PF check for async PF */
6353 if (is_page_fault(intr_info))
6354 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6355 /* Handle machine checks before interrupts are enabled */
6356 else if (is_machine_check(intr_info))
6357 kvm_machine_check();
6358 /* We need to handle NMIs before interrupts are enabled */
6359 else if (is_nmi(intr_info))
6360 handle_interrupt_nmi_irqoff(&vmx->vcpu, intr_info);
6363 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6365 u32 intr_info = vmx_get_intr_info(vcpu);
6367 if (WARN_ONCE(!is_external_intr(intr_info),
6368 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6371 handle_interrupt_nmi_irqoff(vcpu, intr_info);
6374 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6376 struct vcpu_vmx *vmx = to_vmx(vcpu);
6378 if (vmx->exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6379 handle_external_interrupt_irqoff(vcpu);
6380 else if (vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)
6381 handle_exception_nmi_irqoff(vmx);
6384 static bool vmx_has_emulated_msr(u32 index)
6387 case MSR_IA32_SMBASE:
6389 * We cannot do SMM unless we can run the guest in big
6392 return enable_unrestricted_guest || emulate_invalid_guest_state;
6393 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6395 case MSR_AMD64_VIRT_SPEC_CTRL:
6396 /* This is AMD only. */
6403 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6408 bool idtv_info_valid;
6410 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6413 if (vmx->loaded_vmcs->nmi_known_unmasked)
6416 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6417 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6418 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6420 * SDM 3: 27.7.1.2 (September 2008)
6421 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6422 * a guest IRET fault.
6423 * SDM 3: 23.2.2 (September 2008)
6424 * Bit 12 is undefined in any of the following cases:
6425 * If the VM exit sets the valid bit in the IDT-vectoring
6426 * information field.
6427 * If the VM exit is due to a double fault.
6429 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6430 vector != DF_VECTOR && !idtv_info_valid)
6431 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6432 GUEST_INTR_STATE_NMI);
6434 vmx->loaded_vmcs->nmi_known_unmasked =
6435 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6436 & GUEST_INTR_STATE_NMI);
6437 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6438 vmx->loaded_vmcs->vnmi_blocked_time +=
6439 ktime_to_ns(ktime_sub(ktime_get(),
6440 vmx->loaded_vmcs->entry_time));
6443 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6444 u32 idt_vectoring_info,
6445 int instr_len_field,
6446 int error_code_field)
6450 bool idtv_info_valid;
6452 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6454 vcpu->arch.nmi_injected = false;
6455 kvm_clear_exception_queue(vcpu);
6456 kvm_clear_interrupt_queue(vcpu);
6458 if (!idtv_info_valid)
6461 kvm_make_request(KVM_REQ_EVENT, vcpu);
6463 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6464 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6467 case INTR_TYPE_NMI_INTR:
6468 vcpu->arch.nmi_injected = true;
6470 * SDM 3: 27.7.1.2 (September 2008)
6471 * Clear bit "block by NMI" before VM entry if a NMI
6474 vmx_set_nmi_mask(vcpu, false);
6476 case INTR_TYPE_SOFT_EXCEPTION:
6477 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6479 case INTR_TYPE_HARD_EXCEPTION:
6480 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6481 u32 err = vmcs_read32(error_code_field);
6482 kvm_requeue_exception_e(vcpu, vector, err);
6484 kvm_requeue_exception(vcpu, vector);
6486 case INTR_TYPE_SOFT_INTR:
6487 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6489 case INTR_TYPE_EXT_INTR:
6490 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6497 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6499 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6500 VM_EXIT_INSTRUCTION_LEN,
6501 IDT_VECTORING_ERROR_CODE);
6504 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6506 __vmx_complete_interrupts(vcpu,
6507 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6508 VM_ENTRY_INSTRUCTION_LEN,
6509 VM_ENTRY_EXCEPTION_ERROR_CODE);
6511 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6514 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6517 struct perf_guest_switch_msr *msrs;
6519 msrs = perf_guest_get_msrs(&nr_msrs);
6524 for (i = 0; i < nr_msrs; i++)
6525 if (msrs[i].host == msrs[i].guest)
6526 clear_atomic_switch_msr(vmx, msrs[i].msr);
6528 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6529 msrs[i].host, false);
6532 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6534 struct vcpu_vmx *vmx = to_vmx(vcpu);
6538 if (vmx->req_immediate_exit) {
6539 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6540 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6541 } else if (vmx->hv_deadline_tsc != -1) {
6543 if (vmx->hv_deadline_tsc > tscl)
6544 /* set_hv_timer ensures the delta fits in 32-bits */
6545 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6546 cpu_preemption_timer_multi);
6550 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6551 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6552 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6553 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6554 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6558 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6560 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6561 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6562 vmcs_writel(HOST_RSP, host_rsp);
6566 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6568 switch (to_vmx(vcpu)->exit_reason) {
6569 case EXIT_REASON_MSR_WRITE:
6570 return handle_fastpath_set_msr_irqoff(vcpu);
6571 case EXIT_REASON_PREEMPTION_TIMER:
6572 return handle_fastpath_preemption_timer(vcpu);
6574 return EXIT_FASTPATH_NONE;
6578 bool __vmx_vcpu_run(struct vcpu_vmx *vmx, unsigned long *regs, bool launched);
6580 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6581 struct vcpu_vmx *vmx)
6584 * VMENTER enables interrupts (host state), but the kernel state is
6585 * interrupts disabled when this is invoked. Also tell RCU about
6586 * it. This is the same logic as for exit_to_user_mode().
6588 * This ensures that e.g. latency analysis on the host observes
6589 * guest mode as interrupt enabled.
6591 * guest_enter_irqoff() informs context tracking about the
6592 * transition to guest mode and if enabled adjusts RCU state
6595 instrumentation_begin();
6596 trace_hardirqs_on_prepare();
6597 lockdep_hardirqs_on_prepare(CALLER_ADDR0);
6598 instrumentation_end();
6600 guest_enter_irqoff();
6601 lockdep_hardirqs_on(CALLER_ADDR0);
6603 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6604 if (static_branch_unlikely(&vmx_l1d_should_flush))
6605 vmx_l1d_flush(vcpu);
6606 else if (static_branch_unlikely(&mds_user_clear))
6607 mds_clear_cpu_buffers();
6609 if (vcpu->arch.cr2 != native_read_cr2())
6610 native_write_cr2(vcpu->arch.cr2);
6612 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6613 vmx->loaded_vmcs->launched);
6615 vcpu->arch.cr2 = native_read_cr2();
6618 * VMEXIT disables interrupts (host state), but tracing and lockdep
6619 * have them in state 'on' as recorded before entering guest mode.
6620 * Same as enter_from_user_mode().
6622 * guest_exit_irqoff() restores host context and reinstates RCU if
6623 * enabled and required.
6625 * This needs to be done before the below as native_read_msr()
6626 * contains a tracepoint and x86_spec_ctrl_restore_host() calls
6627 * into world and some more.
6629 lockdep_hardirqs_off(CALLER_ADDR0);
6630 guest_exit_irqoff();
6632 instrumentation_begin();
6633 trace_hardirqs_off_finish();
6634 instrumentation_end();
6637 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6639 fastpath_t exit_fastpath;
6640 struct vcpu_vmx *vmx = to_vmx(vcpu);
6641 unsigned long cr3, cr4;
6644 /* Record the guest's net vcpu time for enforced NMI injections. */
6645 if (unlikely(!enable_vnmi &&
6646 vmx->loaded_vmcs->soft_vnmi_blocked))
6647 vmx->loaded_vmcs->entry_time = ktime_get();
6649 /* Don't enter VMX if guest state is invalid, let the exit handler
6650 start emulation until we arrive back to a valid state */
6651 if (vmx->emulation_required)
6652 return EXIT_FASTPATH_NONE;
6654 if (vmx->ple_window_dirty) {
6655 vmx->ple_window_dirty = false;
6656 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6660 * We did this in prepare_switch_to_guest, because it needs to
6661 * be within srcu_read_lock.
6663 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6665 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6666 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6667 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6668 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6670 cr3 = __get_current_cr3_fast();
6671 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6672 vmcs_writel(HOST_CR3, cr3);
6673 vmx->loaded_vmcs->host_state.cr3 = cr3;
6676 cr4 = cr4_read_shadow();
6677 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6678 vmcs_writel(HOST_CR4, cr4);
6679 vmx->loaded_vmcs->host_state.cr4 = cr4;
6682 /* When single-stepping over STI and MOV SS, we must clear the
6683 * corresponding interruptibility bits in the guest state. Otherwise
6684 * vmentry fails as it then expects bit 14 (BS) in pending debug
6685 * exceptions being set, but that's not correct for the guest debugging
6687 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6688 vmx_set_interrupt_shadow(vcpu, 0);
6690 kvm_load_guest_xsave_state(vcpu);
6692 pt_guest_enter(vmx);
6694 atomic_switch_perf_msrs(vmx);
6696 if (enable_preemption_timer)
6697 vmx_update_hv_timer(vcpu);
6699 kvm_wait_lapic_expire(vcpu);
6702 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6703 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6704 * is no need to worry about the conditional branch over the wrmsr
6705 * being speculatively taken.
6707 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6709 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6710 vmx_vcpu_enter_exit(vcpu, vmx);
6713 * We do not use IBRS in the kernel. If this vCPU has used the
6714 * SPEC_CTRL MSR it may have left it on; save the value and
6715 * turn it off. This is much more efficient than blindly adding
6716 * it to the atomic save/restore list. Especially as the former
6717 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6719 * For non-nested case:
6720 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6724 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6727 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6728 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6730 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6732 /* All fields are clean at this point */
6733 if (static_branch_unlikely(&enable_evmcs))
6734 current_evmcs->hv_clean_fields |=
6735 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6737 if (static_branch_unlikely(&enable_evmcs))
6738 current_evmcs->hv_vp_id = vcpu->arch.hyperv.vp_index;
6740 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6741 if (vmx->host_debugctlmsr)
6742 update_debugctlmsr(vmx->host_debugctlmsr);
6744 #ifndef CONFIG_X86_64
6746 * The sysexit path does not restore ds/es, so we must set them to
6747 * a reasonable value ourselves.
6749 * We can't defer this to vmx_prepare_switch_to_host() since that
6750 * function may be executed in interrupt context, which saves and
6751 * restore segments around it, nullifying its effect.
6753 loadsegment(ds, __USER_DS);
6754 loadsegment(es, __USER_DS);
6757 vmx_register_cache_reset(vcpu);
6761 kvm_load_host_xsave_state(vcpu);
6763 vmx->nested.nested_run_pending = 0;
6764 vmx->idt_vectoring_info = 0;
6766 if (unlikely(vmx->fail)) {
6767 vmx->exit_reason = 0xdead;
6768 return EXIT_FASTPATH_NONE;
6771 vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
6772 if (unlikely((u16)vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY))
6773 kvm_machine_check();
6775 trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
6777 if (unlikely(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6778 return EXIT_FASTPATH_NONE;
6780 vmx->loaded_vmcs->launched = 1;
6781 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6783 vmx_recover_nmi_blocking(vmx);
6784 vmx_complete_interrupts(vmx);
6786 if (is_guest_mode(vcpu))
6787 return EXIT_FASTPATH_NONE;
6789 exit_fastpath = vmx_exit_handlers_fastpath(vcpu);
6790 if (exit_fastpath == EXIT_FASTPATH_REENTER_GUEST) {
6791 if (!kvm_vcpu_exit_request(vcpu)) {
6793 * FIXME: this goto should be a loop in vcpu_enter_guest,
6794 * but it would incur the cost of a retpoline for now.
6795 * Revisit once static calls are available.
6797 if (vcpu->arch.apicv_active)
6798 vmx_sync_pir_to_irr(vcpu);
6801 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
6804 return exit_fastpath;
6807 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6809 struct vcpu_vmx *vmx = to_vmx(vcpu);
6812 vmx_destroy_pml_buffer(vmx);
6813 free_vpid(vmx->vpid);
6814 nested_vmx_free_vcpu(vcpu);
6815 free_loaded_vmcs(vmx->loaded_vmcs);
6818 static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
6820 struct vcpu_vmx *vmx;
6821 unsigned long *msr_bitmap;
6824 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6829 vmx->vpid = allocate_vpid();
6832 * If PML is turned on, failure on enabling PML just results in failure
6833 * of creating the vcpu, therefore we can simplify PML logic (by
6834 * avoiding dealing with cases, such as enabling PML partially on vcpus
6835 * for the guest), etc.
6838 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6843 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) != NR_SHARED_MSRS);
6845 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6846 u32 index = vmx_msr_index[i];
6847 u32 data_low, data_high;
6850 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6852 if (wrmsr_safe(index, data_low, data_high) < 0)
6855 vmx->guest_msrs[j].index = i;
6856 vmx->guest_msrs[j].data = 0;
6858 case MSR_IA32_TSX_CTRL:
6860 * No need to pass TSX_CTRL_CPUID_CLEAR through, so
6861 * let's avoid changing CPUID bits under the host
6864 vmx->guest_msrs[j].mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6867 vmx->guest_msrs[j].mask = -1ull;
6873 err = alloc_loaded_vmcs(&vmx->vmcs01);
6877 msr_bitmap = vmx->vmcs01.msr_bitmap;
6878 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6879 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6880 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6881 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6882 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6883 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6884 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6885 if (kvm_cstate_in_guest(vcpu->kvm)) {
6886 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C1_RES, MSR_TYPE_R);
6887 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6888 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6889 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6891 vmx->msr_bitmap_mode = 0;
6893 vmx->loaded_vmcs = &vmx->vmcs01;
6895 vmx_vcpu_load(vcpu, cpu);
6900 if (cpu_need_virtualize_apic_accesses(vcpu)) {
6901 err = alloc_apic_access_page(vcpu->kvm);
6906 if (enable_ept && !enable_unrestricted_guest) {
6907 err = init_rmode_identity_map(vcpu->kvm);
6913 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
6915 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6917 vmx->nested.posted_intr_nv = -1;
6918 vmx->nested.current_vmptr = -1ull;
6920 vcpu->arch.microcode_version = 0x100000000ULL;
6921 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
6924 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6925 * or POSTED_INTR_WAKEUP_VECTOR.
6927 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6928 vmx->pi_desc.sn = 1;
6930 vmx->ept_pointer = INVALID_PAGE;
6935 free_loaded_vmcs(vmx->loaded_vmcs);
6937 vmx_destroy_pml_buffer(vmx);
6939 free_vpid(vmx->vpid);
6943 #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"
6944 #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"
6946 static int vmx_vm_init(struct kvm *kvm)
6948 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
6951 kvm->arch.pause_in_guest = true;
6953 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6954 switch (l1tf_mitigation) {
6955 case L1TF_MITIGATION_OFF:
6956 case L1TF_MITIGATION_FLUSH_NOWARN:
6957 /* 'I explicitly don't care' is set */
6959 case L1TF_MITIGATION_FLUSH:
6960 case L1TF_MITIGATION_FLUSH_NOSMT:
6961 case L1TF_MITIGATION_FULL:
6963 * Warn upon starting the first VM in a potentially
6964 * insecure environment.
6966 if (sched_smt_active())
6967 pr_warn_once(L1TF_MSG_SMT);
6968 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6969 pr_warn_once(L1TF_MSG_L1D);
6971 case L1TF_MITIGATION_FULL_FORCE:
6972 /* Flush is enforced */
6976 kvm_apicv_init(kvm, enable_apicv);
6980 static int __init vmx_check_processor_compat(void)
6982 struct vmcs_config vmcs_conf;
6983 struct vmx_capability vmx_cap;
6985 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
6986 !this_cpu_has(X86_FEATURE_VMX)) {
6987 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
6991 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
6994 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
6995 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6996 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6997 smp_processor_id());
7003 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7008 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7009 * memory aliases with conflicting memory types and sometimes MCEs.
7010 * We have to be careful as to what are honored and when.
7012 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7013 * UC. The effective memory type is UC or WC depending on guest PAT.
7014 * This was historically the source of MCEs and we want to be
7017 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7018 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7019 * EPT memory type is set to WB. The effective memory type is forced
7022 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7023 * EPT memory type is used to emulate guest CD/MTRR.
7027 cache = MTRR_TYPE_UNCACHABLE;
7031 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7032 ipat = VMX_EPT_IPAT_BIT;
7033 cache = MTRR_TYPE_WRBACK;
7037 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7038 ipat = VMX_EPT_IPAT_BIT;
7039 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7040 cache = MTRR_TYPE_WRBACK;
7042 cache = MTRR_TYPE_UNCACHABLE;
7046 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
7049 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7052 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
7055 * These bits in the secondary execution controls field
7056 * are dynamic, the others are mostly based on the hypervisor
7057 * architecture and the guest's CPUID. Do not touch the
7061 SECONDARY_EXEC_SHADOW_VMCS |
7062 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7063 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7064 SECONDARY_EXEC_DESC;
7066 u32 new_ctl = vmx->secondary_exec_control;
7067 u32 cur_ctl = secondary_exec_controls_get(vmx);
7069 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7073 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7074 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7076 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7078 struct vcpu_vmx *vmx = to_vmx(vcpu);
7079 struct kvm_cpuid_entry2 *entry;
7081 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7082 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7084 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7085 if (entry && (entry->_reg & (_cpuid_mask))) \
7086 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7089 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7090 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7091 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7092 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7093 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7094 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7095 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7096 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7097 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7098 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7099 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7100 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7101 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7102 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7103 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7105 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7106 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7107 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7108 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7109 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7110 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7111 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7113 #undef cr4_fixed1_update
7116 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7118 struct vcpu_vmx *vmx = to_vmx(vcpu);
7120 if (kvm_mpx_supported()) {
7121 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7124 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7125 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7127 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7128 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7133 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7135 struct vcpu_vmx *vmx = to_vmx(vcpu);
7136 struct kvm_cpuid_entry2 *best = NULL;
7139 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7140 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7143 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7144 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7145 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7146 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7149 /* Get the number of configurable Address Ranges for filtering */
7150 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7151 PT_CAP_num_address_ranges);
7153 /* Initialize and clear the no dependency bits */
7154 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7155 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7158 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7159 * will inject an #GP
7161 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7162 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7165 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7166 * PSBFreq can be set
7168 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7169 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7170 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7173 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7174 * MTCFreq can be set
7176 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7177 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7178 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7180 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7181 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7182 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7185 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7186 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7187 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7189 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7190 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7191 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7193 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
7194 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7195 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7197 /* unmask address range configure area */
7198 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7199 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7202 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7204 struct vcpu_vmx *vmx = to_vmx(vcpu);
7206 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7207 vcpu->arch.xsaves_enabled = false;
7209 if (cpu_has_secondary_exec_ctrls()) {
7210 vmx_compute_secondary_exec_control(vmx);
7211 vmcs_set_secondary_exec_control(vmx);
7214 if (nested_vmx_allowed(vcpu))
7215 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7216 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7217 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7219 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7220 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7221 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7223 if (nested_vmx_allowed(vcpu)) {
7224 nested_vmx_cr_fixed1_bits_update(vcpu);
7225 nested_vmx_entry_exit_ctls_update(vcpu);
7228 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7229 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7230 update_intel_pt_cfg(vcpu);
7232 if (boot_cpu_has(X86_FEATURE_RTM)) {
7233 struct shared_msr_entry *msr;
7234 msr = find_msr_entry(vmx, MSR_IA32_TSX_CTRL);
7236 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7237 vmx_set_guest_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7242 static __init void vmx_set_cpu_caps(void)
7248 kvm_cpu_cap_set(X86_FEATURE_VMX);
7251 if (kvm_mpx_supported())
7252 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7253 if (cpu_has_vmx_invpcid())
7254 kvm_cpu_cap_check_and_set(X86_FEATURE_INVPCID);
7255 if (vmx_pt_mode_is_host_guest())
7256 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7258 if (vmx_umip_emulated())
7259 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7263 if (!cpu_has_vmx_xsaves())
7264 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7266 /* CPUID 0x80000001 */
7267 if (!cpu_has_vmx_rdtscp())
7268 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7270 if (cpu_has_vmx_waitpkg())
7271 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7274 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7276 to_vmx(vcpu)->req_immediate_exit = true;
7279 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7280 struct x86_instruction_info *info)
7282 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7283 unsigned short port;
7287 if (info->intercept == x86_intercept_in ||
7288 info->intercept == x86_intercept_ins) {
7289 port = info->src_val;
7290 size = info->dst_bytes;
7292 port = info->dst_val;
7293 size = info->src_bytes;
7297 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7298 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7301 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7303 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7304 intercept = nested_cpu_has(vmcs12,
7305 CPU_BASED_UNCOND_IO_EXITING);
7307 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7309 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7310 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7313 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7314 struct x86_instruction_info *info,
7315 enum x86_intercept_stage stage,
7316 struct x86_exception *exception)
7318 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7320 switch (info->intercept) {
7322 * RDPID causes #UD if disabled through secondary execution controls.
7323 * Because it is marked as EmulateOnUD, we need to intercept it here.
7325 case x86_intercept_rdtscp:
7326 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7327 exception->vector = UD_VECTOR;
7328 exception->error_code_valid = false;
7329 return X86EMUL_PROPAGATE_FAULT;
7333 case x86_intercept_in:
7334 case x86_intercept_ins:
7335 case x86_intercept_out:
7336 case x86_intercept_outs:
7337 return vmx_check_intercept_io(vcpu, info);
7339 case x86_intercept_lgdt:
7340 case x86_intercept_lidt:
7341 case x86_intercept_lldt:
7342 case x86_intercept_ltr:
7343 case x86_intercept_sgdt:
7344 case x86_intercept_sidt:
7345 case x86_intercept_sldt:
7346 case x86_intercept_str:
7347 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7348 return X86EMUL_CONTINUE;
7350 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7353 /* TODO: check more intercepts... */
7358 return X86EMUL_UNHANDLEABLE;
7361 #ifdef CONFIG_X86_64
7362 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7363 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7364 u64 divisor, u64 *result)
7366 u64 low = a << shift, high = a >> (64 - shift);
7368 /* To avoid the overflow on divq */
7369 if (high >= divisor)
7372 /* Low hold the result, high hold rem which is discarded */
7373 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7374 "rm" (divisor), "0" (low), "1" (high));
7380 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7383 struct vcpu_vmx *vmx;
7384 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7385 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7389 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7390 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7391 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7392 ktimer->timer_advance_ns);
7394 if (delta_tsc > lapic_timer_advance_cycles)
7395 delta_tsc -= lapic_timer_advance_cycles;
7399 /* Convert to host delta tsc if tsc scaling is enabled */
7400 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7401 delta_tsc && u64_shl_div_u64(delta_tsc,
7402 kvm_tsc_scaling_ratio_frac_bits,
7403 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7407 * If the delta tsc can't fit in the 32 bit after the multi shift,
7408 * we can't use the preemption timer.
7409 * It's possible that it fits on later vmentries, but checking
7410 * on every vmentry is costly so we just use an hrtimer.
7412 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7415 vmx->hv_deadline_tsc = tscl + delta_tsc;
7416 *expired = !delta_tsc;
7420 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7422 to_vmx(vcpu)->hv_deadline_tsc = -1;
7426 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7428 if (!kvm_pause_in_guest(vcpu->kvm))
7429 shrink_ple_window(vcpu);
7432 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7433 struct kvm_memory_slot *slot)
7435 if (!kvm_dirty_log_manual_protect_and_init_set(kvm))
7436 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7437 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7440 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7441 struct kvm_memory_slot *slot)
7443 kvm_mmu_slot_set_dirty(kvm, slot);
7446 static void vmx_flush_log_dirty(struct kvm *kvm)
7448 kvm_flush_pml_buffers(kvm);
7451 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7452 struct kvm_memory_slot *memslot,
7453 gfn_t offset, unsigned long mask)
7455 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7458 static void __pi_post_block(struct kvm_vcpu *vcpu)
7460 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7461 struct pi_desc old, new;
7465 old.control = new.control = pi_desc->control;
7466 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
7467 "Wakeup handler not enabled while the VCPU is blocked\n");
7469 dest = cpu_physical_id(vcpu->cpu);
7471 if (x2apic_enabled())
7474 new.ndst = (dest << 8) & 0xFF00;
7476 /* set 'NV' to 'notification vector' */
7477 new.nv = POSTED_INTR_VECTOR;
7478 } while (cmpxchg64(&pi_desc->control, old.control,
7479 new.control) != old.control);
7481 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
7482 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7483 list_del(&vcpu->blocked_vcpu_list);
7484 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7485 vcpu->pre_pcpu = -1;
7490 * This routine does the following things for vCPU which is going
7491 * to be blocked if VT-d PI is enabled.
7492 * - Store the vCPU to the wakeup list, so when interrupts happen
7493 * we can find the right vCPU to wake up.
7494 * - Change the Posted-interrupt descriptor as below:
7495 * 'NDST' <-- vcpu->pre_pcpu
7496 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
7497 * - If 'ON' is set during this process, which means at least one
7498 * interrupt is posted for this vCPU, we cannot block it, in
7499 * this case, return 1, otherwise, return 0.
7502 static int pi_pre_block(struct kvm_vcpu *vcpu)
7505 struct pi_desc old, new;
7506 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7508 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
7509 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7510 !kvm_vcpu_apicv_active(vcpu))
7513 WARN_ON(irqs_disabled());
7514 local_irq_disable();
7515 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
7516 vcpu->pre_pcpu = vcpu->cpu;
7517 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7518 list_add_tail(&vcpu->blocked_vcpu_list,
7519 &per_cpu(blocked_vcpu_on_cpu,
7521 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7525 old.control = new.control = pi_desc->control;
7527 WARN((pi_desc->sn == 1),
7528 "Warning: SN field of posted-interrupts "
7529 "is set before blocking\n");
7532 * Since vCPU can be preempted during this process,
7533 * vcpu->cpu could be different with pre_pcpu, we
7534 * need to set pre_pcpu as the destination of wakeup
7535 * notification event, then we can find the right vCPU
7536 * to wakeup in wakeup handler if interrupts happen
7537 * when the vCPU is in blocked state.
7539 dest = cpu_physical_id(vcpu->pre_pcpu);
7541 if (x2apic_enabled())
7544 new.ndst = (dest << 8) & 0xFF00;
7546 /* set 'NV' to 'wakeup vector' */
7547 new.nv = POSTED_INTR_WAKEUP_VECTOR;
7548 } while (cmpxchg64(&pi_desc->control, old.control,
7549 new.control) != old.control);
7551 /* We should not block the vCPU if an interrupt is posted for it. */
7552 if (pi_test_on(pi_desc) == 1)
7553 __pi_post_block(vcpu);
7556 return (vcpu->pre_pcpu == -1);
7559 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7561 if (pi_pre_block(vcpu))
7564 if (kvm_lapic_hv_timer_in_use(vcpu))
7565 kvm_lapic_switch_to_sw_timer(vcpu);
7570 static void pi_post_block(struct kvm_vcpu *vcpu)
7572 if (vcpu->pre_pcpu == -1)
7575 WARN_ON(irqs_disabled());
7576 local_irq_disable();
7577 __pi_post_block(vcpu);
7581 static void vmx_post_block(struct kvm_vcpu *vcpu)
7583 if (kvm_x86_ops.set_hv_timer)
7584 kvm_lapic_switch_to_hv_timer(vcpu);
7586 pi_post_block(vcpu);
7590 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
7593 * @host_irq: host irq of the interrupt
7594 * @guest_irq: gsi of the interrupt
7595 * @set: set or unset PI
7596 * returns 0 on success, < 0 on failure
7598 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7599 uint32_t guest_irq, bool set)
7601 struct kvm_kernel_irq_routing_entry *e;
7602 struct kvm_irq_routing_table *irq_rt;
7603 struct kvm_lapic_irq irq;
7604 struct kvm_vcpu *vcpu;
7605 struct vcpu_data vcpu_info;
7608 if (!kvm_arch_has_assigned_device(kvm) ||
7609 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7610 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7613 idx = srcu_read_lock(&kvm->irq_srcu);
7614 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7615 if (guest_irq >= irq_rt->nr_rt_entries ||
7616 hlist_empty(&irq_rt->map[guest_irq])) {
7617 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7618 guest_irq, irq_rt->nr_rt_entries);
7622 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7623 if (e->type != KVM_IRQ_ROUTING_MSI)
7626 * VT-d PI cannot support posting multicast/broadcast
7627 * interrupts to a vCPU, we still use interrupt remapping
7628 * for these kind of interrupts.
7630 * For lowest-priority interrupts, we only support
7631 * those with single CPU as the destination, e.g. user
7632 * configures the interrupts via /proc/irq or uses
7633 * irqbalance to make the interrupts single-CPU.
7635 * We will support full lowest-priority interrupt later.
7637 * In addition, we can only inject generic interrupts using
7638 * the PI mechanism, refuse to route others through it.
7641 kvm_set_msi_irq(kvm, e, &irq);
7642 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
7643 !kvm_irq_is_postable(&irq)) {
7645 * Make sure the IRTE is in remapped mode if
7646 * we don't handle it in posted mode.
7648 ret = irq_set_vcpu_affinity(host_irq, NULL);
7651 "failed to back to remapped mode, irq: %u\n",
7659 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7660 vcpu_info.vector = irq.vector;
7662 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7663 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7666 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7668 ret = irq_set_vcpu_affinity(host_irq, NULL);
7671 printk(KERN_INFO "%s: failed to update PI IRTE\n",
7679 srcu_read_unlock(&kvm->irq_srcu, idx);
7683 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7685 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7686 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7687 FEAT_CTL_LMCE_ENABLED;
7689 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7690 ~FEAT_CTL_LMCE_ENABLED;
7693 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7695 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7696 if (to_vmx(vcpu)->nested.nested_run_pending)
7698 return !is_smm(vcpu);
7701 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7703 struct vcpu_vmx *vmx = to_vmx(vcpu);
7705 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7706 if (vmx->nested.smm.guest_mode)
7707 nested_vmx_vmexit(vcpu, -1, 0, 0);
7709 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7710 vmx->nested.vmxon = false;
7711 vmx_clear_hlt(vcpu);
7715 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7717 struct vcpu_vmx *vmx = to_vmx(vcpu);
7720 if (vmx->nested.smm.vmxon) {
7721 vmx->nested.vmxon = true;
7722 vmx->nested.smm.vmxon = false;
7725 if (vmx->nested.smm.guest_mode) {
7726 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7730 vmx->nested.smm.guest_mode = false;
7735 static void enable_smi_window(struct kvm_vcpu *vcpu)
7737 /* RSM will cause a vmexit anyway. */
7740 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7742 return to_vmx(vcpu)->nested.vmxon;
7745 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7747 if (is_guest_mode(vcpu)) {
7748 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7750 if (hrtimer_try_to_cancel(timer) == 1)
7751 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7755 static void hardware_unsetup(void)
7758 nested_vmx_hardware_unsetup();
7763 static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7765 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7766 BIT(APICV_INHIBIT_REASON_HYPERV);
7768 return supported & BIT(bit);
7771 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7772 .hardware_unsetup = hardware_unsetup,
7774 .hardware_enable = hardware_enable,
7775 .hardware_disable = hardware_disable,
7776 .cpu_has_accelerated_tpr = report_flexpriority,
7777 .has_emulated_msr = vmx_has_emulated_msr,
7779 .vm_size = sizeof(struct kvm_vmx),
7780 .vm_init = vmx_vm_init,
7782 .vcpu_create = vmx_create_vcpu,
7783 .vcpu_free = vmx_free_vcpu,
7784 .vcpu_reset = vmx_vcpu_reset,
7786 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7787 .vcpu_load = vmx_vcpu_load,
7788 .vcpu_put = vmx_vcpu_put,
7790 .update_exception_bitmap = update_exception_bitmap,
7791 .get_msr_feature = vmx_get_msr_feature,
7792 .get_msr = vmx_get_msr,
7793 .set_msr = vmx_set_msr,
7794 .get_segment_base = vmx_get_segment_base,
7795 .get_segment = vmx_get_segment,
7796 .set_segment = vmx_set_segment,
7797 .get_cpl = vmx_get_cpl,
7798 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7799 .set_cr0 = vmx_set_cr0,
7800 .set_cr4 = vmx_set_cr4,
7801 .set_efer = vmx_set_efer,
7802 .get_idt = vmx_get_idt,
7803 .set_idt = vmx_set_idt,
7804 .get_gdt = vmx_get_gdt,
7805 .set_gdt = vmx_set_gdt,
7806 .set_dr7 = vmx_set_dr7,
7807 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7808 .cache_reg = vmx_cache_reg,
7809 .get_rflags = vmx_get_rflags,
7810 .set_rflags = vmx_set_rflags,
7812 .tlb_flush_all = vmx_flush_tlb_all,
7813 .tlb_flush_current = vmx_flush_tlb_current,
7814 .tlb_flush_gva = vmx_flush_tlb_gva,
7815 .tlb_flush_guest = vmx_flush_tlb_guest,
7817 .run = vmx_vcpu_run,
7818 .handle_exit = vmx_handle_exit,
7819 .skip_emulated_instruction = vmx_skip_emulated_instruction,
7820 .update_emulated_instruction = vmx_update_emulated_instruction,
7821 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7822 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7823 .patch_hypercall = vmx_patch_hypercall,
7824 .set_irq = vmx_inject_irq,
7825 .set_nmi = vmx_inject_nmi,
7826 .queue_exception = vmx_queue_exception,
7827 .cancel_injection = vmx_cancel_injection,
7828 .interrupt_allowed = vmx_interrupt_allowed,
7829 .nmi_allowed = vmx_nmi_allowed,
7830 .get_nmi_mask = vmx_get_nmi_mask,
7831 .set_nmi_mask = vmx_set_nmi_mask,
7832 .enable_nmi_window = enable_nmi_window,
7833 .enable_irq_window = enable_irq_window,
7834 .update_cr8_intercept = update_cr8_intercept,
7835 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7836 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7837 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7838 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7839 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7840 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7841 .hwapic_irr_update = vmx_hwapic_irr_update,
7842 .hwapic_isr_update = vmx_hwapic_isr_update,
7843 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7844 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7845 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7846 .dy_apicv_has_pending_interrupt = vmx_dy_apicv_has_pending_interrupt,
7848 .set_tss_addr = vmx_set_tss_addr,
7849 .set_identity_map_addr = vmx_set_identity_map_addr,
7850 .get_mt_mask = vmx_get_mt_mask,
7852 .get_exit_info = vmx_get_exit_info,
7854 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
7856 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7858 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7860 .load_mmu_pgd = vmx_load_mmu_pgd,
7862 .check_intercept = vmx_check_intercept,
7863 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7865 .request_immediate_exit = vmx_request_immediate_exit,
7867 .sched_in = vmx_sched_in,
7869 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7870 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7871 .flush_log_dirty = vmx_flush_log_dirty,
7872 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7874 .pre_block = vmx_pre_block,
7875 .post_block = vmx_post_block,
7877 .pmu_ops = &intel_pmu_ops,
7878 .nested_ops = &vmx_nested_ops,
7880 .update_pi_irte = vmx_update_pi_irte,
7882 #ifdef CONFIG_X86_64
7883 .set_hv_timer = vmx_set_hv_timer,
7884 .cancel_hv_timer = vmx_cancel_hv_timer,
7887 .setup_mce = vmx_setup_mce,
7889 .smi_allowed = vmx_smi_allowed,
7890 .pre_enter_smm = vmx_pre_enter_smm,
7891 .pre_leave_smm = vmx_pre_leave_smm,
7892 .enable_smi_window = enable_smi_window,
7894 .can_emulate_instruction = vmx_can_emulate_instruction,
7895 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7896 .migrate_timers = vmx_migrate_timers,
7899 static __init int hardware_setup(void)
7901 unsigned long host_bndcfgs;
7903 int r, i, ept_lpage_level;
7906 host_idt_base = dt.address;
7908 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7909 kvm_define_shared_msr(i, vmx_msr_index[i]);
7911 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7914 if (boot_cpu_has(X86_FEATURE_NX))
7915 kvm_enable_efer_bits(EFER_NX);
7917 if (boot_cpu_has(X86_FEATURE_MPX)) {
7918 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7919 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7922 if (!cpu_has_vmx_mpx())
7923 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
7924 XFEATURE_MASK_BNDCSR);
7926 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7927 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7930 if (!cpu_has_vmx_ept() ||
7931 !cpu_has_vmx_ept_4levels() ||
7932 !cpu_has_vmx_ept_mt_wb() ||
7933 !cpu_has_vmx_invept_global())
7936 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7937 enable_ept_ad_bits = 0;
7939 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7940 enable_unrestricted_guest = 0;
7942 if (!cpu_has_vmx_flexpriority())
7943 flexpriority_enabled = 0;
7945 if (!cpu_has_virtual_nmis())
7949 * set_apic_access_page_addr() is used to reload apic access
7950 * page upon invalidation. No need to do anything if not
7951 * using the APIC_ACCESS_ADDR VMCS field.
7953 if (!flexpriority_enabled)
7954 vmx_x86_ops.set_apic_access_page_addr = NULL;
7956 if (!cpu_has_vmx_tpr_shadow())
7957 vmx_x86_ops.update_cr8_intercept = NULL;
7959 #if IS_ENABLED(CONFIG_HYPERV)
7960 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7962 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
7963 vmx_x86_ops.tlb_remote_flush_with_range =
7964 hv_remote_flush_tlb_with_range;
7968 if (!cpu_has_vmx_ple()) {
7971 ple_window_grow = 0;
7973 ple_window_shrink = 0;
7976 if (!cpu_has_vmx_apicv()) {
7978 vmx_x86_ops.sync_pir_to_irr = NULL;
7981 if (cpu_has_vmx_tsc_scaling()) {
7982 kvm_has_tsc_control = true;
7983 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7984 kvm_tsc_scaling_ratio_frac_bits = 48;
7987 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7993 ept_lpage_level = 0;
7994 else if (cpu_has_vmx_ept_1g_page())
7995 ept_lpage_level = PG_LEVEL_1G;
7996 else if (cpu_has_vmx_ept_2m_page())
7997 ept_lpage_level = PG_LEVEL_2M;
7999 ept_lpage_level = PG_LEVEL_4K;
8000 kvm_configure_mmu(enable_ept, vmx_get_max_tdp_level(), ept_lpage_level);
8003 * Only enable PML when hardware supports PML feature, and both EPT
8004 * and EPT A/D bit features are enabled -- PML depends on them to work.
8006 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8010 vmx_x86_ops.slot_enable_log_dirty = NULL;
8011 vmx_x86_ops.slot_disable_log_dirty = NULL;
8012 vmx_x86_ops.flush_log_dirty = NULL;
8013 vmx_x86_ops.enable_log_dirty_pt_masked = NULL;
8016 if (!cpu_has_vmx_preemption_timer())
8017 enable_preemption_timer = false;
8019 if (enable_preemption_timer) {
8020 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8023 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
8024 cpu_preemption_timer_multi =
8025 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8028 use_timer_freq = (u64)tsc_khz * 1000;
8029 use_timer_freq >>= cpu_preemption_timer_multi;
8032 * KVM "disables" the preemption timer by setting it to its max
8033 * value. Don't use the timer if it might cause spurious exits
8034 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8036 if (use_timer_freq > 0xffffffffu / 10)
8037 enable_preemption_timer = false;
8040 if (!enable_preemption_timer) {
8041 vmx_x86_ops.set_hv_timer = NULL;
8042 vmx_x86_ops.cancel_hv_timer = NULL;
8043 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8046 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
8048 kvm_mce_cap_supported |= MCG_LMCE_P;
8050 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8052 if (!enable_ept || !cpu_has_vmx_intel_pt())
8053 pt_mode = PT_MODE_SYSTEM;
8056 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
8057 vmx_capability.ept);
8059 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8066 r = alloc_kvm_area();
8068 nested_vmx_hardware_unsetup();
8072 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8073 .cpu_has_kvm_support = cpu_has_kvm_support,
8074 .disabled_by_bios = vmx_disabled_by_bios,
8075 .check_processor_compatibility = vmx_check_processor_compat,
8076 .hardware_setup = hardware_setup,
8078 .runtime_ops = &vmx_x86_ops,
8081 static void vmx_cleanup_l1d_flush(void)
8083 if (vmx_l1d_flush_pages) {
8084 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8085 vmx_l1d_flush_pages = NULL;
8087 /* Restore state so sysfs ignores VMX */
8088 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8091 static void vmx_exit(void)
8093 #ifdef CONFIG_KEXEC_CORE
8094 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8100 #if IS_ENABLED(CONFIG_HYPERV)
8101 if (static_branch_unlikely(&enable_evmcs)) {
8103 struct hv_vp_assist_page *vp_ap;
8105 * Reset everything to support using non-enlightened VMCS
8106 * access later (e.g. when we reload the module with
8107 * enlightened_vmcs=0)
8109 for_each_online_cpu(cpu) {
8110 vp_ap = hv_get_vp_assist_page(cpu);
8115 vp_ap->nested_control.features.directhypercall = 0;
8116 vp_ap->current_nested_vmcs = 0;
8117 vp_ap->enlighten_vmentry = 0;
8120 static_branch_disable(&enable_evmcs);
8123 vmx_cleanup_l1d_flush();
8125 module_exit(vmx_exit);
8127 static int __init vmx_init(void)
8131 #if IS_ENABLED(CONFIG_HYPERV)
8133 * Enlightened VMCS usage should be recommended and the host needs
8134 * to support eVMCS v1 or above. We can also disable eVMCS support
8135 * with module parameter.
8137 if (enlightened_vmcs &&
8138 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8139 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8140 KVM_EVMCS_VERSION) {
8143 /* Check that we have assist pages on all online CPUs */
8144 for_each_online_cpu(cpu) {
8145 if (!hv_get_vp_assist_page(cpu)) {
8146 enlightened_vmcs = false;
8151 if (enlightened_vmcs) {
8152 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8153 static_branch_enable(&enable_evmcs);
8156 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8157 vmx_x86_ops.enable_direct_tlbflush
8158 = hv_enable_direct_tlbflush;
8161 enlightened_vmcs = false;
8165 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8166 __alignof__(struct vcpu_vmx), THIS_MODULE);
8171 * Must be called after kvm_init() so enable_ept is properly set
8172 * up. Hand the parameter mitigation value in which was stored in
8173 * the pre module init parser. If no parameter was given, it will
8174 * contain 'auto' which will be turned into the default 'cond'
8177 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8183 for_each_possible_cpu(cpu) {
8184 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8185 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
8186 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
8189 #ifdef CONFIG_KEXEC_CORE
8190 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8191 crash_vmclear_local_loaded_vmcss);
8193 vmx_check_vmcs12_offsets();
8196 * Intel processors don't have problems with
8197 * GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable
8198 * it for VMX by default
8200 allow_smaller_maxphyaddr = true;
8204 module_init(vmx_init);