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>
34 #include <asm/cpu_device_id.h>
35 #include <asm/debugreg.h>
37 #include <asm/fpu/internal.h>
39 #include <asm/irq_remapping.h>
40 #include <asm/kexec.h>
41 #include <asm/perf_event.h>
43 #include <asm/mmu_context.h>
44 #include <asm/mshyperv.h>
45 #include <asm/mwait.h>
46 #include <asm/spec-ctrl.h>
47 #include <asm/virtext.h>
50 #include "capabilities.h"
54 #include "kvm_cache_regs.h"
66 MODULE_AUTHOR("Qumranet");
67 MODULE_LICENSE("GPL");
70 static const struct x86_cpu_id vmx_cpu_id[] = {
71 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
74 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
77 bool __read_mostly enable_vpid = 1;
78 module_param_named(vpid, enable_vpid, bool, 0444);
80 static bool __read_mostly enable_vnmi = 1;
81 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
83 bool __read_mostly flexpriority_enabled = 1;
84 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
86 bool __read_mostly enable_ept = 1;
87 module_param_named(ept, enable_ept, bool, S_IRUGO);
89 bool __read_mostly enable_unrestricted_guest = 1;
90 module_param_named(unrestricted_guest,
91 enable_unrestricted_guest, bool, S_IRUGO);
93 bool __read_mostly enable_ept_ad_bits = 1;
94 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
96 static bool __read_mostly emulate_invalid_guest_state = true;
97 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
99 static bool __read_mostly fasteoi = 1;
100 module_param(fasteoi, bool, S_IRUGO);
102 bool __read_mostly enable_apicv = 1;
103 module_param(enable_apicv, bool, S_IRUGO);
106 * If nested=1, nested virtualization is supported, i.e., guests may use
107 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
108 * use VMX instructions.
110 static bool __read_mostly nested = 1;
111 module_param(nested, bool, S_IRUGO);
113 bool __read_mostly enable_pml = 1;
114 module_param_named(pml, enable_pml, bool, S_IRUGO);
116 static bool __read_mostly dump_invalid_vmcs = 0;
117 module_param(dump_invalid_vmcs, bool, 0644);
119 #define MSR_BITMAP_MODE_X2APIC 1
120 #define MSR_BITMAP_MODE_X2APIC_APICV 2
122 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
124 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
125 static int __read_mostly cpu_preemption_timer_multi;
126 static bool __read_mostly enable_preemption_timer = 1;
128 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
131 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
132 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
133 #define KVM_VM_CR0_ALWAYS_ON \
134 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
135 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
137 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
138 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
139 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
141 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
143 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
144 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
145 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
146 RTIT_STATUS_BYTECNT))
148 #define MSR_IA32_RTIT_OUTPUT_BASE_MASK \
149 (~((1UL << cpuid_query_maxphyaddr(vcpu)) - 1) | 0x7f)
152 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
153 * ple_gap: upper bound on the amount of time between two successive
154 * executions of PAUSE in a loop. Also indicate if ple enabled.
155 * According to test, this time is usually smaller than 128 cycles.
156 * ple_window: upper bound on the amount of time a guest is allowed to execute
157 * in a PAUSE loop. Tests indicate that most spinlocks are held for
158 * less than 2^12 cycles
159 * Time is measured based on a counter that runs at the same rate as the TSC,
160 * refer SDM volume 3b section 21.6.13 & 22.1.3.
162 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
163 module_param(ple_gap, uint, 0444);
165 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
166 module_param(ple_window, uint, 0444);
168 /* Default doubles per-vcpu window every exit. */
169 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
170 module_param(ple_window_grow, uint, 0444);
172 /* Default resets per-vcpu window every exit to ple_window. */
173 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
174 module_param(ple_window_shrink, uint, 0444);
176 /* Default is to compute the maximum so we can never overflow. */
177 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
178 module_param(ple_window_max, uint, 0444);
180 /* Default is SYSTEM mode, 1 for host-guest mode */
181 int __read_mostly pt_mode = PT_MODE_SYSTEM;
182 module_param(pt_mode, int, S_IRUGO);
184 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
185 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
186 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
188 /* Storage for pre module init parameter parsing */
189 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
191 static const struct {
194 } vmentry_l1d_param[] = {
195 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
196 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
197 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
198 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
199 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
200 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
203 #define L1D_CACHE_ORDER 4
204 static void *vmx_l1d_flush_pages;
206 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
211 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
212 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
217 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
221 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
224 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
225 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
226 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
231 /* If set to auto use the default l1tf mitigation method */
232 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
233 switch (l1tf_mitigation) {
234 case L1TF_MITIGATION_OFF:
235 l1tf = VMENTER_L1D_FLUSH_NEVER;
237 case L1TF_MITIGATION_FLUSH_NOWARN:
238 case L1TF_MITIGATION_FLUSH:
239 case L1TF_MITIGATION_FLUSH_NOSMT:
240 l1tf = VMENTER_L1D_FLUSH_COND;
242 case L1TF_MITIGATION_FULL:
243 case L1TF_MITIGATION_FULL_FORCE:
244 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
247 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
248 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
251 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
252 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
254 * This allocation for vmx_l1d_flush_pages is not tied to a VM
255 * lifetime and so should not be charged to a memcg.
257 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
260 vmx_l1d_flush_pages = page_address(page);
263 * Initialize each page with a different pattern in
264 * order to protect against KSM in the nested
265 * virtualization case.
267 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
268 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
273 l1tf_vmx_mitigation = l1tf;
275 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
276 static_branch_enable(&vmx_l1d_should_flush);
278 static_branch_disable(&vmx_l1d_should_flush);
280 if (l1tf == VMENTER_L1D_FLUSH_COND)
281 static_branch_enable(&vmx_l1d_flush_cond);
283 static_branch_disable(&vmx_l1d_flush_cond);
287 static int vmentry_l1d_flush_parse(const char *s)
292 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
293 if (vmentry_l1d_param[i].for_parse &&
294 sysfs_streq(s, vmentry_l1d_param[i].option))
301 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
305 l1tf = vmentry_l1d_flush_parse(s);
309 if (!boot_cpu_has(X86_BUG_L1TF))
313 * Has vmx_init() run already? If not then this is the pre init
314 * parameter parsing. In that case just store the value and let
315 * vmx_init() do the proper setup after enable_ept has been
318 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
319 vmentry_l1d_flush_param = l1tf;
323 mutex_lock(&vmx_l1d_flush_mutex);
324 ret = vmx_setup_l1d_flush(l1tf);
325 mutex_unlock(&vmx_l1d_flush_mutex);
329 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
331 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
332 return sprintf(s, "???\n");
334 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
337 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
338 .set = vmentry_l1d_flush_set,
339 .get = vmentry_l1d_flush_get,
341 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
343 static bool guest_state_valid(struct kvm_vcpu *vcpu);
344 static u32 vmx_segment_access_rights(struct kvm_segment *var);
345 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
348 void vmx_vmexit(void);
350 #define vmx_insn_failed(fmt...) \
353 pr_warn_ratelimited(fmt); \
356 asmlinkage void vmread_error(unsigned long field, bool fault)
359 kvm_spurious_fault();
361 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
364 noinline void vmwrite_error(unsigned long field, unsigned long value)
366 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
367 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
370 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
372 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
375 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
377 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
380 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
382 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
386 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
388 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
392 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
393 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
395 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
396 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
398 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
401 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
402 * can find which vCPU should be waken up.
404 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
405 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
407 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
408 static DEFINE_SPINLOCK(vmx_vpid_lock);
410 struct vmcs_config vmcs_config;
411 struct vmx_capability vmx_capability;
413 #define VMX_SEGMENT_FIELD(seg) \
414 [VCPU_SREG_##seg] = { \
415 .selector = GUEST_##seg##_SELECTOR, \
416 .base = GUEST_##seg##_BASE, \
417 .limit = GUEST_##seg##_LIMIT, \
418 .ar_bytes = GUEST_##seg##_AR_BYTES, \
421 static const struct kvm_vmx_segment_field {
426 } kvm_vmx_segment_fields[] = {
427 VMX_SEGMENT_FIELD(CS),
428 VMX_SEGMENT_FIELD(DS),
429 VMX_SEGMENT_FIELD(ES),
430 VMX_SEGMENT_FIELD(FS),
431 VMX_SEGMENT_FIELD(GS),
432 VMX_SEGMENT_FIELD(SS),
433 VMX_SEGMENT_FIELD(TR),
434 VMX_SEGMENT_FIELD(LDTR),
437 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
439 vmx->segment_cache.bitmask = 0;
442 static unsigned long host_idt_base;
445 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
446 * will emulate SYSCALL in legacy mode if the vendor string in guest
447 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
448 * support this emulation, IA32_STAR must always be included in
449 * vmx_msr_index[], even in i386 builds.
451 const u32 vmx_msr_index[] = {
453 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
455 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
459 #if IS_ENABLED(CONFIG_HYPERV)
460 static bool __read_mostly enlightened_vmcs = true;
461 module_param(enlightened_vmcs, bool, 0444);
463 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
464 static void check_ept_pointer_match(struct kvm *kvm)
466 struct kvm_vcpu *vcpu;
467 u64 tmp_eptp = INVALID_PAGE;
470 kvm_for_each_vcpu(i, vcpu, kvm) {
471 if (!VALID_PAGE(tmp_eptp)) {
472 tmp_eptp = to_vmx(vcpu)->ept_pointer;
473 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
474 to_kvm_vmx(kvm)->ept_pointers_match
475 = EPT_POINTERS_MISMATCH;
480 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
483 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
486 struct kvm_tlb_range *range = data;
488 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
492 static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
493 struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
495 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
498 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
499 * of the base of EPT PML4 table, strip off EPT configuration
503 return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
504 kvm_fill_hv_flush_list_func, (void *)range);
506 return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
509 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
510 struct kvm_tlb_range *range)
512 struct kvm_vcpu *vcpu;
515 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
517 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
518 check_ept_pointer_match(kvm);
520 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
521 kvm_for_each_vcpu(i, vcpu, kvm) {
522 /* If ept_pointer is invalid pointer, bypass flush request. */
523 if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
524 ret |= __hv_remote_flush_tlb_with_range(
528 ret = __hv_remote_flush_tlb_with_range(kvm,
529 kvm_get_vcpu(kvm, 0), range);
532 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
535 static int hv_remote_flush_tlb(struct kvm *kvm)
537 return hv_remote_flush_tlb_with_range(kvm, NULL);
540 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
542 struct hv_enlightened_vmcs *evmcs;
543 struct hv_partition_assist_pg **p_hv_pa_pg =
544 &vcpu->kvm->arch.hyperv.hv_pa_pg;
546 * Synthetic VM-Exit is not enabled in current code and so All
547 * evmcs in singe VM shares same assist page.
550 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL);
555 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
557 evmcs->partition_assist_page =
559 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
560 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
565 #endif /* IS_ENABLED(CONFIG_HYPERV) */
568 * Comment's format: document - errata name - stepping - processor name.
570 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
572 static u32 vmx_preemption_cpu_tfms[] = {
573 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
575 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
576 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
577 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
579 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
581 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
582 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
584 * 320767.pdf - AAP86 - B1 -
585 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
588 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
590 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
592 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
594 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
595 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
596 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
598 /* Xeon E3-1220 V2 */
602 static inline bool cpu_has_broken_vmx_preemption_timer(void)
604 u32 eax = cpuid_eax(0x00000001), i;
606 /* Clear the reserved bits */
607 eax &= ~(0x3U << 14 | 0xfU << 28);
608 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
609 if (eax == vmx_preemption_cpu_tfms[i])
615 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
617 return flexpriority_enabled && lapic_in_kernel(vcpu);
620 static inline bool report_flexpriority(void)
622 return flexpriority_enabled;
625 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
629 for (i = 0; i < vmx->nmsrs; ++i)
630 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
635 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
639 i = __find_msr_index(vmx, msr);
641 return &vmx->guest_msrs[i];
645 static int vmx_set_guest_msr(struct vcpu_vmx *vmx, struct shared_msr_entry *msr, u64 data)
649 u64 old_msr_data = msr->data;
651 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
653 ret = kvm_set_shared_msr(msr->index, msr->data,
657 msr->data = old_msr_data;
662 #ifdef CONFIG_KEXEC_CORE
663 static void crash_vmclear_local_loaded_vmcss(void)
665 int cpu = raw_smp_processor_id();
666 struct loaded_vmcs *v;
668 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
669 loaded_vmcss_on_cpu_link)
672 #endif /* CONFIG_KEXEC_CORE */
674 static void __loaded_vmcs_clear(void *arg)
676 struct loaded_vmcs *loaded_vmcs = arg;
677 int cpu = raw_smp_processor_id();
679 if (loaded_vmcs->cpu != cpu)
680 return; /* vcpu migration can race with cpu offline */
681 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
682 per_cpu(current_vmcs, cpu) = NULL;
684 vmcs_clear(loaded_vmcs->vmcs);
685 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
686 vmcs_clear(loaded_vmcs->shadow_vmcs);
688 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
691 * Ensure all writes to loaded_vmcs, including deleting it from its
692 * current percpu list, complete before setting loaded_vmcs->vcpu to
693 * -1, otherwise a different cpu can see vcpu == -1 first and add
694 * loaded_vmcs to its percpu list before it's deleted from this cpu's
695 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
699 loaded_vmcs->cpu = -1;
700 loaded_vmcs->launched = 0;
703 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
705 int cpu = loaded_vmcs->cpu;
708 smp_call_function_single(cpu,
709 __loaded_vmcs_clear, loaded_vmcs, 1);
712 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
716 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
718 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
719 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
720 vmx->segment_cache.bitmask = 0;
722 ret = vmx->segment_cache.bitmask & mask;
723 vmx->segment_cache.bitmask |= mask;
727 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
729 u16 *p = &vmx->segment_cache.seg[seg].selector;
731 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
732 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
736 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
738 ulong *p = &vmx->segment_cache.seg[seg].base;
740 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
741 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
745 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
747 u32 *p = &vmx->segment_cache.seg[seg].limit;
749 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
750 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
754 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
756 u32 *p = &vmx->segment_cache.seg[seg].ar;
758 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
759 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
763 void update_exception_bitmap(struct kvm_vcpu *vcpu)
767 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
768 (1u << DB_VECTOR) | (1u << AC_VECTOR);
770 * Guest access to VMware backdoor ports could legitimately
771 * trigger #GP because of TSS I/O permission bitmap.
772 * We intercept those #GP and allow access to them anyway
775 if (enable_vmware_backdoor)
776 eb |= (1u << GP_VECTOR);
777 if ((vcpu->guest_debug &
778 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
779 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
780 eb |= 1u << BP_VECTOR;
781 if (to_vmx(vcpu)->rmode.vm86_active)
784 eb &= ~(1u << PF_VECTOR);
786 /* When we are running a nested L2 guest and L1 specified for it a
787 * certain exception bitmap, we must trap the same exceptions and pass
788 * them to L1. When running L2, we will only handle the exceptions
789 * specified above if L1 did not want them.
791 if (is_guest_mode(vcpu))
792 eb |= get_vmcs12(vcpu)->exception_bitmap;
794 vmcs_write32(EXCEPTION_BITMAP, eb);
798 * Check if MSR is intercepted for currently loaded MSR bitmap.
800 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
802 unsigned long *msr_bitmap;
803 int f = sizeof(unsigned long);
805 if (!cpu_has_vmx_msr_bitmap())
808 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
811 return !!test_bit(msr, msr_bitmap + 0x800 / f);
812 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
814 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
820 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
821 unsigned long entry, unsigned long exit)
823 vm_entry_controls_clearbit(vmx, entry);
824 vm_exit_controls_clearbit(vmx, exit);
827 int vmx_find_msr_index(struct vmx_msrs *m, u32 msr)
831 for (i = 0; i < m->nr; ++i) {
832 if (m->val[i].index == msr)
838 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
841 struct msr_autoload *m = &vmx->msr_autoload;
845 if (cpu_has_load_ia32_efer()) {
846 clear_atomic_switch_msr_special(vmx,
847 VM_ENTRY_LOAD_IA32_EFER,
848 VM_EXIT_LOAD_IA32_EFER);
852 case MSR_CORE_PERF_GLOBAL_CTRL:
853 if (cpu_has_load_perf_global_ctrl()) {
854 clear_atomic_switch_msr_special(vmx,
855 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
856 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
861 i = vmx_find_msr_index(&m->guest, msr);
865 m->guest.val[i] = m->guest.val[m->guest.nr];
866 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
869 i = vmx_find_msr_index(&m->host, msr);
874 m->host.val[i] = m->host.val[m->host.nr];
875 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
878 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
879 unsigned long entry, unsigned long exit,
880 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
881 u64 guest_val, u64 host_val)
883 vmcs_write64(guest_val_vmcs, guest_val);
884 if (host_val_vmcs != HOST_IA32_EFER)
885 vmcs_write64(host_val_vmcs, host_val);
886 vm_entry_controls_setbit(vmx, entry);
887 vm_exit_controls_setbit(vmx, exit);
890 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
891 u64 guest_val, u64 host_val, bool entry_only)
894 struct msr_autoload *m = &vmx->msr_autoload;
898 if (cpu_has_load_ia32_efer()) {
899 add_atomic_switch_msr_special(vmx,
900 VM_ENTRY_LOAD_IA32_EFER,
901 VM_EXIT_LOAD_IA32_EFER,
904 guest_val, host_val);
908 case MSR_CORE_PERF_GLOBAL_CTRL:
909 if (cpu_has_load_perf_global_ctrl()) {
910 add_atomic_switch_msr_special(vmx,
911 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
912 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
913 GUEST_IA32_PERF_GLOBAL_CTRL,
914 HOST_IA32_PERF_GLOBAL_CTRL,
915 guest_val, host_val);
919 case MSR_IA32_PEBS_ENABLE:
920 /* PEBS needs a quiescent period after being disabled (to write
921 * a record). Disabling PEBS through VMX MSR swapping doesn't
922 * provide that period, so a CPU could write host's record into
925 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
928 i = vmx_find_msr_index(&m->guest, msr);
930 j = vmx_find_msr_index(&m->host, msr);
932 if ((i < 0 && m->guest.nr == NR_LOADSTORE_MSRS) ||
933 (j < 0 && m->host.nr == NR_LOADSTORE_MSRS)) {
934 printk_once(KERN_WARNING "Not enough msr switch entries. "
935 "Can't add msr %x\n", msr);
940 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
942 m->guest.val[i].index = msr;
943 m->guest.val[i].value = guest_val;
950 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
952 m->host.val[j].index = msr;
953 m->host.val[j].value = host_val;
956 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
958 u64 guest_efer = vmx->vcpu.arch.efer;
961 /* Shadow paging assumes NX to be available. */
963 guest_efer |= EFER_NX;
966 * LMA and LME handled by hardware; SCE meaningless outside long mode.
968 ignore_bits |= EFER_SCE;
970 ignore_bits |= EFER_LMA | EFER_LME;
971 /* SCE is meaningful only in long mode on Intel */
972 if (guest_efer & EFER_LMA)
973 ignore_bits &= ~(u64)EFER_SCE;
977 * On EPT, we can't emulate NX, so we must switch EFER atomically.
978 * On CPUs that support "load IA32_EFER", always switch EFER
979 * atomically, since it's faster than switching it manually.
981 if (cpu_has_load_ia32_efer() ||
982 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
983 if (!(guest_efer & EFER_LMA))
984 guest_efer &= ~EFER_LME;
985 if (guest_efer != host_efer)
986 add_atomic_switch_msr(vmx, MSR_EFER,
987 guest_efer, host_efer, false);
989 clear_atomic_switch_msr(vmx, MSR_EFER);
992 clear_atomic_switch_msr(vmx, MSR_EFER);
994 guest_efer &= ~ignore_bits;
995 guest_efer |= host_efer & ignore_bits;
997 vmx->guest_msrs[efer_offset].data = guest_efer;
998 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1004 #ifdef CONFIG_X86_32
1006 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1007 * VMCS rather than the segment table. KVM uses this helper to figure
1008 * out the current bases to poke them into the VMCS before entry.
1010 static unsigned long segment_base(u16 selector)
1012 struct desc_struct *table;
1015 if (!(selector & ~SEGMENT_RPL_MASK))
1018 table = get_current_gdt_ro();
1020 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1021 u16 ldt_selector = kvm_read_ldt();
1023 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1026 table = (struct desc_struct *)segment_base(ldt_selector);
1028 v = get_desc_base(&table[selector >> 3]);
1033 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1035 return vmx_pt_mode_is_host_guest() &&
1036 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1039 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1043 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1044 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1045 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1046 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1047 for (i = 0; i < addr_range; i++) {
1048 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1049 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1053 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1057 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1058 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1059 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1060 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1061 for (i = 0; i < addr_range; i++) {
1062 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1063 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1067 static void pt_guest_enter(struct vcpu_vmx *vmx)
1069 if (vmx_pt_mode_is_system())
1073 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1074 * Save host state before VM entry.
1076 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1077 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1078 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1079 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1080 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1084 static void pt_guest_exit(struct vcpu_vmx *vmx)
1086 if (vmx_pt_mode_is_system())
1089 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1090 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1091 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1094 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1095 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1098 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1099 unsigned long fs_base, unsigned long gs_base)
1101 if (unlikely(fs_sel != host->fs_sel)) {
1103 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1105 vmcs_write16(HOST_FS_SELECTOR, 0);
1106 host->fs_sel = fs_sel;
1108 if (unlikely(gs_sel != host->gs_sel)) {
1110 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1112 vmcs_write16(HOST_GS_SELECTOR, 0);
1113 host->gs_sel = gs_sel;
1115 if (unlikely(fs_base != host->fs_base)) {
1116 vmcs_writel(HOST_FS_BASE, fs_base);
1117 host->fs_base = fs_base;
1119 if (unlikely(gs_base != host->gs_base)) {
1120 vmcs_writel(HOST_GS_BASE, gs_base);
1121 host->gs_base = gs_base;
1125 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1127 struct vcpu_vmx *vmx = to_vmx(vcpu);
1128 struct vmcs_host_state *host_state;
1129 #ifdef CONFIG_X86_64
1130 int cpu = raw_smp_processor_id();
1132 unsigned long fs_base, gs_base;
1136 vmx->req_immediate_exit = false;
1139 * Note that guest MSRs to be saved/restored can also be changed
1140 * when guest state is loaded. This happens when guest transitions
1141 * to/from long-mode by setting MSR_EFER.LMA.
1143 if (!vmx->guest_msrs_ready) {
1144 vmx->guest_msrs_ready = true;
1145 for (i = 0; i < vmx->save_nmsrs; ++i)
1146 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1147 vmx->guest_msrs[i].data,
1148 vmx->guest_msrs[i].mask);
1152 if (vmx->nested.need_vmcs12_to_shadow_sync)
1153 nested_sync_vmcs12_to_shadow(vcpu);
1155 if (vmx->guest_state_loaded)
1158 host_state = &vmx->loaded_vmcs->host_state;
1161 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1162 * allow segment selectors with cpl > 0 or ti == 1.
1164 host_state->ldt_sel = kvm_read_ldt();
1166 #ifdef CONFIG_X86_64
1167 savesegment(ds, host_state->ds_sel);
1168 savesegment(es, host_state->es_sel);
1170 gs_base = cpu_kernelmode_gs_base(cpu);
1171 if (likely(is_64bit_mm(current->mm))) {
1172 save_fsgs_for_kvm();
1173 fs_sel = current->thread.fsindex;
1174 gs_sel = current->thread.gsindex;
1175 fs_base = current->thread.fsbase;
1176 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1178 savesegment(fs, fs_sel);
1179 savesegment(gs, gs_sel);
1180 fs_base = read_msr(MSR_FS_BASE);
1181 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1184 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1186 savesegment(fs, fs_sel);
1187 savesegment(gs, gs_sel);
1188 fs_base = segment_base(fs_sel);
1189 gs_base = segment_base(gs_sel);
1192 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1193 vmx->guest_state_loaded = true;
1196 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1198 struct vmcs_host_state *host_state;
1200 if (!vmx->guest_state_loaded)
1203 host_state = &vmx->loaded_vmcs->host_state;
1205 ++vmx->vcpu.stat.host_state_reload;
1207 #ifdef CONFIG_X86_64
1208 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1210 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1211 kvm_load_ldt(host_state->ldt_sel);
1212 #ifdef CONFIG_X86_64
1213 load_gs_index(host_state->gs_sel);
1215 loadsegment(gs, host_state->gs_sel);
1218 if (host_state->fs_sel & 7)
1219 loadsegment(fs, host_state->fs_sel);
1220 #ifdef CONFIG_X86_64
1221 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1222 loadsegment(ds, host_state->ds_sel);
1223 loadsegment(es, host_state->es_sel);
1226 invalidate_tss_limit();
1227 #ifdef CONFIG_X86_64
1228 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1230 load_fixmap_gdt(raw_smp_processor_id());
1231 vmx->guest_state_loaded = false;
1232 vmx->guest_msrs_ready = false;
1235 #ifdef CONFIG_X86_64
1236 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1239 if (vmx->guest_state_loaded)
1240 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1242 return vmx->msr_guest_kernel_gs_base;
1245 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1248 if (vmx->guest_state_loaded)
1249 wrmsrl(MSR_KERNEL_GS_BASE, data);
1251 vmx->msr_guest_kernel_gs_base = data;
1255 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1257 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1258 struct pi_desc old, new;
1262 * In case of hot-plug or hot-unplug, we may have to undo
1263 * vmx_vcpu_pi_put even if there is no assigned device. And we
1264 * always keep PI.NDST up to date for simplicity: it makes the
1265 * code easier, and CPU migration is not a fast path.
1267 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1271 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
1272 * PI.NDST: pi_post_block is the one expected to change PID.NDST and the
1273 * wakeup handler expects the vCPU to be on the blocked_vcpu_list that
1274 * matches PI.NDST. Otherwise, a vcpu may not be able to be woken up
1277 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR || vcpu->cpu == cpu) {
1278 pi_clear_sn(pi_desc);
1279 goto after_clear_sn;
1282 /* The full case. */
1284 old.control = new.control = pi_desc->control;
1286 dest = cpu_physical_id(cpu);
1288 if (x2apic_enabled())
1291 new.ndst = (dest << 8) & 0xFF00;
1294 } while (cmpxchg64(&pi_desc->control, old.control,
1295 new.control) != old.control);
1300 * Clear SN before reading the bitmap. The VT-d firmware
1301 * writes the bitmap and reads SN atomically (5.2.3 in the
1302 * spec), so it doesn't really have a memory barrier that
1303 * pairs with this, but we cannot do that and we need one.
1305 smp_mb__after_atomic();
1307 if (!pi_is_pir_empty(pi_desc))
1311 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1312 struct loaded_vmcs *buddy)
1314 struct vcpu_vmx *vmx = to_vmx(vcpu);
1315 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1318 if (!already_loaded) {
1319 loaded_vmcs_clear(vmx->loaded_vmcs);
1320 local_irq_disable();
1323 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1324 * this cpu's percpu list, otherwise it may not yet be deleted
1325 * from its previous cpu's percpu list. Pairs with the
1326 * smb_wmb() in __loaded_vmcs_clear().
1330 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1331 &per_cpu(loaded_vmcss_on_cpu, cpu));
1335 prev = per_cpu(current_vmcs, cpu);
1336 if (prev != vmx->loaded_vmcs->vmcs) {
1337 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1338 vmcs_load(vmx->loaded_vmcs->vmcs);
1341 * No indirect branch prediction barrier needed when switching
1342 * the active VMCS within a guest, e.g. on nested VM-Enter.
1343 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1345 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1346 indirect_branch_prediction_barrier();
1349 if (!already_loaded) {
1350 void *gdt = get_current_gdt_ro();
1351 unsigned long sysenter_esp;
1354 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1355 * TLB entries from its previous association with the vCPU.
1357 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1360 * Linux uses per-cpu TSS and GDT, so set these when switching
1361 * processors. See 22.2.4.
1363 vmcs_writel(HOST_TR_BASE,
1364 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1365 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1367 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1368 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1370 vmx->loaded_vmcs->cpu = cpu;
1373 /* Setup TSC multiplier */
1374 if (kvm_has_tsc_control &&
1375 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1376 decache_tsc_multiplier(vmx);
1380 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1381 * vcpu mutex is already taken.
1383 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1385 struct vcpu_vmx *vmx = to_vmx(vcpu);
1387 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1389 vmx_vcpu_pi_load(vcpu, cpu);
1391 vmx->host_debugctlmsr = get_debugctlmsr();
1394 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1396 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1398 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1399 !irq_remapping_cap(IRQ_POSTING_CAP) ||
1400 !kvm_vcpu_apicv_active(vcpu))
1403 /* Set SN when the vCPU is preempted */
1404 if (vcpu->preempted)
1408 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1410 vmx_vcpu_pi_put(vcpu);
1412 vmx_prepare_switch_to_host(to_vmx(vcpu));
1415 static bool emulation_required(struct kvm_vcpu *vcpu)
1417 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1420 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1422 struct vcpu_vmx *vmx = to_vmx(vcpu);
1423 unsigned long rflags, save_rflags;
1425 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1426 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1427 rflags = vmcs_readl(GUEST_RFLAGS);
1428 if (vmx->rmode.vm86_active) {
1429 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1430 save_rflags = vmx->rmode.save_rflags;
1431 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1433 vmx->rflags = rflags;
1438 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1440 struct vcpu_vmx *vmx = to_vmx(vcpu);
1441 unsigned long old_rflags;
1443 if (enable_unrestricted_guest) {
1444 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1445 vmx->rflags = rflags;
1446 vmcs_writel(GUEST_RFLAGS, rflags);
1450 old_rflags = vmx_get_rflags(vcpu);
1451 vmx->rflags = rflags;
1452 if (vmx->rmode.vm86_active) {
1453 vmx->rmode.save_rflags = rflags;
1454 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1456 vmcs_writel(GUEST_RFLAGS, rflags);
1458 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1459 vmx->emulation_required = emulation_required(vcpu);
1462 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1464 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1467 if (interruptibility & GUEST_INTR_STATE_STI)
1468 ret |= KVM_X86_SHADOW_INT_STI;
1469 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1470 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1475 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1477 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1478 u32 interruptibility = interruptibility_old;
1480 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1482 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1483 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1484 else if (mask & KVM_X86_SHADOW_INT_STI)
1485 interruptibility |= GUEST_INTR_STATE_STI;
1487 if ((interruptibility != interruptibility_old))
1488 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1491 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1493 struct vcpu_vmx *vmx = to_vmx(vcpu);
1494 unsigned long value;
1497 * Any MSR write that attempts to change bits marked reserved will
1500 if (data & vmx->pt_desc.ctl_bitmask)
1504 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1505 * result in a #GP unless the same write also clears TraceEn.
1507 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1508 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1512 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1513 * and FabricEn would cause #GP, if
1514 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1516 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1517 !(data & RTIT_CTL_FABRIC_EN) &&
1518 !intel_pt_validate_cap(vmx->pt_desc.caps,
1519 PT_CAP_single_range_output))
1523 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1524 * utilize encodings marked reserved will casue a #GP fault.
1526 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1527 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1528 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1529 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1531 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1532 PT_CAP_cycle_thresholds);
1533 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1534 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1535 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1537 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1538 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1539 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1540 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1544 * If ADDRx_CFG is reserved or the encodings is >2 will
1545 * cause a #GP fault.
1547 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1548 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1550 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1551 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1553 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1554 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1556 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1557 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1563 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1565 unsigned long rip, orig_rip;
1568 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1569 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1570 * set when EPT misconfig occurs. In practice, real hardware updates
1571 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1572 * (namely Hyper-V) don't set it due to it being undefined behavior,
1573 * i.e. we end up advancing IP with some random value.
1575 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1576 to_vmx(vcpu)->exit_reason != EXIT_REASON_EPT_MISCONFIG) {
1577 orig_rip = kvm_rip_read(vcpu);
1578 rip = orig_rip + vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1579 #ifdef CONFIG_X86_64
1581 * We need to mask out the high 32 bits of RIP if not in 64-bit
1582 * mode, but just finding out that we are in 64-bit mode is
1583 * quite expensive. Only do it if there was a carry.
1585 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1588 kvm_rip_write(vcpu, rip);
1590 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1594 /* skipping an emulated instruction also counts */
1595 vmx_set_interrupt_shadow(vcpu, 0);
1601 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
1602 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
1603 * indicates whether exit to userspace is needed.
1605 int vmx_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
1606 struct x86_exception *e)
1608 if (r == X86EMUL_PROPAGATE_FAULT) {
1609 kvm_inject_emulated_page_fault(vcpu, e);
1614 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
1615 * while handling a VMX instruction KVM could've handled the request
1616 * correctly by exiting to userspace and performing I/O but there
1617 * doesn't seem to be a real use-case behind such requests, just return
1618 * KVM_EXIT_INTERNAL_ERROR for now.
1620 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
1621 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
1622 vcpu->run->internal.ndata = 0;
1628 * Recognizes a pending MTF VM-exit and records the nested state for later
1631 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1633 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1634 struct vcpu_vmx *vmx = to_vmx(vcpu);
1636 if (!is_guest_mode(vcpu))
1640 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1641 * T-bit traps. As instruction emulation is completed (i.e. at the
1642 * instruction boundary), any #DB exception pending delivery must be a
1643 * debug-trap. Record the pending MTF state to be delivered in
1644 * vmx_check_nested_events().
1646 if (nested_cpu_has_mtf(vmcs12) &&
1647 (!vcpu->arch.exception.pending ||
1648 vcpu->arch.exception.nr == DB_VECTOR))
1649 vmx->nested.mtf_pending = true;
1651 vmx->nested.mtf_pending = false;
1654 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1656 vmx_update_emulated_instruction(vcpu);
1657 return skip_emulated_instruction(vcpu);
1660 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1663 * Ensure that we clear the HLT state in the VMCS. We don't need to
1664 * explicitly skip the instruction because if the HLT state is set,
1665 * then the instruction is already executing and RIP has already been
1668 if (kvm_hlt_in_guest(vcpu->kvm) &&
1669 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1670 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1673 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1675 struct vcpu_vmx *vmx = to_vmx(vcpu);
1676 unsigned nr = vcpu->arch.exception.nr;
1677 bool has_error_code = vcpu->arch.exception.has_error_code;
1678 u32 error_code = vcpu->arch.exception.error_code;
1679 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1681 kvm_deliver_exception_payload(vcpu);
1683 if (has_error_code) {
1684 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1685 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1688 if (vmx->rmode.vm86_active) {
1690 if (kvm_exception_is_soft(nr))
1691 inc_eip = vcpu->arch.event_exit_inst_len;
1692 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1696 WARN_ON_ONCE(vmx->emulation_required);
1698 if (kvm_exception_is_soft(nr)) {
1699 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1700 vmx->vcpu.arch.event_exit_inst_len);
1701 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1703 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1705 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1707 vmx_clear_hlt(vcpu);
1711 * Swap MSR entry in host/guest MSR entry array.
1713 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1715 struct shared_msr_entry tmp;
1717 tmp = vmx->guest_msrs[to];
1718 vmx->guest_msrs[to] = vmx->guest_msrs[from];
1719 vmx->guest_msrs[from] = tmp;
1723 * Set up the vmcs to automatically save and restore system
1724 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1725 * mode, as fiddling with msrs is very expensive.
1727 static void setup_msrs(struct vcpu_vmx *vmx)
1729 int save_nmsrs, index;
1732 #ifdef CONFIG_X86_64
1734 * The SYSCALL MSRs are only needed on long mode guests, and only
1735 * when EFER.SCE is set.
1737 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1738 index = __find_msr_index(vmx, MSR_STAR);
1740 move_msr_up(vmx, index, save_nmsrs++);
1741 index = __find_msr_index(vmx, MSR_LSTAR);
1743 move_msr_up(vmx, index, save_nmsrs++);
1744 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1746 move_msr_up(vmx, index, save_nmsrs++);
1749 index = __find_msr_index(vmx, MSR_EFER);
1750 if (index >= 0 && update_transition_efer(vmx, index))
1751 move_msr_up(vmx, index, save_nmsrs++);
1752 index = __find_msr_index(vmx, MSR_TSC_AUX);
1753 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1754 move_msr_up(vmx, index, save_nmsrs++);
1755 index = __find_msr_index(vmx, MSR_IA32_TSX_CTRL);
1757 move_msr_up(vmx, index, save_nmsrs++);
1759 vmx->save_nmsrs = save_nmsrs;
1760 vmx->guest_msrs_ready = false;
1762 if (cpu_has_vmx_msr_bitmap())
1763 vmx_update_msr_bitmap(&vmx->vcpu);
1766 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1768 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1769 u64 g_tsc_offset = 0;
1772 * We're here if L1 chose not to trap WRMSR to TSC. According
1773 * to the spec, this should set L1's TSC; The offset that L1
1774 * set for L2 remains unchanged, and still needs to be added
1775 * to the newly set TSC to get L2's TSC.
1777 if (is_guest_mode(vcpu) &&
1778 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
1779 g_tsc_offset = vmcs12->tsc_offset;
1781 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1782 vcpu->arch.tsc_offset - g_tsc_offset,
1784 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1785 return offset + g_tsc_offset;
1789 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1790 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1791 * all guests if the "nested" module option is off, and can also be disabled
1792 * for a single guest by disabling its VMX cpuid bit.
1794 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1796 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1799 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1802 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1804 return !(val & ~valid_bits);
1807 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1809 switch (msr->index) {
1810 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1813 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1814 case MSR_IA32_PERF_CAPABILITIES:
1815 msr->data = vmx_get_perf_capabilities();
1818 return KVM_MSR_RET_INVALID;
1823 * Reads an msr value (of 'msr_index') into 'pdata'.
1824 * Returns 0 on success, non-0 otherwise.
1825 * Assumes vcpu_load() was already called.
1827 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1829 struct vcpu_vmx *vmx = to_vmx(vcpu);
1830 struct shared_msr_entry *msr;
1833 switch (msr_info->index) {
1834 #ifdef CONFIG_X86_64
1836 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1839 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1841 case MSR_KERNEL_GS_BASE:
1842 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1846 return kvm_get_msr_common(vcpu, msr_info);
1847 case MSR_IA32_TSX_CTRL:
1848 if (!msr_info->host_initiated &&
1849 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1851 goto find_shared_msr;
1852 case MSR_IA32_UMWAIT_CONTROL:
1853 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1856 msr_info->data = vmx->msr_ia32_umwait_control;
1858 case MSR_IA32_SPEC_CTRL:
1859 if (!msr_info->host_initiated &&
1860 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1863 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1865 case MSR_IA32_SYSENTER_CS:
1866 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1868 case MSR_IA32_SYSENTER_EIP:
1869 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1871 case MSR_IA32_SYSENTER_ESP:
1872 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1874 case MSR_IA32_BNDCFGS:
1875 if (!kvm_mpx_supported() ||
1876 (!msr_info->host_initiated &&
1877 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1879 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1881 case MSR_IA32_MCG_EXT_CTL:
1882 if (!msr_info->host_initiated &&
1883 !(vmx->msr_ia32_feature_control &
1884 FEAT_CTL_LMCE_ENABLED))
1886 msr_info->data = vcpu->arch.mcg_ext_ctl;
1888 case MSR_IA32_FEAT_CTL:
1889 msr_info->data = vmx->msr_ia32_feature_control;
1891 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1892 if (!nested_vmx_allowed(vcpu))
1894 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1898 * Enlightened VMCS v1 doesn't have certain fields, but buggy
1899 * Hyper-V versions are still trying to use corresponding
1900 * features when they are exposed. Filter out the essential
1903 if (!msr_info->host_initiated &&
1904 vmx->nested.enlightened_vmcs_enabled)
1905 nested_evmcs_filter_control_msr(msr_info->index,
1908 case MSR_IA32_RTIT_CTL:
1909 if (!vmx_pt_mode_is_host_guest())
1911 msr_info->data = vmx->pt_desc.guest.ctl;
1913 case MSR_IA32_RTIT_STATUS:
1914 if (!vmx_pt_mode_is_host_guest())
1916 msr_info->data = vmx->pt_desc.guest.status;
1918 case MSR_IA32_RTIT_CR3_MATCH:
1919 if (!vmx_pt_mode_is_host_guest() ||
1920 !intel_pt_validate_cap(vmx->pt_desc.caps,
1921 PT_CAP_cr3_filtering))
1923 msr_info->data = vmx->pt_desc.guest.cr3_match;
1925 case MSR_IA32_RTIT_OUTPUT_BASE:
1926 if (!vmx_pt_mode_is_host_guest() ||
1927 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1928 PT_CAP_topa_output) &&
1929 !intel_pt_validate_cap(vmx->pt_desc.caps,
1930 PT_CAP_single_range_output)))
1932 msr_info->data = vmx->pt_desc.guest.output_base;
1934 case MSR_IA32_RTIT_OUTPUT_MASK:
1935 if (!vmx_pt_mode_is_host_guest() ||
1936 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1937 PT_CAP_topa_output) &&
1938 !intel_pt_validate_cap(vmx->pt_desc.caps,
1939 PT_CAP_single_range_output)))
1941 msr_info->data = vmx->pt_desc.guest.output_mask;
1943 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1944 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1945 if (!vmx_pt_mode_is_host_guest() ||
1946 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1947 PT_CAP_num_address_ranges)))
1950 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1952 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1955 if (!msr_info->host_initiated &&
1956 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1958 goto find_shared_msr;
1961 msr = find_msr_entry(vmx, msr_info->index);
1963 msr_info->data = msr->data;
1966 return kvm_get_msr_common(vcpu, msr_info);
1972 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
1975 #ifdef CONFIG_X86_64
1976 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
1979 return (unsigned long)data;
1983 * Writes msr value into the appropriate "register".
1984 * Returns 0 on success, non-0 otherwise.
1985 * Assumes vcpu_load() was already called.
1987 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1989 struct vcpu_vmx *vmx = to_vmx(vcpu);
1990 struct shared_msr_entry *msr;
1992 u32 msr_index = msr_info->index;
1993 u64 data = msr_info->data;
1996 switch (msr_index) {
1998 ret = kvm_set_msr_common(vcpu, msr_info);
2000 #ifdef CONFIG_X86_64
2002 vmx_segment_cache_clear(vmx);
2003 vmcs_writel(GUEST_FS_BASE, data);
2006 vmx_segment_cache_clear(vmx);
2007 vmcs_writel(GUEST_GS_BASE, data);
2009 case MSR_KERNEL_GS_BASE:
2010 vmx_write_guest_kernel_gs_base(vmx, data);
2013 case MSR_IA32_SYSENTER_CS:
2014 if (is_guest_mode(vcpu))
2015 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2016 vmcs_write32(GUEST_SYSENTER_CS, data);
2018 case MSR_IA32_SYSENTER_EIP:
2019 if (is_guest_mode(vcpu)) {
2020 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2021 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2023 vmcs_writel(GUEST_SYSENTER_EIP, data);
2025 case MSR_IA32_SYSENTER_ESP:
2026 if (is_guest_mode(vcpu)) {
2027 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2028 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2030 vmcs_writel(GUEST_SYSENTER_ESP, data);
2032 case MSR_IA32_DEBUGCTLMSR:
2033 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2034 VM_EXIT_SAVE_DEBUG_CONTROLS)
2035 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2037 ret = kvm_set_msr_common(vcpu, msr_info);
2040 case MSR_IA32_BNDCFGS:
2041 if (!kvm_mpx_supported() ||
2042 (!msr_info->host_initiated &&
2043 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2045 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2046 (data & MSR_IA32_BNDCFGS_RSVD))
2048 vmcs_write64(GUEST_BNDCFGS, data);
2050 case MSR_IA32_UMWAIT_CONTROL:
2051 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2054 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2055 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2058 vmx->msr_ia32_umwait_control = data;
2060 case MSR_IA32_SPEC_CTRL:
2061 if (!msr_info->host_initiated &&
2062 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
2065 if (kvm_spec_ctrl_test_value(data))
2068 vmx->spec_ctrl = data;
2074 * When it's written (to non-zero) for the first time, pass
2078 * The handling of the MSR bitmap for L2 guests is done in
2079 * nested_vmx_prepare_msr_bitmap. We should not touch the
2080 * vmcs02.msr_bitmap here since it gets completely overwritten
2081 * in the merging. We update the vmcs01 here for L1 as well
2082 * since it will end up touching the MSR anyway now.
2084 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
2088 case MSR_IA32_TSX_CTRL:
2089 if (!msr_info->host_initiated &&
2090 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2092 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2094 goto find_shared_msr;
2095 case MSR_IA32_PRED_CMD:
2096 if (!msr_info->host_initiated &&
2097 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
2100 if (data & ~PRED_CMD_IBPB)
2102 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL))
2107 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2111 * When it's written (to non-zero) for the first time, pass
2115 * The handling of the MSR bitmap for L2 guests is done in
2116 * nested_vmx_prepare_msr_bitmap. We should not touch the
2117 * vmcs02.msr_bitmap here since it gets completely overwritten
2120 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
2123 case MSR_IA32_CR_PAT:
2124 if (!kvm_pat_valid(data))
2127 if (is_guest_mode(vcpu) &&
2128 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2129 get_vmcs12(vcpu)->guest_ia32_pat = data;
2131 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2132 vmcs_write64(GUEST_IA32_PAT, data);
2133 vcpu->arch.pat = data;
2136 ret = kvm_set_msr_common(vcpu, msr_info);
2138 case MSR_IA32_TSC_ADJUST:
2139 ret = kvm_set_msr_common(vcpu, msr_info);
2141 case MSR_IA32_MCG_EXT_CTL:
2142 if ((!msr_info->host_initiated &&
2143 !(to_vmx(vcpu)->msr_ia32_feature_control &
2144 FEAT_CTL_LMCE_ENABLED)) ||
2145 (data & ~MCG_EXT_CTL_LMCE_EN))
2147 vcpu->arch.mcg_ext_ctl = data;
2149 case MSR_IA32_FEAT_CTL:
2150 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2151 (to_vmx(vcpu)->msr_ia32_feature_control &
2152 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2154 vmx->msr_ia32_feature_control = data;
2155 if (msr_info->host_initiated && data == 0)
2156 vmx_leave_nested(vcpu);
2158 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2159 if (!msr_info->host_initiated)
2160 return 1; /* they are read-only */
2161 if (!nested_vmx_allowed(vcpu))
2163 return vmx_set_vmx_msr(vcpu, msr_index, data);
2164 case MSR_IA32_RTIT_CTL:
2165 if (!vmx_pt_mode_is_host_guest() ||
2166 vmx_rtit_ctl_check(vcpu, data) ||
2169 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2170 vmx->pt_desc.guest.ctl = data;
2171 pt_update_intercept_for_msr(vmx);
2173 case MSR_IA32_RTIT_STATUS:
2174 if (!pt_can_write_msr(vmx))
2176 if (data & MSR_IA32_RTIT_STATUS_MASK)
2178 vmx->pt_desc.guest.status = data;
2180 case MSR_IA32_RTIT_CR3_MATCH:
2181 if (!pt_can_write_msr(vmx))
2183 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2184 PT_CAP_cr3_filtering))
2186 vmx->pt_desc.guest.cr3_match = data;
2188 case MSR_IA32_RTIT_OUTPUT_BASE:
2189 if (!pt_can_write_msr(vmx))
2191 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2192 PT_CAP_topa_output) &&
2193 !intel_pt_validate_cap(vmx->pt_desc.caps,
2194 PT_CAP_single_range_output))
2196 if (data & MSR_IA32_RTIT_OUTPUT_BASE_MASK)
2198 vmx->pt_desc.guest.output_base = data;
2200 case MSR_IA32_RTIT_OUTPUT_MASK:
2201 if (!pt_can_write_msr(vmx))
2203 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2204 PT_CAP_topa_output) &&
2205 !intel_pt_validate_cap(vmx->pt_desc.caps,
2206 PT_CAP_single_range_output))
2208 vmx->pt_desc.guest.output_mask = data;
2210 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2211 if (!pt_can_write_msr(vmx))
2213 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2214 if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2215 PT_CAP_num_address_ranges))
2217 if (is_noncanonical_address(data, vcpu))
2220 vmx->pt_desc.guest.addr_b[index / 2] = data;
2222 vmx->pt_desc.guest.addr_a[index / 2] = data;
2225 if (!msr_info->host_initiated &&
2226 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2228 /* Check reserved bit, higher 32 bits should be zero */
2229 if ((data >> 32) != 0)
2231 goto find_shared_msr;
2235 msr = find_msr_entry(vmx, msr_index);
2237 ret = vmx_set_guest_msr(vmx, msr, data);
2239 ret = kvm_set_msr_common(vcpu, msr_info);
2245 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2247 unsigned long guest_owned_bits;
2249 kvm_register_mark_available(vcpu, reg);
2253 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2256 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2258 case VCPU_EXREG_PDPTR:
2260 ept_save_pdptrs(vcpu);
2262 case VCPU_EXREG_CR0:
2263 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2265 vcpu->arch.cr0 &= ~guest_owned_bits;
2266 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2268 case VCPU_EXREG_CR3:
2269 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
2270 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2272 case VCPU_EXREG_CR4:
2273 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2275 vcpu->arch.cr4 &= ~guest_owned_bits;
2276 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2284 static __init int cpu_has_kvm_support(void)
2286 return cpu_has_vmx();
2289 static __init int vmx_disabled_by_bios(void)
2291 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2292 !boot_cpu_has(X86_FEATURE_VMX);
2295 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2299 cr4_set_bits(X86_CR4_VMXE);
2300 intel_pt_handle_vmx(1);
2302 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2303 _ASM_EXTABLE(1b, %l[fault])
2304 : : [vmxon_pointer] "m"(vmxon_pointer)
2309 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2310 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2311 intel_pt_handle_vmx(0);
2312 cr4_clear_bits(X86_CR4_VMXE);
2317 static int hardware_enable(void)
2319 int cpu = raw_smp_processor_id();
2320 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2323 if (cr4_read_shadow() & X86_CR4_VMXE)
2327 * This can happen if we hot-added a CPU but failed to allocate
2328 * VP assist page for it.
2330 if (static_branch_unlikely(&enable_evmcs) &&
2331 !hv_get_vp_assist_page(cpu))
2334 r = kvm_cpu_vmxon(phys_addr);
2344 static void vmclear_local_loaded_vmcss(void)
2346 int cpu = raw_smp_processor_id();
2347 struct loaded_vmcs *v, *n;
2349 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2350 loaded_vmcss_on_cpu_link)
2351 __loaded_vmcs_clear(v);
2355 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2358 static void kvm_cpu_vmxoff(void)
2360 asm volatile (__ex("vmxoff"));
2362 intel_pt_handle_vmx(0);
2363 cr4_clear_bits(X86_CR4_VMXE);
2366 static void hardware_disable(void)
2368 vmclear_local_loaded_vmcss();
2373 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2374 * directly instead of going through cpu_has(), to ensure KVM is trapping
2375 * ENCLS whenever it's supported in hardware. It does not matter whether
2376 * the host OS supports or has enabled SGX.
2378 static bool cpu_has_sgx(void)
2380 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2383 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2384 u32 msr, u32 *result)
2386 u32 vmx_msr_low, vmx_msr_high;
2387 u32 ctl = ctl_min | ctl_opt;
2389 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2391 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2392 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2394 /* Ensure minimum (required) set of control bits are supported. */
2402 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2403 struct vmx_capability *vmx_cap)
2405 u32 vmx_msr_low, vmx_msr_high;
2406 u32 min, opt, min2, opt2;
2407 u32 _pin_based_exec_control = 0;
2408 u32 _cpu_based_exec_control = 0;
2409 u32 _cpu_based_2nd_exec_control = 0;
2410 u32 _vmexit_control = 0;
2411 u32 _vmentry_control = 0;
2413 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2414 min = CPU_BASED_HLT_EXITING |
2415 #ifdef CONFIG_X86_64
2416 CPU_BASED_CR8_LOAD_EXITING |
2417 CPU_BASED_CR8_STORE_EXITING |
2419 CPU_BASED_CR3_LOAD_EXITING |
2420 CPU_BASED_CR3_STORE_EXITING |
2421 CPU_BASED_UNCOND_IO_EXITING |
2422 CPU_BASED_MOV_DR_EXITING |
2423 CPU_BASED_USE_TSC_OFFSETTING |
2424 CPU_BASED_MWAIT_EXITING |
2425 CPU_BASED_MONITOR_EXITING |
2426 CPU_BASED_INVLPG_EXITING |
2427 CPU_BASED_RDPMC_EXITING;
2429 opt = CPU_BASED_TPR_SHADOW |
2430 CPU_BASED_USE_MSR_BITMAPS |
2431 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2432 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2433 &_cpu_based_exec_control) < 0)
2435 #ifdef CONFIG_X86_64
2436 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2437 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2438 ~CPU_BASED_CR8_STORE_EXITING;
2440 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2442 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2443 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2444 SECONDARY_EXEC_WBINVD_EXITING |
2445 SECONDARY_EXEC_ENABLE_VPID |
2446 SECONDARY_EXEC_ENABLE_EPT |
2447 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2448 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2449 SECONDARY_EXEC_DESC |
2450 SECONDARY_EXEC_RDTSCP |
2451 SECONDARY_EXEC_ENABLE_INVPCID |
2452 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2453 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2454 SECONDARY_EXEC_SHADOW_VMCS |
2455 SECONDARY_EXEC_XSAVES |
2456 SECONDARY_EXEC_RDSEED_EXITING |
2457 SECONDARY_EXEC_RDRAND_EXITING |
2458 SECONDARY_EXEC_ENABLE_PML |
2459 SECONDARY_EXEC_TSC_SCALING |
2460 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2461 SECONDARY_EXEC_PT_USE_GPA |
2462 SECONDARY_EXEC_PT_CONCEAL_VMX |
2463 SECONDARY_EXEC_ENABLE_VMFUNC;
2465 opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2466 if (adjust_vmx_controls(min2, opt2,
2467 MSR_IA32_VMX_PROCBASED_CTLS2,
2468 &_cpu_based_2nd_exec_control) < 0)
2471 #ifndef CONFIG_X86_64
2472 if (!(_cpu_based_2nd_exec_control &
2473 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2474 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2477 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2478 _cpu_based_2nd_exec_control &= ~(
2479 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2480 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2481 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2483 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2484 &vmx_cap->ept, &vmx_cap->vpid);
2486 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2487 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2489 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2490 CPU_BASED_CR3_STORE_EXITING |
2491 CPU_BASED_INVLPG_EXITING);
2492 } else if (vmx_cap->ept) {
2494 pr_warn_once("EPT CAP should not exist if not support "
2495 "1-setting enable EPT VM-execution control\n");
2497 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2500 pr_warn_once("VPID CAP should not exist if not support "
2501 "1-setting enable VPID VM-execution control\n");
2504 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2505 #ifdef CONFIG_X86_64
2506 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2508 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2509 VM_EXIT_LOAD_IA32_PAT |
2510 VM_EXIT_LOAD_IA32_EFER |
2511 VM_EXIT_CLEAR_BNDCFGS |
2512 VM_EXIT_PT_CONCEAL_PIP |
2513 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2514 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2515 &_vmexit_control) < 0)
2518 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2519 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2520 PIN_BASED_VMX_PREEMPTION_TIMER;
2521 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2522 &_pin_based_exec_control) < 0)
2525 if (cpu_has_broken_vmx_preemption_timer())
2526 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2527 if (!(_cpu_based_2nd_exec_control &
2528 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2529 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2531 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2532 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2533 VM_ENTRY_LOAD_IA32_PAT |
2534 VM_ENTRY_LOAD_IA32_EFER |
2535 VM_ENTRY_LOAD_BNDCFGS |
2536 VM_ENTRY_PT_CONCEAL_PIP |
2537 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2538 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2539 &_vmentry_control) < 0)
2543 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2544 * can't be used due to an errata where VM Exit may incorrectly clear
2545 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2546 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2548 if (boot_cpu_data.x86 == 0x6) {
2549 switch (boot_cpu_data.x86_model) {
2550 case 26: /* AAK155 */
2551 case 30: /* AAP115 */
2552 case 37: /* AAT100 */
2553 case 44: /* BC86,AAY89,BD102 */
2555 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2556 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2557 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2558 "does not work properly. Using workaround\n");
2566 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2568 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2569 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2572 #ifdef CONFIG_X86_64
2573 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2574 if (vmx_msr_high & (1u<<16))
2578 /* Require Write-Back (WB) memory type for VMCS accesses. */
2579 if (((vmx_msr_high >> 18) & 15) != 6)
2582 vmcs_conf->size = vmx_msr_high & 0x1fff;
2583 vmcs_conf->order = get_order(vmcs_conf->size);
2584 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2586 vmcs_conf->revision_id = vmx_msr_low;
2588 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2589 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2590 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2591 vmcs_conf->vmexit_ctrl = _vmexit_control;
2592 vmcs_conf->vmentry_ctrl = _vmentry_control;
2594 if (static_branch_unlikely(&enable_evmcs))
2595 evmcs_sanitize_exec_ctrls(vmcs_conf);
2600 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2602 int node = cpu_to_node(cpu);
2606 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2609 vmcs = page_address(pages);
2610 memset(vmcs, 0, vmcs_config.size);
2612 /* KVM supports Enlightened VMCS v1 only */
2613 if (static_branch_unlikely(&enable_evmcs))
2614 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2616 vmcs->hdr.revision_id = vmcs_config.revision_id;
2619 vmcs->hdr.shadow_vmcs = 1;
2623 void free_vmcs(struct vmcs *vmcs)
2625 free_pages((unsigned long)vmcs, vmcs_config.order);
2629 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2631 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2633 if (!loaded_vmcs->vmcs)
2635 loaded_vmcs_clear(loaded_vmcs);
2636 free_vmcs(loaded_vmcs->vmcs);
2637 loaded_vmcs->vmcs = NULL;
2638 if (loaded_vmcs->msr_bitmap)
2639 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2640 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2643 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2645 loaded_vmcs->vmcs = alloc_vmcs(false);
2646 if (!loaded_vmcs->vmcs)
2649 vmcs_clear(loaded_vmcs->vmcs);
2651 loaded_vmcs->shadow_vmcs = NULL;
2652 loaded_vmcs->hv_timer_soft_disabled = false;
2653 loaded_vmcs->cpu = -1;
2654 loaded_vmcs->launched = 0;
2656 if (cpu_has_vmx_msr_bitmap()) {
2657 loaded_vmcs->msr_bitmap = (unsigned long *)
2658 __get_free_page(GFP_KERNEL_ACCOUNT);
2659 if (!loaded_vmcs->msr_bitmap)
2661 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2663 if (IS_ENABLED(CONFIG_HYPERV) &&
2664 static_branch_unlikely(&enable_evmcs) &&
2665 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2666 struct hv_enlightened_vmcs *evmcs =
2667 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2669 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2673 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2674 memset(&loaded_vmcs->controls_shadow, 0,
2675 sizeof(struct vmcs_controls_shadow));
2680 free_loaded_vmcs(loaded_vmcs);
2684 static void free_kvm_area(void)
2688 for_each_possible_cpu(cpu) {
2689 free_vmcs(per_cpu(vmxarea, cpu));
2690 per_cpu(vmxarea, cpu) = NULL;
2694 static __init int alloc_kvm_area(void)
2698 for_each_possible_cpu(cpu) {
2701 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2708 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2709 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2710 * revision_id reported by MSR_IA32_VMX_BASIC.
2712 * However, even though not explicitly documented by
2713 * TLFS, VMXArea passed as VMXON argument should
2714 * still be marked with revision_id reported by
2717 if (static_branch_unlikely(&enable_evmcs))
2718 vmcs->hdr.revision_id = vmcs_config.revision_id;
2720 per_cpu(vmxarea, cpu) = vmcs;
2725 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2726 struct kvm_segment *save)
2728 if (!emulate_invalid_guest_state) {
2730 * CS and SS RPL should be equal during guest entry according
2731 * to VMX spec, but in reality it is not always so. Since vcpu
2732 * is in the middle of the transition from real mode to
2733 * protected mode it is safe to assume that RPL 0 is a good
2736 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2737 save->selector &= ~SEGMENT_RPL_MASK;
2738 save->dpl = save->selector & SEGMENT_RPL_MASK;
2741 vmx_set_segment(vcpu, save, seg);
2744 static void enter_pmode(struct kvm_vcpu *vcpu)
2746 unsigned long flags;
2747 struct vcpu_vmx *vmx = to_vmx(vcpu);
2750 * Update real mode segment cache. It may be not up-to-date if sement
2751 * register was written while vcpu was in a guest mode.
2753 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2754 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2755 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2756 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2757 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2758 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2760 vmx->rmode.vm86_active = 0;
2762 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2764 flags = vmcs_readl(GUEST_RFLAGS);
2765 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2766 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2767 vmcs_writel(GUEST_RFLAGS, flags);
2769 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2770 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2772 update_exception_bitmap(vcpu);
2774 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2775 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2776 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2777 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2778 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2779 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2782 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2784 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2785 struct kvm_segment var = *save;
2788 if (seg == VCPU_SREG_CS)
2791 if (!emulate_invalid_guest_state) {
2792 var.selector = var.base >> 4;
2793 var.base = var.base & 0xffff0;
2803 if (save->base & 0xf)
2804 printk_once(KERN_WARNING "kvm: segment base is not "
2805 "paragraph aligned when entering "
2806 "protected mode (seg=%d)", seg);
2809 vmcs_write16(sf->selector, var.selector);
2810 vmcs_writel(sf->base, var.base);
2811 vmcs_write32(sf->limit, var.limit);
2812 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2815 static void enter_rmode(struct kvm_vcpu *vcpu)
2817 unsigned long flags;
2818 struct vcpu_vmx *vmx = to_vmx(vcpu);
2819 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2821 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2822 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2823 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2824 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2825 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2826 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2827 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2829 vmx->rmode.vm86_active = 1;
2832 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2833 * vcpu. Warn the user that an update is overdue.
2835 if (!kvm_vmx->tss_addr)
2836 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2837 "called before entering vcpu\n");
2839 vmx_segment_cache_clear(vmx);
2841 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2842 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2843 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2845 flags = vmcs_readl(GUEST_RFLAGS);
2846 vmx->rmode.save_rflags = flags;
2848 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2850 vmcs_writel(GUEST_RFLAGS, flags);
2851 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2852 update_exception_bitmap(vcpu);
2854 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2855 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2856 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2857 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2858 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2859 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2861 kvm_mmu_reset_context(vcpu);
2864 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2866 struct vcpu_vmx *vmx = to_vmx(vcpu);
2867 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2872 vcpu->arch.efer = efer;
2873 if (efer & EFER_LMA) {
2874 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2877 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2879 msr->data = efer & ~EFER_LME;
2884 #ifdef CONFIG_X86_64
2886 static void enter_lmode(struct kvm_vcpu *vcpu)
2890 vmx_segment_cache_clear(to_vmx(vcpu));
2892 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2893 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2894 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2896 vmcs_write32(GUEST_TR_AR_BYTES,
2897 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2898 | VMX_AR_TYPE_BUSY_64_TSS);
2900 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2903 static void exit_lmode(struct kvm_vcpu *vcpu)
2905 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2906 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2911 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
2913 struct vcpu_vmx *vmx = to_vmx(vcpu);
2916 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
2917 * the CPU is not required to invalidate guest-physical mappings on
2918 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
2919 * associated with the root EPT structure and not any particular VPID
2920 * (INVVPID also isn't required to invalidate guest-physical mappings).
2924 } else if (enable_vpid) {
2925 if (cpu_has_vmx_invvpid_global()) {
2926 vpid_sync_vcpu_global();
2928 vpid_sync_vcpu_single(vmx->vpid);
2929 vpid_sync_vcpu_single(vmx->nested.vpid02);
2934 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
2936 u64 root_hpa = vcpu->arch.mmu->root_hpa;
2938 /* No flush required if the current context is invalid. */
2939 if (!VALID_PAGE(root_hpa))
2943 ept_sync_context(construct_eptp(vcpu, root_hpa));
2944 else if (!is_guest_mode(vcpu))
2945 vpid_sync_context(to_vmx(vcpu)->vpid);
2947 vpid_sync_context(nested_get_vpid02(vcpu));
2950 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2953 * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
2954 * vmx_flush_tlb_guest() for an explanation of why this is ok.
2956 vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
2959 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
2962 * vpid_sync_context() is a nop if vmx->vpid==0, e.g. if enable_vpid==0
2963 * or a vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit
2964 * are required to flush GVA->{G,H}PA mappings from the TLB if vpid is
2965 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
2966 * i.e. no explicit INVVPID is necessary.
2968 vpid_sync_context(to_vmx(vcpu)->vpid);
2971 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2973 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2975 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
2978 if (is_pae_paging(vcpu)) {
2979 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2980 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2981 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2982 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2986 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2988 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2990 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
2993 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2994 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2995 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2996 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2998 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
3001 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3003 struct kvm_vcpu *vcpu)
3005 struct vcpu_vmx *vmx = to_vmx(vcpu);
3007 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3008 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3009 if (!(cr0 & X86_CR0_PG)) {
3010 /* From paging/starting to nonpaging */
3011 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3012 CPU_BASED_CR3_STORE_EXITING);
3013 vcpu->arch.cr0 = cr0;
3014 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3015 } else if (!is_paging(vcpu)) {
3016 /* From nonpaging to paging */
3017 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3018 CPU_BASED_CR3_STORE_EXITING);
3019 vcpu->arch.cr0 = cr0;
3020 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3023 if (!(cr0 & X86_CR0_WP))
3024 *hw_cr0 &= ~X86_CR0_WP;
3027 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3029 struct vcpu_vmx *vmx = to_vmx(vcpu);
3030 unsigned long hw_cr0;
3032 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3033 if (enable_unrestricted_guest)
3034 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3036 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3038 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3041 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3045 #ifdef CONFIG_X86_64
3046 if (vcpu->arch.efer & EFER_LME) {
3047 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3049 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3054 if (enable_ept && !enable_unrestricted_guest)
3055 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3057 vmcs_writel(CR0_READ_SHADOW, cr0);
3058 vmcs_writel(GUEST_CR0, hw_cr0);
3059 vcpu->arch.cr0 = cr0;
3060 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3062 /* depends on vcpu->arch.cr0 to be set to a new value */
3063 vmx->emulation_required = emulation_required(vcpu);
3066 static int vmx_get_tdp_level(struct kvm_vcpu *vcpu)
3068 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
3073 static int get_ept_level(struct kvm_vcpu *vcpu)
3075 if (is_guest_mode(vcpu) && nested_cpu_has_ept(get_vmcs12(vcpu)))
3076 return vmx_eptp_page_walk_level(nested_ept_get_eptp(vcpu));
3078 return vmx_get_tdp_level(vcpu);
3081 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
3083 u64 eptp = VMX_EPTP_MT_WB;
3085 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3087 if (enable_ept_ad_bits &&
3088 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3089 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3090 eptp |= (root_hpa & PAGE_MASK);
3095 void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, unsigned long pgd)
3097 struct kvm *kvm = vcpu->kvm;
3098 bool update_guest_cr3 = true;
3099 unsigned long guest_cr3;
3103 eptp = construct_eptp(vcpu, pgd);
3104 vmcs_write64(EPT_POINTER, eptp);
3106 if (kvm_x86_ops.tlb_remote_flush) {
3107 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3108 to_vmx(vcpu)->ept_pointer = eptp;
3109 to_kvm_vmx(kvm)->ept_pointers_match
3110 = EPT_POINTERS_CHECK;
3111 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3114 if (!enable_unrestricted_guest && !is_paging(vcpu))
3115 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3116 else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3117 guest_cr3 = vcpu->arch.cr3;
3118 else /* vmcs01.GUEST_CR3 is already up-to-date. */
3119 update_guest_cr3 = false;
3120 ept_load_pdptrs(vcpu);
3125 if (update_guest_cr3)
3126 vmcs_writel(GUEST_CR3, guest_cr3);
3129 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3131 struct vcpu_vmx *vmx = to_vmx(vcpu);
3133 * Pass through host's Machine Check Enable value to hw_cr4, which
3134 * is in force while we are in guest mode. Do not let guests control
3135 * this bit, even if host CR4.MCE == 0.
3137 unsigned long hw_cr4;
3139 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3140 if (enable_unrestricted_guest)
3141 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3142 else if (vmx->rmode.vm86_active)
3143 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3145 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3147 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3148 if (cr4 & X86_CR4_UMIP) {
3149 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3150 hw_cr4 &= ~X86_CR4_UMIP;
3151 } else if (!is_guest_mode(vcpu) ||
3152 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3153 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3157 if (cr4 & X86_CR4_VMXE) {
3159 * To use VMXON (and later other VMX instructions), a guest
3160 * must first be able to turn on cr4.VMXE (see handle_vmon()).
3161 * So basically the check on whether to allow nested VMX
3162 * is here. We operate under the default treatment of SMM,
3163 * so VMX cannot be enabled under SMM.
3165 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
3169 if (vmx->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3172 vcpu->arch.cr4 = cr4;
3173 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3175 if (!enable_unrestricted_guest) {
3177 if (!is_paging(vcpu)) {
3178 hw_cr4 &= ~X86_CR4_PAE;
3179 hw_cr4 |= X86_CR4_PSE;
3180 } else if (!(cr4 & X86_CR4_PAE)) {
3181 hw_cr4 &= ~X86_CR4_PAE;
3186 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3187 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3188 * to be manually disabled when guest switches to non-paging
3191 * If !enable_unrestricted_guest, the CPU is always running
3192 * with CR0.PG=1 and CR4 needs to be modified.
3193 * If enable_unrestricted_guest, the CPU automatically
3194 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3196 if (!is_paging(vcpu))
3197 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3200 vmcs_writel(CR4_READ_SHADOW, cr4);
3201 vmcs_writel(GUEST_CR4, hw_cr4);
3205 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3207 struct vcpu_vmx *vmx = to_vmx(vcpu);
3210 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3211 *var = vmx->rmode.segs[seg];
3212 if (seg == VCPU_SREG_TR
3213 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3215 var->base = vmx_read_guest_seg_base(vmx, seg);
3216 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3219 var->base = vmx_read_guest_seg_base(vmx, seg);
3220 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3221 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3222 ar = vmx_read_guest_seg_ar(vmx, seg);
3223 var->unusable = (ar >> 16) & 1;
3224 var->type = ar & 15;
3225 var->s = (ar >> 4) & 1;
3226 var->dpl = (ar >> 5) & 3;
3228 * Some userspaces do not preserve unusable property. Since usable
3229 * segment has to be present according to VMX spec we can use present
3230 * property to amend userspace bug by making unusable segment always
3231 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3232 * segment as unusable.
3234 var->present = !var->unusable;
3235 var->avl = (ar >> 12) & 1;
3236 var->l = (ar >> 13) & 1;
3237 var->db = (ar >> 14) & 1;
3238 var->g = (ar >> 15) & 1;
3241 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3243 struct kvm_segment s;
3245 if (to_vmx(vcpu)->rmode.vm86_active) {
3246 vmx_get_segment(vcpu, &s, seg);
3249 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3252 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3254 struct vcpu_vmx *vmx = to_vmx(vcpu);
3256 if (unlikely(vmx->rmode.vm86_active))
3259 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3260 return VMX_AR_DPL(ar);
3264 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3268 if (var->unusable || !var->present)
3271 ar = var->type & 15;
3272 ar |= (var->s & 1) << 4;
3273 ar |= (var->dpl & 3) << 5;
3274 ar |= (var->present & 1) << 7;
3275 ar |= (var->avl & 1) << 12;
3276 ar |= (var->l & 1) << 13;
3277 ar |= (var->db & 1) << 14;
3278 ar |= (var->g & 1) << 15;
3284 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3286 struct vcpu_vmx *vmx = to_vmx(vcpu);
3287 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3289 vmx_segment_cache_clear(vmx);
3291 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3292 vmx->rmode.segs[seg] = *var;
3293 if (seg == VCPU_SREG_TR)
3294 vmcs_write16(sf->selector, var->selector);
3296 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3300 vmcs_writel(sf->base, var->base);
3301 vmcs_write32(sf->limit, var->limit);
3302 vmcs_write16(sf->selector, var->selector);
3305 * Fix the "Accessed" bit in AR field of segment registers for older
3307 * IA32 arch specifies that at the time of processor reset the
3308 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3309 * is setting it to 0 in the userland code. This causes invalid guest
3310 * state vmexit when "unrestricted guest" mode is turned on.
3311 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3312 * tree. Newer qemu binaries with that qemu fix would not need this
3315 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3316 var->type |= 0x1; /* Accessed */
3318 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3321 vmx->emulation_required = emulation_required(vcpu);
3324 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3326 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3328 *db = (ar >> 14) & 1;
3329 *l = (ar >> 13) & 1;
3332 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3334 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3335 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3338 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3340 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3341 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3344 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3346 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3347 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3350 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3352 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3353 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3356 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3358 struct kvm_segment var;
3361 vmx_get_segment(vcpu, &var, seg);
3363 if (seg == VCPU_SREG_CS)
3365 ar = vmx_segment_access_rights(&var);
3367 if (var.base != (var.selector << 4))
3369 if (var.limit != 0xffff)
3377 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3379 struct kvm_segment cs;
3380 unsigned int cs_rpl;
3382 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3383 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3387 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3391 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3392 if (cs.dpl > cs_rpl)
3395 if (cs.dpl != cs_rpl)
3401 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3405 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3407 struct kvm_segment ss;
3408 unsigned int ss_rpl;
3410 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3411 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3415 if (ss.type != 3 && ss.type != 7)
3419 if (ss.dpl != ss_rpl) /* DPL != RPL */
3427 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3429 struct kvm_segment var;
3432 vmx_get_segment(vcpu, &var, seg);
3433 rpl = var.selector & SEGMENT_RPL_MASK;
3441 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3442 if (var.dpl < rpl) /* DPL < RPL */
3446 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3452 static bool tr_valid(struct kvm_vcpu *vcpu)
3454 struct kvm_segment tr;
3456 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3460 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3462 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3470 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3472 struct kvm_segment ldtr;
3474 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3478 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3488 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3490 struct kvm_segment cs, ss;
3492 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3493 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3495 return ((cs.selector & SEGMENT_RPL_MASK) ==
3496 (ss.selector & SEGMENT_RPL_MASK));
3500 * Check if guest state is valid. Returns true if valid, false if
3502 * We assume that registers are always usable
3504 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3506 if (enable_unrestricted_guest)
3509 /* real mode guest state checks */
3510 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3511 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3513 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3515 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3517 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3519 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3521 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3524 /* protected mode guest state checks */
3525 if (!cs_ss_rpl_check(vcpu))
3527 if (!code_segment_valid(vcpu))
3529 if (!stack_segment_valid(vcpu))
3531 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3533 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3535 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3537 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3539 if (!tr_valid(vcpu))
3541 if (!ldtr_valid(vcpu))
3545 * - Add checks on RIP
3546 * - Add checks on RFLAGS
3552 static int init_rmode_tss(struct kvm *kvm)
3558 idx = srcu_read_lock(&kvm->srcu);
3559 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3560 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3563 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3564 r = kvm_write_guest_page(kvm, fn++, &data,
3565 TSS_IOPB_BASE_OFFSET, sizeof(u16));
3568 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3571 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3575 r = kvm_write_guest_page(kvm, fn, &data,
3576 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3579 srcu_read_unlock(&kvm->srcu, idx);
3583 static int init_rmode_identity_map(struct kvm *kvm)
3585 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3587 kvm_pfn_t identity_map_pfn;
3590 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3591 mutex_lock(&kvm->slots_lock);
3593 if (likely(kvm_vmx->ept_identity_pagetable_done))
3596 if (!kvm_vmx->ept_identity_map_addr)
3597 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3598 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3600 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3601 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3605 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3608 /* Set up identity-mapping pagetable for EPT in real mode */
3609 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3610 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3611 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3612 r = kvm_write_guest_page(kvm, identity_map_pfn,
3613 &tmp, i * sizeof(tmp), sizeof(tmp));
3617 kvm_vmx->ept_identity_pagetable_done = true;
3620 mutex_unlock(&kvm->slots_lock);
3624 static void seg_setup(int seg)
3626 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3629 vmcs_write16(sf->selector, 0);
3630 vmcs_writel(sf->base, 0);
3631 vmcs_write32(sf->limit, 0xffff);
3633 if (seg == VCPU_SREG_CS)
3634 ar |= 0x08; /* code segment */
3636 vmcs_write32(sf->ar_bytes, ar);
3639 static int alloc_apic_access_page(struct kvm *kvm)
3644 mutex_lock(&kvm->slots_lock);
3645 if (kvm->arch.apic_access_page_done)
3647 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3648 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3652 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3653 if (is_error_page(page)) {
3659 * Do not pin the page in memory, so that memory hot-unplug
3660 * is able to migrate it.
3663 kvm->arch.apic_access_page_done = true;
3665 mutex_unlock(&kvm->slots_lock);
3669 int allocate_vpid(void)
3675 spin_lock(&vmx_vpid_lock);
3676 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3677 if (vpid < VMX_NR_VPIDS)
3678 __set_bit(vpid, vmx_vpid_bitmap);
3681 spin_unlock(&vmx_vpid_lock);
3685 void free_vpid(int vpid)
3687 if (!enable_vpid || vpid == 0)
3689 spin_lock(&vmx_vpid_lock);
3690 __clear_bit(vpid, vmx_vpid_bitmap);
3691 spin_unlock(&vmx_vpid_lock);
3694 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3697 int f = sizeof(unsigned long);
3699 if (!cpu_has_vmx_msr_bitmap())
3702 if (static_branch_unlikely(&enable_evmcs))
3703 evmcs_touch_msr_bitmap();
3706 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3707 * have the write-low and read-high bitmap offsets the wrong way round.
3708 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3710 if (msr <= 0x1fff) {
3711 if (type & MSR_TYPE_R)
3713 __clear_bit(msr, msr_bitmap + 0x000 / f);
3715 if (type & MSR_TYPE_W)
3717 __clear_bit(msr, msr_bitmap + 0x800 / f);
3719 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3721 if (type & MSR_TYPE_R)
3723 __clear_bit(msr, msr_bitmap + 0x400 / f);
3725 if (type & MSR_TYPE_W)
3727 __clear_bit(msr, msr_bitmap + 0xc00 / f);
3732 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3735 int f = sizeof(unsigned long);
3737 if (!cpu_has_vmx_msr_bitmap())
3740 if (static_branch_unlikely(&enable_evmcs))
3741 evmcs_touch_msr_bitmap();
3744 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3745 * have the write-low and read-high bitmap offsets the wrong way round.
3746 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3748 if (msr <= 0x1fff) {
3749 if (type & MSR_TYPE_R)
3751 __set_bit(msr, msr_bitmap + 0x000 / f);
3753 if (type & MSR_TYPE_W)
3755 __set_bit(msr, msr_bitmap + 0x800 / f);
3757 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3759 if (type & MSR_TYPE_R)
3761 __set_bit(msr, msr_bitmap + 0x400 / f);
3763 if (type & MSR_TYPE_W)
3765 __set_bit(msr, msr_bitmap + 0xc00 / f);
3770 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3771 u32 msr, int type, bool value)
3774 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3776 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3779 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3783 if (cpu_has_secondary_exec_ctrls() &&
3784 (secondary_exec_controls_get(to_vmx(vcpu)) &
3785 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3786 mode |= MSR_BITMAP_MODE_X2APIC;
3787 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3788 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3794 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3799 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3800 unsigned word = msr / BITS_PER_LONG;
3801 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3802 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3805 if (mode & MSR_BITMAP_MODE_X2APIC) {
3807 * TPR reads and writes can be virtualized even if virtual interrupt
3808 * delivery is not in use.
3810 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3811 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3812 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3813 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3814 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3819 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3821 struct vcpu_vmx *vmx = to_vmx(vcpu);
3822 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3823 u8 mode = vmx_msr_bitmap_mode(vcpu);
3824 u8 changed = mode ^ vmx->msr_bitmap_mode;
3829 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3830 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3832 vmx->msr_bitmap_mode = mode;
3835 void pt_update_intercept_for_msr(struct vcpu_vmx *vmx)
3837 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3838 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3841 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_STATUS,
3843 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_BASE,
3845 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_MASK,
3847 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_CR3_MATCH,
3849 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3850 vmx_set_intercept_for_msr(msr_bitmap,
3851 MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3852 vmx_set_intercept_for_msr(msr_bitmap,
3853 MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3857 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3859 struct vcpu_vmx *vmx = to_vmx(vcpu);
3864 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3865 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3866 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3869 rvi = vmx_get_rvi();
3871 vapic_page = vmx->nested.virtual_apic_map.hva;
3872 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3874 return ((rvi & 0xf0) > (vppr & 0xf0));
3877 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3881 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3883 if (vcpu->mode == IN_GUEST_MODE) {
3885 * The vector of interrupt to be delivered to vcpu had
3886 * been set in PIR before this function.
3888 * Following cases will be reached in this block, and
3889 * we always send a notification event in all cases as
3892 * Case 1: vcpu keeps in non-root mode. Sending a
3893 * notification event posts the interrupt to vcpu.
3895 * Case 2: vcpu exits to root mode and is still
3896 * runnable. PIR will be synced to vIRR before the
3897 * next vcpu entry. Sending a notification event in
3898 * this case has no effect, as vcpu is not in root
3901 * Case 3: vcpu exits to root mode and is blocked.
3902 * vcpu_block() has already synced PIR to vIRR and
3903 * never blocks vcpu if vIRR is not cleared. Therefore,
3904 * a blocked vcpu here does not wait for any requested
3905 * interrupts in PIR, and sending a notification event
3906 * which has no effect is safe here.
3909 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3916 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3919 struct vcpu_vmx *vmx = to_vmx(vcpu);
3921 if (is_guest_mode(vcpu) &&
3922 vector == vmx->nested.posted_intr_nv) {
3924 * If a posted intr is not recognized by hardware,
3925 * we will accomplish it in the next vmentry.
3927 vmx->nested.pi_pending = true;
3928 kvm_make_request(KVM_REQ_EVENT, vcpu);
3929 /* the PIR and ON have been set by L1. */
3930 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3931 kvm_vcpu_kick(vcpu);
3937 * Send interrupt to vcpu via posted interrupt way.
3938 * 1. If target vcpu is running(non-root mode), send posted interrupt
3939 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3940 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3941 * interrupt from PIR in next vmentry.
3943 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3945 struct vcpu_vmx *vmx = to_vmx(vcpu);
3948 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3952 if (!vcpu->arch.apicv_active)
3955 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3958 /* If a previous notification has sent the IPI, nothing to do. */
3959 if (pi_test_and_set_on(&vmx->pi_desc))
3962 if (vcpu != kvm_get_running_vcpu() &&
3963 !kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3964 kvm_vcpu_kick(vcpu);
3970 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3971 * will not change in the lifetime of the guest.
3972 * Note that host-state that does change is set elsewhere. E.g., host-state
3973 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3975 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3979 unsigned long cr0, cr3, cr4;
3982 WARN_ON(cr0 & X86_CR0_TS);
3983 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
3986 * Save the most likely value for this task's CR3 in the VMCS.
3987 * We can't use __get_current_cr3_fast() because we're not atomic.
3990 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
3991 vmx->loaded_vmcs->host_state.cr3 = cr3;
3993 /* Save the most likely value for this task's CR4 in the VMCS. */
3994 cr4 = cr4_read_shadow();
3995 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
3996 vmx->loaded_vmcs->host_state.cr4 = cr4;
3998 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
3999 #ifdef CONFIG_X86_64
4001 * Load null selectors, so we can avoid reloading them in
4002 * vmx_prepare_switch_to_host(), in case userspace uses
4003 * the null selectors too (the expected case).
4005 vmcs_write16(HOST_DS_SELECTOR, 0);
4006 vmcs_write16(HOST_ES_SELECTOR, 0);
4008 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4009 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4011 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4012 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4014 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4016 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4018 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4019 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4020 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4021 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4023 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4024 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4025 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4028 if (cpu_has_load_ia32_efer())
4029 vmcs_write64(HOST_IA32_EFER, host_efer);
4032 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4034 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS;
4036 vmx->vcpu.arch.cr4_guest_owned_bits &= ~X86_CR4_PGE;
4037 if (is_guest_mode(&vmx->vcpu))
4038 vmx->vcpu.arch.cr4_guest_owned_bits &=
4039 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
4040 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
4043 u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4045 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4047 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4048 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4051 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4053 if (!enable_preemption_timer)
4054 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4056 return pin_based_exec_ctrl;
4059 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4061 struct vcpu_vmx *vmx = to_vmx(vcpu);
4063 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4064 if (cpu_has_secondary_exec_ctrls()) {
4065 if (kvm_vcpu_apicv_active(vcpu))
4066 secondary_exec_controls_setbit(vmx,
4067 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4068 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4070 secondary_exec_controls_clearbit(vmx,
4071 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4072 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4075 if (cpu_has_vmx_msr_bitmap())
4076 vmx_update_msr_bitmap(vcpu);
4079 u32 vmx_exec_control(struct vcpu_vmx *vmx)
4081 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4083 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4084 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4086 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4087 exec_control &= ~CPU_BASED_TPR_SHADOW;
4088 #ifdef CONFIG_X86_64
4089 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4090 CPU_BASED_CR8_LOAD_EXITING;
4094 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4095 CPU_BASED_CR3_LOAD_EXITING |
4096 CPU_BASED_INVLPG_EXITING;
4097 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4098 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4099 CPU_BASED_MONITOR_EXITING);
4100 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4101 exec_control &= ~CPU_BASED_HLT_EXITING;
4102 return exec_control;
4106 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
4108 struct kvm_vcpu *vcpu = &vmx->vcpu;
4110 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4112 if (vmx_pt_mode_is_system())
4113 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4114 if (!cpu_need_virtualize_apic_accesses(vcpu))
4115 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4117 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4119 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4120 enable_unrestricted_guest = 0;
4122 if (!enable_unrestricted_guest)
4123 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4124 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4125 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4126 if (!kvm_vcpu_apicv_active(vcpu))
4127 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4128 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4129 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4131 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4132 * in vmx_set_cr4. */
4133 exec_control &= ~SECONDARY_EXEC_DESC;
4135 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4137 We can NOT enable shadow_vmcs here because we don't have yet
4140 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4143 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4145 if (vmx_xsaves_supported()) {
4146 /* Exposing XSAVES only when XSAVE is exposed */
4147 bool xsaves_enabled =
4148 boot_cpu_has(X86_FEATURE_XSAVE) &&
4149 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4150 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4152 vcpu->arch.xsaves_enabled = xsaves_enabled;
4154 if (!xsaves_enabled)
4155 exec_control &= ~SECONDARY_EXEC_XSAVES;
4159 vmx->nested.msrs.secondary_ctls_high |=
4160 SECONDARY_EXEC_XSAVES;
4162 vmx->nested.msrs.secondary_ctls_high &=
4163 ~SECONDARY_EXEC_XSAVES;
4167 if (cpu_has_vmx_rdtscp()) {
4168 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
4169 if (!rdtscp_enabled)
4170 exec_control &= ~SECONDARY_EXEC_RDTSCP;
4174 vmx->nested.msrs.secondary_ctls_high |=
4175 SECONDARY_EXEC_RDTSCP;
4177 vmx->nested.msrs.secondary_ctls_high &=
4178 ~SECONDARY_EXEC_RDTSCP;
4182 if (cpu_has_vmx_invpcid()) {
4183 /* Exposing INVPCID only when PCID is exposed */
4184 bool invpcid_enabled =
4185 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
4186 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
4188 if (!invpcid_enabled) {
4189 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
4190 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
4194 if (invpcid_enabled)
4195 vmx->nested.msrs.secondary_ctls_high |=
4196 SECONDARY_EXEC_ENABLE_INVPCID;
4198 vmx->nested.msrs.secondary_ctls_high &=
4199 ~SECONDARY_EXEC_ENABLE_INVPCID;
4203 if (vmx_rdrand_supported()) {
4204 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
4206 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
4210 vmx->nested.msrs.secondary_ctls_high |=
4211 SECONDARY_EXEC_RDRAND_EXITING;
4213 vmx->nested.msrs.secondary_ctls_high &=
4214 ~SECONDARY_EXEC_RDRAND_EXITING;
4218 if (vmx_rdseed_supported()) {
4219 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
4221 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
4225 vmx->nested.msrs.secondary_ctls_high |=
4226 SECONDARY_EXEC_RDSEED_EXITING;
4228 vmx->nested.msrs.secondary_ctls_high &=
4229 ~SECONDARY_EXEC_RDSEED_EXITING;
4233 if (vmx_waitpkg_supported()) {
4234 bool waitpkg_enabled =
4235 guest_cpuid_has(vcpu, X86_FEATURE_WAITPKG);
4237 if (!waitpkg_enabled)
4238 exec_control &= ~SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4241 if (waitpkg_enabled)
4242 vmx->nested.msrs.secondary_ctls_high |=
4243 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4245 vmx->nested.msrs.secondary_ctls_high &=
4246 ~SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4250 vmx->secondary_exec_control = exec_control;
4253 static void ept_set_mmio_spte_mask(void)
4256 * EPT Misconfigurations can be generated if the value of bits 2:0
4257 * of an EPT paging-structure entry is 110b (write/execute).
4259 kvm_mmu_set_mmio_spte_mask(VMX_EPT_MISCONFIG_WX_VALUE, 0);
4262 #define VMX_XSS_EXIT_BITMAP 0
4265 * Noting that the initialization of Guest-state Area of VMCS is in
4268 static void init_vmcs(struct vcpu_vmx *vmx)
4271 nested_vmx_set_vmcs_shadowing_bitmap();
4273 if (cpu_has_vmx_msr_bitmap())
4274 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4276 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4279 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4281 exec_controls_set(vmx, vmx_exec_control(vmx));
4283 if (cpu_has_secondary_exec_ctrls()) {
4284 vmx_compute_secondary_exec_control(vmx);
4285 secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
4288 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4289 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4290 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4291 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4292 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4294 vmcs_write16(GUEST_INTR_STATUS, 0);
4296 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4297 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4300 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4301 vmcs_write32(PLE_GAP, ple_gap);
4302 vmx->ple_window = ple_window;
4303 vmx->ple_window_dirty = true;
4306 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4307 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4308 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4310 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4311 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4312 vmx_set_constant_host_state(vmx);
4313 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4314 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4316 if (cpu_has_vmx_vmfunc())
4317 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4319 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4320 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4321 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4322 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4323 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4325 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4326 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4328 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4330 /* 22.2.1, 20.8.1 */
4331 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4333 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4334 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4336 set_cr4_guest_host_mask(vmx);
4339 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4341 if (vmx_xsaves_supported())
4342 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4345 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4346 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4349 if (cpu_has_vmx_encls_vmexit())
4350 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
4352 if (vmx_pt_mode_is_host_guest()) {
4353 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4354 /* Bit[6~0] are forced to 1, writes are ignored. */
4355 vmx->pt_desc.guest.output_mask = 0x7F;
4356 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4360 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4362 struct vcpu_vmx *vmx = to_vmx(vcpu);
4363 struct msr_data apic_base_msr;
4366 vmx->rmode.vm86_active = 0;
4369 vmx->msr_ia32_umwait_control = 0;
4371 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4372 vmx->hv_deadline_tsc = -1;
4373 kvm_set_cr8(vcpu, 0);
4376 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4377 MSR_IA32_APICBASE_ENABLE;
4378 if (kvm_vcpu_is_reset_bsp(vcpu))
4379 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4380 apic_base_msr.host_initiated = true;
4381 kvm_set_apic_base(vcpu, &apic_base_msr);
4384 vmx_segment_cache_clear(vmx);
4386 seg_setup(VCPU_SREG_CS);
4387 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4388 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4390 seg_setup(VCPU_SREG_DS);
4391 seg_setup(VCPU_SREG_ES);
4392 seg_setup(VCPU_SREG_FS);
4393 seg_setup(VCPU_SREG_GS);
4394 seg_setup(VCPU_SREG_SS);
4396 vmcs_write16(GUEST_TR_SELECTOR, 0);
4397 vmcs_writel(GUEST_TR_BASE, 0);
4398 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4399 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4401 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4402 vmcs_writel(GUEST_LDTR_BASE, 0);
4403 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4404 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4407 vmcs_write32(GUEST_SYSENTER_CS, 0);
4408 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4409 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4410 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4413 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4414 kvm_rip_write(vcpu, 0xfff0);
4416 vmcs_writel(GUEST_GDTR_BASE, 0);
4417 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4419 vmcs_writel(GUEST_IDTR_BASE, 0);
4420 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4422 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4423 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4424 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4425 if (kvm_mpx_supported())
4426 vmcs_write64(GUEST_BNDCFGS, 0);
4430 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4432 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4433 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4434 if (cpu_need_tpr_shadow(vcpu))
4435 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4436 __pa(vcpu->arch.apic->regs));
4437 vmcs_write32(TPR_THRESHOLD, 0);
4440 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4442 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4443 vmx->vcpu.arch.cr0 = cr0;
4444 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4445 vmx_set_cr4(vcpu, 0);
4446 vmx_set_efer(vcpu, 0);
4448 update_exception_bitmap(vcpu);
4450 vpid_sync_context(vmx->vpid);
4452 vmx_clear_hlt(vcpu);
4455 static void enable_irq_window(struct kvm_vcpu *vcpu)
4457 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4460 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4463 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4464 enable_irq_window(vcpu);
4468 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4471 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4473 struct vcpu_vmx *vmx = to_vmx(vcpu);
4475 int irq = vcpu->arch.interrupt.nr;
4477 trace_kvm_inj_virq(irq);
4479 ++vcpu->stat.irq_injections;
4480 if (vmx->rmode.vm86_active) {
4482 if (vcpu->arch.interrupt.soft)
4483 inc_eip = vcpu->arch.event_exit_inst_len;
4484 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4487 intr = irq | INTR_INFO_VALID_MASK;
4488 if (vcpu->arch.interrupt.soft) {
4489 intr |= INTR_TYPE_SOFT_INTR;
4490 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4491 vmx->vcpu.arch.event_exit_inst_len);
4493 intr |= INTR_TYPE_EXT_INTR;
4494 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4496 vmx_clear_hlt(vcpu);
4499 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4501 struct vcpu_vmx *vmx = to_vmx(vcpu);
4505 * Tracking the NMI-blocked state in software is built upon
4506 * finding the next open IRQ window. This, in turn, depends on
4507 * well-behaving guests: They have to keep IRQs disabled at
4508 * least as long as the NMI handler runs. Otherwise we may
4509 * cause NMI nesting, maybe breaking the guest. But as this is
4510 * highly unlikely, we can live with the residual risk.
4512 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4513 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4516 ++vcpu->stat.nmi_injections;
4517 vmx->loaded_vmcs->nmi_known_unmasked = false;
4519 if (vmx->rmode.vm86_active) {
4520 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4524 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4525 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4527 vmx_clear_hlt(vcpu);
4530 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4532 struct vcpu_vmx *vmx = to_vmx(vcpu);
4536 return vmx->loaded_vmcs->soft_vnmi_blocked;
4537 if (vmx->loaded_vmcs->nmi_known_unmasked)
4539 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4540 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4544 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4546 struct vcpu_vmx *vmx = to_vmx(vcpu);
4549 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4550 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4551 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4554 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4556 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4557 GUEST_INTR_STATE_NMI);
4559 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4560 GUEST_INTR_STATE_NMI);
4564 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4566 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4569 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4572 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4573 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4574 GUEST_INTR_STATE_NMI));
4577 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4579 if (to_vmx(vcpu)->nested.nested_run_pending)
4582 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4583 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4586 return !vmx_nmi_blocked(vcpu);
4589 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4591 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4594 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4595 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4596 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4599 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4601 if (to_vmx(vcpu)->nested.nested_run_pending)
4605 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4606 * e.g. if the IRQ arrived asynchronously after checking nested events.
4608 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4611 return !vmx_interrupt_blocked(vcpu);
4614 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4618 if (enable_unrestricted_guest)
4621 mutex_lock(&kvm->slots_lock);
4622 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4624 mutex_unlock(&kvm->slots_lock);
4628 to_kvm_vmx(kvm)->tss_addr = addr;
4629 return init_rmode_tss(kvm);
4632 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4634 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4638 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4643 * Update instruction length as we may reinject the exception
4644 * from user space while in guest debugging mode.
4646 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4647 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4648 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4652 return !(vcpu->guest_debug &
4653 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4667 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4668 int vec, u32 err_code)
4671 * Instruction with address size override prefix opcode 0x67
4672 * Cause the #SS fault with 0 error code in VM86 mode.
4674 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4675 if (kvm_emulate_instruction(vcpu, 0)) {
4676 if (vcpu->arch.halt_request) {
4677 vcpu->arch.halt_request = 0;
4678 return kvm_vcpu_halt(vcpu);
4686 * Forward all other exceptions that are valid in real mode.
4687 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4688 * the required debugging infrastructure rework.
4690 kvm_queue_exception(vcpu, vec);
4695 * Trigger machine check on the host. We assume all the MSRs are already set up
4696 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4697 * We pass a fake environment to the machine check handler because we want
4698 * the guest to be always treated like user space, no matter what context
4699 * it used internally.
4701 static void kvm_machine_check(void)
4703 #if defined(CONFIG_X86_MCE)
4704 struct pt_regs regs = {
4705 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4706 .flags = X86_EFLAGS_IF,
4709 do_machine_check(®s);
4713 static int handle_machine_check(struct kvm_vcpu *vcpu)
4715 /* handled by vmx_vcpu_run() */
4720 * If the host has split lock detection disabled, then #AC is
4721 * unconditionally injected into the guest, which is the pre split lock
4722 * detection behaviour.
4724 * If the host has split lock detection enabled then #AC is
4725 * only injected into the guest when:
4726 * - Guest CPL == 3 (user mode)
4727 * - Guest has #AC detection enabled in CR0
4728 * - Guest EFLAGS has AC bit set
4730 static inline bool guest_inject_ac(struct kvm_vcpu *vcpu)
4732 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4735 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4736 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4739 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4741 struct vcpu_vmx *vmx = to_vmx(vcpu);
4742 struct kvm_run *kvm_run = vcpu->run;
4743 u32 intr_info, ex_no, error_code;
4744 unsigned long cr2, rip, dr6;
4747 vect_info = vmx->idt_vectoring_info;
4748 intr_info = vmx_get_intr_info(vcpu);
4750 if (is_machine_check(intr_info) || is_nmi(intr_info))
4751 return 1; /* handled by handle_exception_nmi_irqoff() */
4753 if (is_invalid_opcode(intr_info))
4754 return handle_ud(vcpu);
4757 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4758 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4760 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4761 WARN_ON_ONCE(!enable_vmware_backdoor);
4764 * VMware backdoor emulation on #GP interception only handles
4765 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4766 * error code on #GP.
4769 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4772 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4776 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4777 * MMIO, it is better to report an internal error.
4778 * See the comments in vmx_handle_exit.
4780 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4781 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4782 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4783 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4784 vcpu->run->internal.ndata = 4;
4785 vcpu->run->internal.data[0] = vect_info;
4786 vcpu->run->internal.data[1] = intr_info;
4787 vcpu->run->internal.data[2] = error_code;
4788 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
4792 if (is_page_fault(intr_info)) {
4793 cr2 = vmx_get_exit_qual(vcpu);
4794 /* EPT won't cause page fault directly */
4795 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_flags && enable_ept);
4796 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4799 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4801 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4802 return handle_rmode_exception(vcpu, ex_no, error_code);
4806 dr6 = vmx_get_exit_qual(vcpu);
4807 if (!(vcpu->guest_debug &
4808 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4809 if (is_icebp(intr_info))
4810 WARN_ON(!skip_emulated_instruction(vcpu));
4812 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
4815 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
4816 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4820 * Update instruction length as we may reinject #BP from
4821 * user space while in guest debugging mode. Reading it for
4822 * #DB as well causes no harm, it is not used in that case.
4824 vmx->vcpu.arch.event_exit_inst_len =
4825 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4826 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4827 rip = kvm_rip_read(vcpu);
4828 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4829 kvm_run->debug.arch.exception = ex_no;
4832 if (guest_inject_ac(vcpu)) {
4833 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4838 * Handle split lock. Depending on detection mode this will
4839 * either warn and disable split lock detection for this
4840 * task or force SIGBUS on it.
4842 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4846 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4847 kvm_run->ex.exception = ex_no;
4848 kvm_run->ex.error_code = error_code;
4854 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4856 ++vcpu->stat.irq_exits;
4860 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4862 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4863 vcpu->mmio_needed = 0;
4867 static int handle_io(struct kvm_vcpu *vcpu)
4869 unsigned long exit_qualification;
4870 int size, in, string;
4873 exit_qualification = vmx_get_exit_qual(vcpu);
4874 string = (exit_qualification & 16) != 0;
4876 ++vcpu->stat.io_exits;
4879 return kvm_emulate_instruction(vcpu, 0);
4881 port = exit_qualification >> 16;
4882 size = (exit_qualification & 7) + 1;
4883 in = (exit_qualification & 8) != 0;
4885 return kvm_fast_pio(vcpu, size, port, in);
4889 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4892 * Patch in the VMCALL instruction:
4894 hypercall[0] = 0x0f;
4895 hypercall[1] = 0x01;
4896 hypercall[2] = 0xc1;
4899 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4900 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4902 if (is_guest_mode(vcpu)) {
4903 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4904 unsigned long orig_val = val;
4907 * We get here when L2 changed cr0 in a way that did not change
4908 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4909 * but did change L0 shadowed bits. So we first calculate the
4910 * effective cr0 value that L1 would like to write into the
4911 * hardware. It consists of the L2-owned bits from the new
4912 * value combined with the L1-owned bits from L1's guest_cr0.
4914 val = (val & ~vmcs12->cr0_guest_host_mask) |
4915 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4917 if (!nested_guest_cr0_valid(vcpu, val))
4920 if (kvm_set_cr0(vcpu, val))
4922 vmcs_writel(CR0_READ_SHADOW, orig_val);
4925 if (to_vmx(vcpu)->nested.vmxon &&
4926 !nested_host_cr0_valid(vcpu, val))
4929 return kvm_set_cr0(vcpu, val);
4933 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4935 if (is_guest_mode(vcpu)) {
4936 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4937 unsigned long orig_val = val;
4939 /* analogously to handle_set_cr0 */
4940 val = (val & ~vmcs12->cr4_guest_host_mask) |
4941 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4942 if (kvm_set_cr4(vcpu, val))
4944 vmcs_writel(CR4_READ_SHADOW, orig_val);
4947 return kvm_set_cr4(vcpu, val);
4950 static int handle_desc(struct kvm_vcpu *vcpu)
4952 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4953 return kvm_emulate_instruction(vcpu, 0);
4956 static int handle_cr(struct kvm_vcpu *vcpu)
4958 unsigned long exit_qualification, val;
4964 exit_qualification = vmx_get_exit_qual(vcpu);
4965 cr = exit_qualification & 15;
4966 reg = (exit_qualification >> 8) & 15;
4967 switch ((exit_qualification >> 4) & 3) {
4968 case 0: /* mov to cr */
4969 val = kvm_register_readl(vcpu, reg);
4970 trace_kvm_cr_write(cr, val);
4973 err = handle_set_cr0(vcpu, val);
4974 return kvm_complete_insn_gp(vcpu, err);
4976 WARN_ON_ONCE(enable_unrestricted_guest);
4977 err = kvm_set_cr3(vcpu, val);
4978 return kvm_complete_insn_gp(vcpu, err);
4980 err = handle_set_cr4(vcpu, val);
4981 return kvm_complete_insn_gp(vcpu, err);
4983 u8 cr8_prev = kvm_get_cr8(vcpu);
4985 err = kvm_set_cr8(vcpu, cr8);
4986 ret = kvm_complete_insn_gp(vcpu, err);
4987 if (lapic_in_kernel(vcpu))
4989 if (cr8_prev <= cr8)
4992 * TODO: we might be squashing a
4993 * KVM_GUESTDBG_SINGLESTEP-triggered
4994 * KVM_EXIT_DEBUG here.
4996 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5002 WARN_ONCE(1, "Guest should always own CR0.TS");
5003 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5004 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5005 return kvm_skip_emulated_instruction(vcpu);
5006 case 1: /*mov from cr*/
5009 WARN_ON_ONCE(enable_unrestricted_guest);
5010 val = kvm_read_cr3(vcpu);
5011 kvm_register_write(vcpu, reg, val);
5012 trace_kvm_cr_read(cr, val);
5013 return kvm_skip_emulated_instruction(vcpu);
5015 val = kvm_get_cr8(vcpu);
5016 kvm_register_write(vcpu, reg, val);
5017 trace_kvm_cr_read(cr, val);
5018 return kvm_skip_emulated_instruction(vcpu);
5022 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5023 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5024 kvm_lmsw(vcpu, val);
5026 return kvm_skip_emulated_instruction(vcpu);
5030 vcpu->run->exit_reason = 0;
5031 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5032 (int)(exit_qualification >> 4) & 3, cr);
5036 static int handle_dr(struct kvm_vcpu *vcpu)
5038 unsigned long exit_qualification;
5041 exit_qualification = vmx_get_exit_qual(vcpu);
5042 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5044 /* First, if DR does not exist, trigger UD */
5045 if (!kvm_require_dr(vcpu, dr))
5048 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
5049 if (!kvm_require_cpl(vcpu, 0))
5051 dr7 = vmcs_readl(GUEST_DR7);
5054 * As the vm-exit takes precedence over the debug trap, we
5055 * need to emulate the latter, either for the host or the
5056 * guest debugging itself.
5058 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5059 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_RTM | DR6_FIXED_1;
5060 vcpu->run->debug.arch.dr7 = dr7;
5061 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5062 vcpu->run->debug.arch.exception = DB_VECTOR;
5063 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5066 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5071 if (vcpu->guest_debug == 0) {
5072 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5075 * No more DR vmexits; force a reload of the debug registers
5076 * and reenter on this instruction. The next vmexit will
5077 * retrieve the full state of the debug registers.
5079 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5083 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5084 if (exit_qualification & TYPE_MOV_FROM_DR) {
5087 if (kvm_get_dr(vcpu, dr, &val))
5089 kvm_register_write(vcpu, reg, val);
5091 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
5094 return kvm_skip_emulated_instruction(vcpu);
5097 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5099 get_debugreg(vcpu->arch.db[0], 0);
5100 get_debugreg(vcpu->arch.db[1], 1);
5101 get_debugreg(vcpu->arch.db[2], 2);
5102 get_debugreg(vcpu->arch.db[3], 3);
5103 get_debugreg(vcpu->arch.dr6, 6);
5104 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5106 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5107 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5110 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5112 vmcs_writel(GUEST_DR7, val);
5115 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5117 kvm_apic_update_ppr(vcpu);
5121 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5123 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5125 kvm_make_request(KVM_REQ_EVENT, vcpu);
5127 ++vcpu->stat.irq_window_exits;
5131 static int handle_vmcall(struct kvm_vcpu *vcpu)
5133 return kvm_emulate_hypercall(vcpu);
5136 static int handle_invd(struct kvm_vcpu *vcpu)
5138 return kvm_emulate_instruction(vcpu, 0);
5141 static int handle_invlpg(struct kvm_vcpu *vcpu)
5143 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5145 kvm_mmu_invlpg(vcpu, exit_qualification);
5146 return kvm_skip_emulated_instruction(vcpu);
5149 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5153 err = kvm_rdpmc(vcpu);
5154 return kvm_complete_insn_gp(vcpu, err);
5157 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5159 return kvm_emulate_wbinvd(vcpu);
5162 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5164 u64 new_bv = kvm_read_edx_eax(vcpu);
5165 u32 index = kvm_rcx_read(vcpu);
5167 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5168 return kvm_skip_emulated_instruction(vcpu);
5172 static int handle_apic_access(struct kvm_vcpu *vcpu)
5174 if (likely(fasteoi)) {
5175 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5176 int access_type, offset;
5178 access_type = exit_qualification & APIC_ACCESS_TYPE;
5179 offset = exit_qualification & APIC_ACCESS_OFFSET;
5181 * Sane guest uses MOV to write EOI, with written value
5182 * not cared. So make a short-circuit here by avoiding
5183 * heavy instruction emulation.
5185 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5186 (offset == APIC_EOI)) {
5187 kvm_lapic_set_eoi(vcpu);
5188 return kvm_skip_emulated_instruction(vcpu);
5191 return kvm_emulate_instruction(vcpu, 0);
5194 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5196 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5197 int vector = exit_qualification & 0xff;
5199 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5200 kvm_apic_set_eoi_accelerated(vcpu, vector);
5204 static int handle_apic_write(struct kvm_vcpu *vcpu)
5206 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5207 u32 offset = exit_qualification & 0xfff;
5209 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5210 kvm_apic_write_nodecode(vcpu, offset);
5214 static int handle_task_switch(struct kvm_vcpu *vcpu)
5216 struct vcpu_vmx *vmx = to_vmx(vcpu);
5217 unsigned long exit_qualification;
5218 bool has_error_code = false;
5221 int reason, type, idt_v, idt_index;
5223 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5224 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5225 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5227 exit_qualification = vmx_get_exit_qual(vcpu);
5229 reason = (u32)exit_qualification >> 30;
5230 if (reason == TASK_SWITCH_GATE && idt_v) {
5232 case INTR_TYPE_NMI_INTR:
5233 vcpu->arch.nmi_injected = false;
5234 vmx_set_nmi_mask(vcpu, true);
5236 case INTR_TYPE_EXT_INTR:
5237 case INTR_TYPE_SOFT_INTR:
5238 kvm_clear_interrupt_queue(vcpu);
5240 case INTR_TYPE_HARD_EXCEPTION:
5241 if (vmx->idt_vectoring_info &
5242 VECTORING_INFO_DELIVER_CODE_MASK) {
5243 has_error_code = true;
5245 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5248 case INTR_TYPE_SOFT_EXCEPTION:
5249 kvm_clear_exception_queue(vcpu);
5255 tss_selector = exit_qualification;
5257 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5258 type != INTR_TYPE_EXT_INTR &&
5259 type != INTR_TYPE_NMI_INTR))
5260 WARN_ON(!skip_emulated_instruction(vcpu));
5263 * TODO: What about debug traps on tss switch?
5264 * Are we supposed to inject them and update dr6?
5266 return kvm_task_switch(vcpu, tss_selector,
5267 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5268 reason, has_error_code, error_code);
5271 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5273 unsigned long exit_qualification;
5277 exit_qualification = vmx_get_exit_qual(vcpu);
5280 * EPT violation happened while executing iret from NMI,
5281 * "blocked by NMI" bit has to be set before next VM entry.
5282 * There are errata that may cause this bit to not be set:
5285 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5287 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5288 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5290 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5291 trace_kvm_page_fault(gpa, exit_qualification);
5293 /* Is it a read fault? */
5294 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5295 ? PFERR_USER_MASK : 0;
5296 /* Is it a write fault? */
5297 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5298 ? PFERR_WRITE_MASK : 0;
5299 /* Is it a fetch fault? */
5300 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5301 ? PFERR_FETCH_MASK : 0;
5302 /* ept page table entry is present? */
5303 error_code |= (exit_qualification &
5304 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5305 EPT_VIOLATION_EXECUTABLE))
5306 ? PFERR_PRESENT_MASK : 0;
5308 error_code |= (exit_qualification & 0x100) != 0 ?
5309 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5311 vcpu->arch.exit_qualification = exit_qualification;
5312 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5315 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5320 * A nested guest cannot optimize MMIO vmexits, because we have an
5321 * nGPA here instead of the required GPA.
5323 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5324 if (!is_guest_mode(vcpu) &&
5325 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5326 trace_kvm_fast_mmio(gpa);
5327 return kvm_skip_emulated_instruction(vcpu);
5330 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5333 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5335 WARN_ON_ONCE(!enable_vnmi);
5336 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5337 ++vcpu->stat.nmi_window_exits;
5338 kvm_make_request(KVM_REQ_EVENT, vcpu);
5343 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5345 struct vcpu_vmx *vmx = to_vmx(vcpu);
5346 bool intr_window_requested;
5347 unsigned count = 130;
5349 intr_window_requested = exec_controls_get(vmx) &
5350 CPU_BASED_INTR_WINDOW_EXITING;
5352 while (vmx->emulation_required && count-- != 0) {
5353 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5354 return handle_interrupt_window(&vmx->vcpu);
5356 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5359 if (!kvm_emulate_instruction(vcpu, 0))
5362 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5363 vcpu->arch.exception.pending) {
5364 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5365 vcpu->run->internal.suberror =
5366 KVM_INTERNAL_ERROR_EMULATION;
5367 vcpu->run->internal.ndata = 0;
5371 if (vcpu->arch.halt_request) {
5372 vcpu->arch.halt_request = 0;
5373 return kvm_vcpu_halt(vcpu);
5377 * Note, return 1 and not 0, vcpu_run() is responsible for
5378 * morphing the pending signal into the proper return code.
5380 if (signal_pending(current))
5390 static void grow_ple_window(struct kvm_vcpu *vcpu)
5392 struct vcpu_vmx *vmx = to_vmx(vcpu);
5393 unsigned int old = vmx->ple_window;
5395 vmx->ple_window = __grow_ple_window(old, ple_window,
5399 if (vmx->ple_window != old) {
5400 vmx->ple_window_dirty = true;
5401 trace_kvm_ple_window_update(vcpu->vcpu_id,
5402 vmx->ple_window, old);
5406 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5408 struct vcpu_vmx *vmx = to_vmx(vcpu);
5409 unsigned int old = vmx->ple_window;
5411 vmx->ple_window = __shrink_ple_window(old, ple_window,
5415 if (vmx->ple_window != old) {
5416 vmx->ple_window_dirty = true;
5417 trace_kvm_ple_window_update(vcpu->vcpu_id,
5418 vmx->ple_window, old);
5423 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5425 static void wakeup_handler(void)
5427 struct kvm_vcpu *vcpu;
5428 int cpu = smp_processor_id();
5430 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5431 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5432 blocked_vcpu_list) {
5433 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5435 if (pi_test_on(pi_desc) == 1)
5436 kvm_vcpu_kick(vcpu);
5438 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5441 static void vmx_enable_tdp(void)
5443 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5444 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5445 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5446 0ull, VMX_EPT_EXECUTABLE_MASK,
5447 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5448 VMX_EPT_RWX_MASK, 0ull);
5450 ept_set_mmio_spte_mask();
5454 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5455 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5457 static int handle_pause(struct kvm_vcpu *vcpu)
5459 if (!kvm_pause_in_guest(vcpu->kvm))
5460 grow_ple_window(vcpu);
5463 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5464 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5465 * never set PAUSE_EXITING and just set PLE if supported,
5466 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5468 kvm_vcpu_on_spin(vcpu, true);
5469 return kvm_skip_emulated_instruction(vcpu);
5472 static int handle_nop(struct kvm_vcpu *vcpu)
5474 return kvm_skip_emulated_instruction(vcpu);
5477 static int handle_mwait(struct kvm_vcpu *vcpu)
5479 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5480 return handle_nop(vcpu);
5483 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5485 kvm_queue_exception(vcpu, UD_VECTOR);
5489 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5494 static int handle_monitor(struct kvm_vcpu *vcpu)
5496 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5497 return handle_nop(vcpu);
5500 static int handle_invpcid(struct kvm_vcpu *vcpu)
5502 u32 vmx_instruction_info;
5506 struct x86_exception e;
5508 unsigned long roots_to_free = 0;
5515 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5516 kvm_queue_exception(vcpu, UD_VECTOR);
5520 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5521 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5524 kvm_inject_gp(vcpu, 0);
5528 /* According to the Intel instruction reference, the memory operand
5529 * is read even if it isn't needed (e.g., for type==all)
5531 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5532 vmx_instruction_info, false,
5533 sizeof(operand), &gva))
5536 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
5537 if (r != X86EMUL_CONTINUE)
5538 return vmx_handle_memory_failure(vcpu, r, &e);
5540 if (operand.pcid >> 12 != 0) {
5541 kvm_inject_gp(vcpu, 0);
5545 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5548 case INVPCID_TYPE_INDIV_ADDR:
5549 if ((!pcid_enabled && (operand.pcid != 0)) ||
5550 is_noncanonical_address(operand.gla, vcpu)) {
5551 kvm_inject_gp(vcpu, 0);
5554 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5555 return kvm_skip_emulated_instruction(vcpu);
5557 case INVPCID_TYPE_SINGLE_CTXT:
5558 if (!pcid_enabled && (operand.pcid != 0)) {
5559 kvm_inject_gp(vcpu, 0);
5563 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5564 kvm_mmu_sync_roots(vcpu);
5565 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
5568 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5569 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].pgd)
5571 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5573 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5575 * If neither the current cr3 nor any of the prev_roots use the
5576 * given PCID, then nothing needs to be done here because a
5577 * resync will happen anyway before switching to any other CR3.
5580 return kvm_skip_emulated_instruction(vcpu);
5582 case INVPCID_TYPE_ALL_NON_GLOBAL:
5584 * Currently, KVM doesn't mark global entries in the shadow
5585 * page tables, so a non-global flush just degenerates to a
5586 * global flush. If needed, we could optimize this later by
5587 * keeping track of global entries in shadow page tables.
5591 case INVPCID_TYPE_ALL_INCL_GLOBAL:
5592 kvm_mmu_unload(vcpu);
5593 return kvm_skip_emulated_instruction(vcpu);
5596 BUG(); /* We have already checked above that type <= 3 */
5600 static int handle_pml_full(struct kvm_vcpu *vcpu)
5602 unsigned long exit_qualification;
5604 trace_kvm_pml_full(vcpu->vcpu_id);
5606 exit_qualification = vmx_get_exit_qual(vcpu);
5609 * PML buffer FULL happened while executing iret from NMI,
5610 * "blocked by NMI" bit has to be set before next VM entry.
5612 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5614 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5615 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5616 GUEST_INTR_STATE_NMI);
5619 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5620 * here.., and there's no userspace involvement needed for PML.
5625 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5627 struct vcpu_vmx *vmx = to_vmx(vcpu);
5629 if (!vmx->req_immediate_exit &&
5630 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5631 kvm_lapic_expired_hv_timer(vcpu);
5632 return EXIT_FASTPATH_REENTER_GUEST;
5635 return EXIT_FASTPATH_NONE;
5638 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5640 handle_fastpath_preemption_timer(vcpu);
5645 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5646 * are overwritten by nested_vmx_setup() when nested=1.
5648 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5650 kvm_queue_exception(vcpu, UD_VECTOR);
5654 static int handle_encls(struct kvm_vcpu *vcpu)
5657 * SGX virtualization is not yet supported. There is no software
5658 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5659 * to prevent the guest from executing ENCLS.
5661 kvm_queue_exception(vcpu, UD_VECTOR);
5666 * The exit handlers return 1 if the exit was handled fully and guest execution
5667 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5668 * to be done to userspace and return 0.
5670 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5671 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5672 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5673 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5674 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5675 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5676 [EXIT_REASON_CR_ACCESS] = handle_cr,
5677 [EXIT_REASON_DR_ACCESS] = handle_dr,
5678 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5679 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5680 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5681 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5682 [EXIT_REASON_HLT] = kvm_emulate_halt,
5683 [EXIT_REASON_INVD] = handle_invd,
5684 [EXIT_REASON_INVLPG] = handle_invlpg,
5685 [EXIT_REASON_RDPMC] = handle_rdpmc,
5686 [EXIT_REASON_VMCALL] = handle_vmcall,
5687 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5688 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5689 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5690 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5691 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5692 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5693 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5694 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5695 [EXIT_REASON_VMON] = handle_vmx_instruction,
5696 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5697 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5698 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5699 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5700 [EXIT_REASON_WBINVD] = handle_wbinvd,
5701 [EXIT_REASON_XSETBV] = handle_xsetbv,
5702 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5703 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5704 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5705 [EXIT_REASON_LDTR_TR] = handle_desc,
5706 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5707 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5708 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5709 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5710 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5711 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5712 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5713 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5714 [EXIT_REASON_RDRAND] = handle_invalid_op,
5715 [EXIT_REASON_RDSEED] = handle_invalid_op,
5716 [EXIT_REASON_PML_FULL] = handle_pml_full,
5717 [EXIT_REASON_INVPCID] = handle_invpcid,
5718 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5719 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5720 [EXIT_REASON_ENCLS] = handle_encls,
5723 static const int kvm_vmx_max_exit_handlers =
5724 ARRAY_SIZE(kvm_vmx_exit_handlers);
5726 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5728 *info1 = vmx_get_exit_qual(vcpu);
5729 *info2 = vmx_get_intr_info(vcpu);
5732 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5735 __free_page(vmx->pml_pg);
5740 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5742 struct vcpu_vmx *vmx = to_vmx(vcpu);
5746 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5748 /* Do nothing if PML buffer is empty */
5749 if (pml_idx == (PML_ENTITY_NUM - 1))
5752 /* PML index always points to next available PML buffer entity */
5753 if (pml_idx >= PML_ENTITY_NUM)
5758 pml_buf = page_address(vmx->pml_pg);
5759 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5762 gpa = pml_buf[pml_idx];
5763 WARN_ON(gpa & (PAGE_SIZE - 1));
5764 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5767 /* reset PML index */
5768 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5772 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5773 * Called before reporting dirty_bitmap to userspace.
5775 static void kvm_flush_pml_buffers(struct kvm *kvm)
5778 struct kvm_vcpu *vcpu;
5780 * We only need to kick vcpu out of guest mode here, as PML buffer
5781 * is flushed at beginning of all VMEXITs, and it's obvious that only
5782 * vcpus running in guest are possible to have unflushed GPAs in PML
5785 kvm_for_each_vcpu(i, vcpu, kvm)
5786 kvm_vcpu_kick(vcpu);
5789 static void vmx_dump_sel(char *name, uint32_t sel)
5791 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5792 name, vmcs_read16(sel),
5793 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5794 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5795 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5798 static void vmx_dump_dtsel(char *name, uint32_t limit)
5800 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5801 name, vmcs_read32(limit),
5802 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5805 void dump_vmcs(void)
5807 u32 vmentry_ctl, vmexit_ctl;
5808 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5812 if (!dump_invalid_vmcs) {
5813 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5817 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5818 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5819 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5820 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5821 cr4 = vmcs_readl(GUEST_CR4);
5822 efer = vmcs_read64(GUEST_IA32_EFER);
5823 secondary_exec_control = 0;
5824 if (cpu_has_secondary_exec_ctrls())
5825 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5827 pr_err("*** Guest State ***\n");
5828 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5829 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5830 vmcs_readl(CR0_GUEST_HOST_MASK));
5831 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5832 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5833 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5834 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5835 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5837 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5838 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5839 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5840 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5842 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5843 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5844 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5845 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5846 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5847 vmcs_readl(GUEST_SYSENTER_ESP),
5848 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5849 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5850 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5851 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5852 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5853 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5854 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5855 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5856 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5857 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5858 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5859 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5860 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5861 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5862 efer, vmcs_read64(GUEST_IA32_PAT));
5863 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5864 vmcs_read64(GUEST_IA32_DEBUGCTL),
5865 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5866 if (cpu_has_load_perf_global_ctrl() &&
5867 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5868 pr_err("PerfGlobCtl = 0x%016llx\n",
5869 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5870 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5871 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5872 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5873 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5874 vmcs_read32(GUEST_ACTIVITY_STATE));
5875 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5876 pr_err("InterruptStatus = %04x\n",
5877 vmcs_read16(GUEST_INTR_STATUS));
5879 pr_err("*** Host State ***\n");
5880 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5881 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5882 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5883 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5884 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5885 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5886 vmcs_read16(HOST_TR_SELECTOR));
5887 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5888 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5889 vmcs_readl(HOST_TR_BASE));
5890 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5891 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5892 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5893 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5894 vmcs_readl(HOST_CR4));
5895 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5896 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5897 vmcs_read32(HOST_IA32_SYSENTER_CS),
5898 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5899 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5900 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5901 vmcs_read64(HOST_IA32_EFER),
5902 vmcs_read64(HOST_IA32_PAT));
5903 if (cpu_has_load_perf_global_ctrl() &&
5904 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5905 pr_err("PerfGlobCtl = 0x%016llx\n",
5906 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5908 pr_err("*** Control State ***\n");
5909 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5910 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5911 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5912 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5913 vmcs_read32(EXCEPTION_BITMAP),
5914 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5915 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5916 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5917 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5918 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5919 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5920 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5921 vmcs_read32(VM_EXIT_INTR_INFO),
5922 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5923 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5924 pr_err(" reason=%08x qualification=%016lx\n",
5925 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5926 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5927 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5928 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5929 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5930 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5931 pr_err("TSC Multiplier = 0x%016llx\n",
5932 vmcs_read64(TSC_MULTIPLIER));
5933 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5934 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5935 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5936 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5938 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5939 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5940 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5941 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5943 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5944 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5945 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5946 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5947 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5948 pr_err("PLE Gap=%08x Window=%08x\n",
5949 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5950 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5951 pr_err("Virtual processor ID = 0x%04x\n",
5952 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5956 * The guest has exited. See if we can fix it or if we need userspace
5959 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
5961 struct vcpu_vmx *vmx = to_vmx(vcpu);
5962 u32 exit_reason = vmx->exit_reason;
5963 u32 vectoring_info = vmx->idt_vectoring_info;
5966 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5967 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5968 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5969 * mode as if vcpus is in root mode, the PML buffer must has been
5973 vmx_flush_pml_buffer(vcpu);
5976 * We should never reach this point with a pending nested VM-Enter, and
5977 * more specifically emulation of L2 due to invalid guest state (see
5978 * below) should never happen as that means we incorrectly allowed a
5979 * nested VM-Enter with an invalid vmcs12.
5981 WARN_ON_ONCE(vmx->nested.nested_run_pending);
5983 /* If guest state is invalid, start emulating */
5984 if (vmx->emulation_required)
5985 return handle_invalid_guest_state(vcpu);
5987 if (is_guest_mode(vcpu)) {
5989 * The host physical addresses of some pages of guest memory
5990 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
5991 * Page). The CPU may write to these pages via their host
5992 * physical address while L2 is running, bypassing any
5993 * address-translation-based dirty tracking (e.g. EPT write
5996 * Mark them dirty on every exit from L2 to prevent them from
5997 * getting out of sync with dirty tracking.
5999 nested_mark_vmcs12_pages_dirty(vcpu);
6001 if (nested_vmx_reflect_vmexit(vcpu))
6005 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
6007 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6008 vcpu->run->fail_entry.hardware_entry_failure_reason
6010 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6014 if (unlikely(vmx->fail)) {
6016 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6017 vcpu->run->fail_entry.hardware_entry_failure_reason
6018 = vmcs_read32(VM_INSTRUCTION_ERROR);
6019 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6025 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6026 * delivery event since it indicates guest is accessing MMIO.
6027 * The vm-exit can be triggered again after return to guest that
6028 * will cause infinite loop.
6030 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6031 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
6032 exit_reason != EXIT_REASON_EPT_VIOLATION &&
6033 exit_reason != EXIT_REASON_PML_FULL &&
6034 exit_reason != EXIT_REASON_TASK_SWITCH)) {
6035 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6036 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6037 vcpu->run->internal.ndata = 3;
6038 vcpu->run->internal.data[0] = vectoring_info;
6039 vcpu->run->internal.data[1] = exit_reason;
6040 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6041 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
6042 vcpu->run->internal.ndata++;
6043 vcpu->run->internal.data[3] =
6044 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6046 vcpu->run->internal.data[vcpu->run->internal.ndata++] =
6047 vcpu->arch.last_vmentry_cpu;
6051 if (unlikely(!enable_vnmi &&
6052 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6053 if (!vmx_interrupt_blocked(vcpu)) {
6054 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6055 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6056 vcpu->arch.nmi_pending) {
6058 * This CPU don't support us in finding the end of an
6059 * NMI-blocked window if the guest runs with IRQs
6060 * disabled. So we pull the trigger after 1 s of
6061 * futile waiting, but inform the user about this.
6063 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6064 "state on VCPU %d after 1 s timeout\n",
6065 __func__, vcpu->vcpu_id);
6066 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6070 if (exit_fastpath != EXIT_FASTPATH_NONE)
6073 if (exit_reason >= kvm_vmx_max_exit_handlers)
6074 goto unexpected_vmexit;
6075 #ifdef CONFIG_RETPOLINE
6076 if (exit_reason == EXIT_REASON_MSR_WRITE)
6077 return kvm_emulate_wrmsr(vcpu);
6078 else if (exit_reason == EXIT_REASON_PREEMPTION_TIMER)
6079 return handle_preemption_timer(vcpu);
6080 else if (exit_reason == EXIT_REASON_INTERRUPT_WINDOW)
6081 return handle_interrupt_window(vcpu);
6082 else if (exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6083 return handle_external_interrupt(vcpu);
6084 else if (exit_reason == EXIT_REASON_HLT)
6085 return kvm_emulate_halt(vcpu);
6086 else if (exit_reason == EXIT_REASON_EPT_MISCONFIG)
6087 return handle_ept_misconfig(vcpu);
6090 exit_reason = array_index_nospec(exit_reason,
6091 kvm_vmx_max_exit_handlers);
6092 if (!kvm_vmx_exit_handlers[exit_reason])
6093 goto unexpected_vmexit;
6095 return kvm_vmx_exit_handlers[exit_reason](vcpu);
6098 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n", exit_reason);
6100 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6101 vcpu->run->internal.suberror =
6102 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6103 vcpu->run->internal.ndata = 2;
6104 vcpu->run->internal.data[0] = exit_reason;
6105 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6110 * Software based L1D cache flush which is used when microcode providing
6111 * the cache control MSR is not loaded.
6113 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6114 * flush it is required to read in 64 KiB because the replacement algorithm
6115 * is not exactly LRU. This could be sized at runtime via topology
6116 * information but as all relevant affected CPUs have 32KiB L1D cache size
6117 * there is no point in doing so.
6119 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6121 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6124 * This code is only executed when the the flush mode is 'cond' or
6127 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6131 * Clear the per-vcpu flush bit, it gets set again
6132 * either from vcpu_run() or from one of the unsafe
6135 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6136 vcpu->arch.l1tf_flush_l1d = false;
6139 * Clear the per-cpu flush bit, it gets set again from
6140 * the interrupt handlers.
6142 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6143 kvm_clear_cpu_l1tf_flush_l1d();
6149 vcpu->stat.l1d_flush++;
6151 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6152 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6157 /* First ensure the pages are in the TLB */
6158 "xorl %%eax, %%eax\n"
6159 ".Lpopulate_tlb:\n\t"
6160 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6161 "addl $4096, %%eax\n\t"
6162 "cmpl %%eax, %[size]\n\t"
6163 "jne .Lpopulate_tlb\n\t"
6164 "xorl %%eax, %%eax\n\t"
6166 /* Now fill the cache */
6167 "xorl %%eax, %%eax\n"
6169 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6170 "addl $64, %%eax\n\t"
6171 "cmpl %%eax, %[size]\n\t"
6172 "jne .Lfill_cache\n\t"
6174 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6176 : "eax", "ebx", "ecx", "edx");
6179 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6181 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6184 if (is_guest_mode(vcpu) &&
6185 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6188 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6189 if (is_guest_mode(vcpu))
6190 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6192 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6195 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6197 struct vcpu_vmx *vmx = to_vmx(vcpu);
6198 u32 sec_exec_control;
6200 if (!lapic_in_kernel(vcpu))
6203 if (!flexpriority_enabled &&
6204 !cpu_has_vmx_virtualize_x2apic_mode())
6207 /* Postpone execution until vmcs01 is the current VMCS. */
6208 if (is_guest_mode(vcpu)) {
6209 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6213 sec_exec_control = secondary_exec_controls_get(vmx);
6214 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6215 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6217 switch (kvm_get_apic_mode(vcpu)) {
6218 case LAPIC_MODE_INVALID:
6219 WARN_ONCE(true, "Invalid local APIC state");
6220 case LAPIC_MODE_DISABLED:
6222 case LAPIC_MODE_XAPIC:
6223 if (flexpriority_enabled) {
6225 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6226 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6229 * Flush the TLB, reloading the APIC access page will
6230 * only do so if its physical address has changed, but
6231 * the guest may have inserted a non-APIC mapping into
6232 * the TLB while the APIC access page was disabled.
6234 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6237 case LAPIC_MODE_X2APIC:
6238 if (cpu_has_vmx_virtualize_x2apic_mode())
6240 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6243 secondary_exec_controls_set(vmx, sec_exec_control);
6245 vmx_update_msr_bitmap(vcpu);
6248 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6252 /* Defer reload until vmcs01 is the current VMCS. */
6253 if (is_guest_mode(vcpu)) {
6254 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6258 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6259 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6262 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6263 if (is_error_page(page))
6266 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6267 vmx_flush_tlb_current(vcpu);
6270 * Do not pin apic access page in memory, the MMU notifier
6271 * will call us again if it is migrated or swapped out.
6276 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6284 status = vmcs_read16(GUEST_INTR_STATUS);
6286 if (max_isr != old) {
6288 status |= max_isr << 8;
6289 vmcs_write16(GUEST_INTR_STATUS, status);
6293 static void vmx_set_rvi(int vector)
6301 status = vmcs_read16(GUEST_INTR_STATUS);
6302 old = (u8)status & 0xff;
6303 if ((u8)vector != old) {
6305 status |= (u8)vector;
6306 vmcs_write16(GUEST_INTR_STATUS, status);
6310 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6313 * When running L2, updating RVI is only relevant when
6314 * vmcs12 virtual-interrupt-delivery enabled.
6315 * However, it can be enabled only when L1 also
6316 * intercepts external-interrupts and in that case
6317 * we should not update vmcs02 RVI but instead intercept
6318 * interrupt. Therefore, do nothing when running L2.
6320 if (!is_guest_mode(vcpu))
6321 vmx_set_rvi(max_irr);
6324 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6326 struct vcpu_vmx *vmx = to_vmx(vcpu);
6328 bool max_irr_updated;
6330 WARN_ON(!vcpu->arch.apicv_active);
6331 if (pi_test_on(&vmx->pi_desc)) {
6332 pi_clear_on(&vmx->pi_desc);
6334 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6335 * But on x86 this is just a compiler barrier anyway.
6337 smp_mb__after_atomic();
6339 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6342 * If we are running L2 and L1 has a new pending interrupt
6343 * which can be injected, we should re-evaluate
6344 * what should be done with this new L1 interrupt.
6345 * If L1 intercepts external-interrupts, we should
6346 * exit from L2 to L1. Otherwise, interrupt should be
6347 * delivered directly to L2.
6349 if (is_guest_mode(vcpu) && max_irr_updated) {
6350 if (nested_exit_on_intr(vcpu))
6351 kvm_vcpu_exiting_guest_mode(vcpu);
6353 kvm_make_request(KVM_REQ_EVENT, vcpu);
6356 max_irr = kvm_lapic_find_highest_irr(vcpu);
6358 vmx_hwapic_irr_update(vcpu, max_irr);
6362 static bool vmx_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
6364 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6366 return pi_test_on(pi_desc) ||
6367 (pi_test_sn(pi_desc) && !pi_is_pir_empty(pi_desc));
6370 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6372 if (!kvm_vcpu_apicv_active(vcpu))
6375 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6376 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6377 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6378 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6381 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6383 struct vcpu_vmx *vmx = to_vmx(vcpu);
6385 pi_clear_on(&vmx->pi_desc);
6386 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6389 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6391 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6393 /* if exit due to PF check for async PF */
6394 if (is_page_fault(intr_info)) {
6395 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6396 /* Handle machine checks before interrupts are enabled */
6397 } else if (is_machine_check(intr_info)) {
6398 kvm_machine_check();
6399 /* We need to handle NMIs before interrupts are enabled */
6400 } else if (is_nmi(intr_info)) {
6401 kvm_before_interrupt(&vmx->vcpu);
6403 kvm_after_interrupt(&vmx->vcpu);
6407 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6409 unsigned int vector;
6410 unsigned long entry;
6411 #ifdef CONFIG_X86_64
6415 u32 intr_info = vmx_get_intr_info(vcpu);
6417 if (WARN_ONCE(!is_external_intr(intr_info),
6418 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6421 vector = intr_info & INTR_INFO_VECTOR_MASK;
6422 desc = (gate_desc *)host_idt_base + vector;
6423 entry = gate_offset(desc);
6425 kvm_before_interrupt(vcpu);
6428 #ifdef CONFIG_X86_64
6429 "mov %%rsp, %[sp]\n\t"
6430 "and $-16, %%rsp\n\t"
6438 #ifdef CONFIG_X86_64
6443 [thunk_target]"r"(entry),
6444 #ifdef CONFIG_X86_64
6445 [ss]"i"(__KERNEL_DS),
6447 [cs]"i"(__KERNEL_CS)
6450 kvm_after_interrupt(vcpu);
6452 STACK_FRAME_NON_STANDARD(handle_external_interrupt_irqoff);
6454 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6456 struct vcpu_vmx *vmx = to_vmx(vcpu);
6458 if (vmx->exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6459 handle_external_interrupt_irqoff(vcpu);
6460 else if (vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)
6461 handle_exception_nmi_irqoff(vmx);
6464 static bool vmx_has_emulated_msr(u32 index)
6467 case MSR_IA32_SMBASE:
6469 * We cannot do SMM unless we can run the guest in big
6472 return enable_unrestricted_guest || emulate_invalid_guest_state;
6473 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6475 case MSR_AMD64_VIRT_SPEC_CTRL:
6476 /* This is AMD only. */
6483 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6488 bool idtv_info_valid;
6490 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6493 if (vmx->loaded_vmcs->nmi_known_unmasked)
6496 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6497 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6498 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6500 * SDM 3: 27.7.1.2 (September 2008)
6501 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6502 * a guest IRET fault.
6503 * SDM 3: 23.2.2 (September 2008)
6504 * Bit 12 is undefined in any of the following cases:
6505 * If the VM exit sets the valid bit in the IDT-vectoring
6506 * information field.
6507 * If the VM exit is due to a double fault.
6509 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6510 vector != DF_VECTOR && !idtv_info_valid)
6511 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6512 GUEST_INTR_STATE_NMI);
6514 vmx->loaded_vmcs->nmi_known_unmasked =
6515 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6516 & GUEST_INTR_STATE_NMI);
6517 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6518 vmx->loaded_vmcs->vnmi_blocked_time +=
6519 ktime_to_ns(ktime_sub(ktime_get(),
6520 vmx->loaded_vmcs->entry_time));
6523 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6524 u32 idt_vectoring_info,
6525 int instr_len_field,
6526 int error_code_field)
6530 bool idtv_info_valid;
6532 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6534 vcpu->arch.nmi_injected = false;
6535 kvm_clear_exception_queue(vcpu);
6536 kvm_clear_interrupt_queue(vcpu);
6538 if (!idtv_info_valid)
6541 kvm_make_request(KVM_REQ_EVENT, vcpu);
6543 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6544 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6547 case INTR_TYPE_NMI_INTR:
6548 vcpu->arch.nmi_injected = true;
6550 * SDM 3: 27.7.1.2 (September 2008)
6551 * Clear bit "block by NMI" before VM entry if a NMI
6554 vmx_set_nmi_mask(vcpu, false);
6556 case INTR_TYPE_SOFT_EXCEPTION:
6557 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6559 case INTR_TYPE_HARD_EXCEPTION:
6560 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6561 u32 err = vmcs_read32(error_code_field);
6562 kvm_requeue_exception_e(vcpu, vector, err);
6564 kvm_requeue_exception(vcpu, vector);
6566 case INTR_TYPE_SOFT_INTR:
6567 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6569 case INTR_TYPE_EXT_INTR:
6570 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6577 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6579 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6580 VM_EXIT_INSTRUCTION_LEN,
6581 IDT_VECTORING_ERROR_CODE);
6584 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6586 __vmx_complete_interrupts(vcpu,
6587 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6588 VM_ENTRY_INSTRUCTION_LEN,
6589 VM_ENTRY_EXCEPTION_ERROR_CODE);
6591 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6594 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6597 struct perf_guest_switch_msr *msrs;
6599 msrs = perf_guest_get_msrs(&nr_msrs);
6604 for (i = 0; i < nr_msrs; i++)
6605 if (msrs[i].host == msrs[i].guest)
6606 clear_atomic_switch_msr(vmx, msrs[i].msr);
6608 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6609 msrs[i].host, false);
6612 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6614 struct vcpu_vmx *vmx = to_vmx(vcpu);
6618 if (vmx->req_immediate_exit) {
6619 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6620 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6621 } else if (vmx->hv_deadline_tsc != -1) {
6623 if (vmx->hv_deadline_tsc > tscl)
6624 /* set_hv_timer ensures the delta fits in 32-bits */
6625 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6626 cpu_preemption_timer_multi);
6630 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6631 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6632 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6633 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6634 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6638 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6640 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6641 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6642 vmcs_writel(HOST_RSP, host_rsp);
6646 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6648 switch (to_vmx(vcpu)->exit_reason) {
6649 case EXIT_REASON_MSR_WRITE:
6650 return handle_fastpath_set_msr_irqoff(vcpu);
6651 case EXIT_REASON_PREEMPTION_TIMER:
6652 return handle_fastpath_preemption_timer(vcpu);
6654 return EXIT_FASTPATH_NONE;
6658 bool __vmx_vcpu_run(struct vcpu_vmx *vmx, unsigned long *regs, bool launched);
6660 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6661 struct vcpu_vmx *vmx)
6664 * VMENTER enables interrupts (host state), but the kernel state is
6665 * interrupts disabled when this is invoked. Also tell RCU about
6666 * it. This is the same logic as for exit_to_user_mode().
6668 * This ensures that e.g. latency analysis on the host observes
6669 * guest mode as interrupt enabled.
6671 * guest_enter_irqoff() informs context tracking about the
6672 * transition to guest mode and if enabled adjusts RCU state
6675 instrumentation_begin();
6676 trace_hardirqs_on_prepare();
6677 lockdep_hardirqs_on_prepare(CALLER_ADDR0);
6678 instrumentation_end();
6680 guest_enter_irqoff();
6681 lockdep_hardirqs_on(CALLER_ADDR0);
6683 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6684 if (static_branch_unlikely(&vmx_l1d_should_flush))
6685 vmx_l1d_flush(vcpu);
6686 else if (static_branch_unlikely(&mds_user_clear))
6687 mds_clear_cpu_buffers();
6689 if (vcpu->arch.cr2 != native_read_cr2())
6690 native_write_cr2(vcpu->arch.cr2);
6692 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6693 vmx->loaded_vmcs->launched);
6695 vcpu->arch.cr2 = native_read_cr2();
6698 * VMEXIT disables interrupts (host state), but tracing and lockdep
6699 * have them in state 'on' as recorded before entering guest mode.
6700 * Same as enter_from_user_mode().
6702 * guest_exit_irqoff() restores host context and reinstates RCU if
6703 * enabled and required.
6705 * This needs to be done before the below as native_read_msr()
6706 * contains a tracepoint and x86_spec_ctrl_restore_host() calls
6707 * into world and some more.
6709 lockdep_hardirqs_off(CALLER_ADDR0);
6710 guest_exit_irqoff();
6712 instrumentation_begin();
6713 trace_hardirqs_off_finish();
6714 instrumentation_end();
6717 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6719 fastpath_t exit_fastpath;
6720 struct vcpu_vmx *vmx = to_vmx(vcpu);
6721 unsigned long cr3, cr4;
6724 /* Record the guest's net vcpu time for enforced NMI injections. */
6725 if (unlikely(!enable_vnmi &&
6726 vmx->loaded_vmcs->soft_vnmi_blocked))
6727 vmx->loaded_vmcs->entry_time = ktime_get();
6729 /* Don't enter VMX if guest state is invalid, let the exit handler
6730 start emulation until we arrive back to a valid state */
6731 if (vmx->emulation_required)
6732 return EXIT_FASTPATH_NONE;
6734 if (vmx->ple_window_dirty) {
6735 vmx->ple_window_dirty = false;
6736 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6740 * We did this in prepare_switch_to_guest, because it needs to
6741 * be within srcu_read_lock.
6743 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6745 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6746 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6747 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6748 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6750 cr3 = __get_current_cr3_fast();
6751 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6752 vmcs_writel(HOST_CR3, cr3);
6753 vmx->loaded_vmcs->host_state.cr3 = cr3;
6756 cr4 = cr4_read_shadow();
6757 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6758 vmcs_writel(HOST_CR4, cr4);
6759 vmx->loaded_vmcs->host_state.cr4 = cr4;
6762 /* When single-stepping over STI and MOV SS, we must clear the
6763 * corresponding interruptibility bits in the guest state. Otherwise
6764 * vmentry fails as it then expects bit 14 (BS) in pending debug
6765 * exceptions being set, but that's not correct for the guest debugging
6767 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6768 vmx_set_interrupt_shadow(vcpu, 0);
6770 kvm_load_guest_xsave_state(vcpu);
6772 pt_guest_enter(vmx);
6774 atomic_switch_perf_msrs(vmx);
6776 if (enable_preemption_timer)
6777 vmx_update_hv_timer(vcpu);
6779 if (lapic_in_kernel(vcpu) &&
6780 vcpu->arch.apic->lapic_timer.timer_advance_ns)
6781 kvm_wait_lapic_expire(vcpu);
6784 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6785 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6786 * is no need to worry about the conditional branch over the wrmsr
6787 * being speculatively taken.
6789 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6791 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6792 vmx_vcpu_enter_exit(vcpu, vmx);
6795 * We do not use IBRS in the kernel. If this vCPU has used the
6796 * SPEC_CTRL MSR it may have left it on; save the value and
6797 * turn it off. This is much more efficient than blindly adding
6798 * it to the atomic save/restore list. Especially as the former
6799 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6801 * For non-nested case:
6802 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6806 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6809 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6810 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6812 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6814 /* All fields are clean at this point */
6815 if (static_branch_unlikely(&enable_evmcs))
6816 current_evmcs->hv_clean_fields |=
6817 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6819 if (static_branch_unlikely(&enable_evmcs))
6820 current_evmcs->hv_vp_id = vcpu->arch.hyperv.vp_index;
6822 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6823 if (vmx->host_debugctlmsr)
6824 update_debugctlmsr(vmx->host_debugctlmsr);
6826 #ifndef CONFIG_X86_64
6828 * The sysexit path does not restore ds/es, so we must set them to
6829 * a reasonable value ourselves.
6831 * We can't defer this to vmx_prepare_switch_to_host() since that
6832 * function may be executed in interrupt context, which saves and
6833 * restore segments around it, nullifying its effect.
6835 loadsegment(ds, __USER_DS);
6836 loadsegment(es, __USER_DS);
6839 vmx_register_cache_reset(vcpu);
6843 kvm_load_host_xsave_state(vcpu);
6845 vmx->nested.nested_run_pending = 0;
6846 vmx->idt_vectoring_info = 0;
6848 if (unlikely(vmx->fail)) {
6849 vmx->exit_reason = 0xdead;
6850 return EXIT_FASTPATH_NONE;
6853 vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
6854 if (unlikely((u16)vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY))
6855 kvm_machine_check();
6857 trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
6859 if (unlikely(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6860 return EXIT_FASTPATH_NONE;
6862 vmx->loaded_vmcs->launched = 1;
6863 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6865 vmx_recover_nmi_blocking(vmx);
6866 vmx_complete_interrupts(vmx);
6868 if (is_guest_mode(vcpu))
6869 return EXIT_FASTPATH_NONE;
6871 exit_fastpath = vmx_exit_handlers_fastpath(vcpu);
6872 if (exit_fastpath == EXIT_FASTPATH_REENTER_GUEST) {
6873 if (!kvm_vcpu_exit_request(vcpu)) {
6875 * FIXME: this goto should be a loop in vcpu_enter_guest,
6876 * but it would incur the cost of a retpoline for now.
6877 * Revisit once static calls are available.
6879 if (vcpu->arch.apicv_active)
6880 vmx_sync_pir_to_irr(vcpu);
6883 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
6886 return exit_fastpath;
6889 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6891 struct vcpu_vmx *vmx = to_vmx(vcpu);
6894 vmx_destroy_pml_buffer(vmx);
6895 free_vpid(vmx->vpid);
6896 nested_vmx_free_vcpu(vcpu);
6897 free_loaded_vmcs(vmx->loaded_vmcs);
6900 static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
6902 struct vcpu_vmx *vmx;
6903 unsigned long *msr_bitmap;
6906 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6911 vmx->vpid = allocate_vpid();
6914 * If PML is turned on, failure on enabling PML just results in failure
6915 * of creating the vcpu, therefore we can simplify PML logic (by
6916 * avoiding dealing with cases, such as enabling PML partially on vcpus
6917 * for the guest), etc.
6920 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6925 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) != NR_SHARED_MSRS);
6927 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6928 u32 index = vmx_msr_index[i];
6929 u32 data_low, data_high;
6932 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6934 if (wrmsr_safe(index, data_low, data_high) < 0)
6937 vmx->guest_msrs[j].index = i;
6938 vmx->guest_msrs[j].data = 0;
6940 case MSR_IA32_TSX_CTRL:
6942 * No need to pass TSX_CTRL_CPUID_CLEAR through, so
6943 * let's avoid changing CPUID bits under the host
6946 vmx->guest_msrs[j].mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6949 vmx->guest_msrs[j].mask = -1ull;
6955 err = alloc_loaded_vmcs(&vmx->vmcs01);
6959 msr_bitmap = vmx->vmcs01.msr_bitmap;
6960 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6961 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6962 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6963 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6964 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6965 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6966 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6967 if (kvm_cstate_in_guest(vcpu->kvm)) {
6968 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C1_RES, MSR_TYPE_R);
6969 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6970 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6971 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6973 vmx->msr_bitmap_mode = 0;
6975 vmx->loaded_vmcs = &vmx->vmcs01;
6977 vmx_vcpu_load(vcpu, cpu);
6982 if (cpu_need_virtualize_apic_accesses(vcpu)) {
6983 err = alloc_apic_access_page(vcpu->kvm);
6988 if (enable_ept && !enable_unrestricted_guest) {
6989 err = init_rmode_identity_map(vcpu->kvm);
6995 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
6996 vmx_capability.ept);
6998 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
7000 vmx->nested.posted_intr_nv = -1;
7001 vmx->nested.current_vmptr = -1ull;
7003 vcpu->arch.microcode_version = 0x100000000ULL;
7004 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
7007 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
7008 * or POSTED_INTR_WAKEUP_VECTOR.
7010 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
7011 vmx->pi_desc.sn = 1;
7013 vmx->ept_pointer = INVALID_PAGE;
7018 free_loaded_vmcs(vmx->loaded_vmcs);
7020 vmx_destroy_pml_buffer(vmx);
7022 free_vpid(vmx->vpid);
7026 #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"
7027 #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"
7029 static int vmx_vm_init(struct kvm *kvm)
7031 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
7034 kvm->arch.pause_in_guest = true;
7036 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7037 switch (l1tf_mitigation) {
7038 case L1TF_MITIGATION_OFF:
7039 case L1TF_MITIGATION_FLUSH_NOWARN:
7040 /* 'I explicitly don't care' is set */
7042 case L1TF_MITIGATION_FLUSH:
7043 case L1TF_MITIGATION_FLUSH_NOSMT:
7044 case L1TF_MITIGATION_FULL:
7046 * Warn upon starting the first VM in a potentially
7047 * insecure environment.
7049 if (sched_smt_active())
7050 pr_warn_once(L1TF_MSG_SMT);
7051 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7052 pr_warn_once(L1TF_MSG_L1D);
7054 case L1TF_MITIGATION_FULL_FORCE:
7055 /* Flush is enforced */
7059 kvm_apicv_init(kvm, enable_apicv);
7063 static int __init vmx_check_processor_compat(void)
7065 struct vmcs_config vmcs_conf;
7066 struct vmx_capability vmx_cap;
7068 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7069 !this_cpu_has(X86_FEATURE_VMX)) {
7070 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7074 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7077 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
7078 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7079 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7080 smp_processor_id());
7086 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7091 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7092 * memory aliases with conflicting memory types and sometimes MCEs.
7093 * We have to be careful as to what are honored and when.
7095 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7096 * UC. The effective memory type is UC or WC depending on guest PAT.
7097 * This was historically the source of MCEs and we want to be
7100 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7101 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7102 * EPT memory type is set to WB. The effective memory type is forced
7105 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7106 * EPT memory type is used to emulate guest CD/MTRR.
7110 cache = MTRR_TYPE_UNCACHABLE;
7114 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7115 ipat = VMX_EPT_IPAT_BIT;
7116 cache = MTRR_TYPE_WRBACK;
7120 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7121 ipat = VMX_EPT_IPAT_BIT;
7122 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7123 cache = MTRR_TYPE_WRBACK;
7125 cache = MTRR_TYPE_UNCACHABLE;
7129 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
7132 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7135 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
7138 * These bits in the secondary execution controls field
7139 * are dynamic, the others are mostly based on the hypervisor
7140 * architecture and the guest's CPUID. Do not touch the
7144 SECONDARY_EXEC_SHADOW_VMCS |
7145 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7146 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7147 SECONDARY_EXEC_DESC;
7149 u32 new_ctl = vmx->secondary_exec_control;
7150 u32 cur_ctl = secondary_exec_controls_get(vmx);
7152 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7156 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7157 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7159 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7161 struct vcpu_vmx *vmx = to_vmx(vcpu);
7162 struct kvm_cpuid_entry2 *entry;
7164 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7165 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7167 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7168 if (entry && (entry->_reg & (_cpuid_mask))) \
7169 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7172 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7173 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7174 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7175 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7176 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7177 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7178 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7179 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7180 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7181 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7182 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7183 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7184 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7185 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7186 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7188 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7189 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7190 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7191 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7192 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7193 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7194 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7196 #undef cr4_fixed1_update
7199 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7201 struct vcpu_vmx *vmx = to_vmx(vcpu);
7203 if (kvm_mpx_supported()) {
7204 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7207 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7208 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7210 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7211 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7216 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7218 struct vcpu_vmx *vmx = to_vmx(vcpu);
7219 struct kvm_cpuid_entry2 *best = NULL;
7222 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7223 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7226 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7227 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7228 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7229 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7232 /* Get the number of configurable Address Ranges for filtering */
7233 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7234 PT_CAP_num_address_ranges);
7236 /* Initialize and clear the no dependency bits */
7237 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7238 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7241 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7242 * will inject an #GP
7244 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7245 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7248 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7249 * PSBFreq can be set
7251 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7252 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7253 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7256 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7257 * MTCFreq can be set
7259 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7260 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7261 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7263 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7264 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7265 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7268 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7269 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7270 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7272 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7273 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7274 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7276 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
7277 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7278 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7280 /* unmask address range configure area */
7281 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7282 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7285 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7287 struct vcpu_vmx *vmx = to_vmx(vcpu);
7289 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7290 vcpu->arch.xsaves_enabled = false;
7292 if (cpu_has_secondary_exec_ctrls()) {
7293 vmx_compute_secondary_exec_control(vmx);
7294 vmcs_set_secondary_exec_control(vmx);
7297 if (nested_vmx_allowed(vcpu))
7298 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7299 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7300 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7302 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7303 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7304 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7306 if (nested_vmx_allowed(vcpu)) {
7307 nested_vmx_cr_fixed1_bits_update(vcpu);
7308 nested_vmx_entry_exit_ctls_update(vcpu);
7311 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7312 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7313 update_intel_pt_cfg(vcpu);
7315 if (boot_cpu_has(X86_FEATURE_RTM)) {
7316 struct shared_msr_entry *msr;
7317 msr = find_msr_entry(vmx, MSR_IA32_TSX_CTRL);
7319 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7320 vmx_set_guest_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7325 static __init void vmx_set_cpu_caps(void)
7331 kvm_cpu_cap_set(X86_FEATURE_VMX);
7334 if (kvm_mpx_supported())
7335 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7336 if (cpu_has_vmx_invpcid())
7337 kvm_cpu_cap_check_and_set(X86_FEATURE_INVPCID);
7338 if (vmx_pt_mode_is_host_guest())
7339 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7341 if (vmx_umip_emulated())
7342 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7346 if (!vmx_xsaves_supported())
7347 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7349 /* CPUID 0x80000001 */
7350 if (!cpu_has_vmx_rdtscp())
7351 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7353 if (vmx_waitpkg_supported())
7354 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7357 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7359 to_vmx(vcpu)->req_immediate_exit = true;
7362 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7363 struct x86_instruction_info *info)
7365 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7366 unsigned short port;
7370 if (info->intercept == x86_intercept_in ||
7371 info->intercept == x86_intercept_ins) {
7372 port = info->src_val;
7373 size = info->dst_bytes;
7375 port = info->dst_val;
7376 size = info->src_bytes;
7380 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7381 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7384 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7386 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7387 intercept = nested_cpu_has(vmcs12,
7388 CPU_BASED_UNCOND_IO_EXITING);
7390 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7392 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7393 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7396 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7397 struct x86_instruction_info *info,
7398 enum x86_intercept_stage stage,
7399 struct x86_exception *exception)
7401 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7403 switch (info->intercept) {
7405 * RDPID causes #UD if disabled through secondary execution controls.
7406 * Because it is marked as EmulateOnUD, we need to intercept it here.
7408 case x86_intercept_rdtscp:
7409 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
7410 exception->vector = UD_VECTOR;
7411 exception->error_code_valid = false;
7412 return X86EMUL_PROPAGATE_FAULT;
7416 case x86_intercept_in:
7417 case x86_intercept_ins:
7418 case x86_intercept_out:
7419 case x86_intercept_outs:
7420 return vmx_check_intercept_io(vcpu, info);
7422 case x86_intercept_lgdt:
7423 case x86_intercept_lidt:
7424 case x86_intercept_lldt:
7425 case x86_intercept_ltr:
7426 case x86_intercept_sgdt:
7427 case x86_intercept_sidt:
7428 case x86_intercept_sldt:
7429 case x86_intercept_str:
7430 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7431 return X86EMUL_CONTINUE;
7433 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7436 /* TODO: check more intercepts... */
7441 return X86EMUL_UNHANDLEABLE;
7444 #ifdef CONFIG_X86_64
7445 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7446 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7447 u64 divisor, u64 *result)
7449 u64 low = a << shift, high = a >> (64 - shift);
7451 /* To avoid the overflow on divq */
7452 if (high >= divisor)
7455 /* Low hold the result, high hold rem which is discarded */
7456 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7457 "rm" (divisor), "0" (low), "1" (high));
7463 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7466 struct vcpu_vmx *vmx;
7467 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7468 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7472 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7473 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7474 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7475 ktimer->timer_advance_ns);
7477 if (delta_tsc > lapic_timer_advance_cycles)
7478 delta_tsc -= lapic_timer_advance_cycles;
7482 /* Convert to host delta tsc if tsc scaling is enabled */
7483 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7484 delta_tsc && u64_shl_div_u64(delta_tsc,
7485 kvm_tsc_scaling_ratio_frac_bits,
7486 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7490 * If the delta tsc can't fit in the 32 bit after the multi shift,
7491 * we can't use the preemption timer.
7492 * It's possible that it fits on later vmentries, but checking
7493 * on every vmentry is costly so we just use an hrtimer.
7495 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7498 vmx->hv_deadline_tsc = tscl + delta_tsc;
7499 *expired = !delta_tsc;
7503 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7505 to_vmx(vcpu)->hv_deadline_tsc = -1;
7509 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7511 if (!kvm_pause_in_guest(vcpu->kvm))
7512 shrink_ple_window(vcpu);
7515 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7516 struct kvm_memory_slot *slot)
7518 if (!kvm_dirty_log_manual_protect_and_init_set(kvm))
7519 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7520 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7523 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7524 struct kvm_memory_slot *slot)
7526 kvm_mmu_slot_set_dirty(kvm, slot);
7529 static void vmx_flush_log_dirty(struct kvm *kvm)
7531 kvm_flush_pml_buffers(kvm);
7534 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7535 struct kvm_memory_slot *memslot,
7536 gfn_t offset, unsigned long mask)
7538 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7541 static void __pi_post_block(struct kvm_vcpu *vcpu)
7543 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7544 struct pi_desc old, new;
7548 old.control = new.control = pi_desc->control;
7549 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
7550 "Wakeup handler not enabled while the VCPU is blocked\n");
7552 dest = cpu_physical_id(vcpu->cpu);
7554 if (x2apic_enabled())
7557 new.ndst = (dest << 8) & 0xFF00;
7559 /* set 'NV' to 'notification vector' */
7560 new.nv = POSTED_INTR_VECTOR;
7561 } while (cmpxchg64(&pi_desc->control, old.control,
7562 new.control) != old.control);
7564 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
7565 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7566 list_del(&vcpu->blocked_vcpu_list);
7567 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7568 vcpu->pre_pcpu = -1;
7573 * This routine does the following things for vCPU which is going
7574 * to be blocked if VT-d PI is enabled.
7575 * - Store the vCPU to the wakeup list, so when interrupts happen
7576 * we can find the right vCPU to wake up.
7577 * - Change the Posted-interrupt descriptor as below:
7578 * 'NDST' <-- vcpu->pre_pcpu
7579 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
7580 * - If 'ON' is set during this process, which means at least one
7581 * interrupt is posted for this vCPU, we cannot block it, in
7582 * this case, return 1, otherwise, return 0.
7585 static int pi_pre_block(struct kvm_vcpu *vcpu)
7588 struct pi_desc old, new;
7589 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7591 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
7592 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7593 !kvm_vcpu_apicv_active(vcpu))
7596 WARN_ON(irqs_disabled());
7597 local_irq_disable();
7598 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
7599 vcpu->pre_pcpu = vcpu->cpu;
7600 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7601 list_add_tail(&vcpu->blocked_vcpu_list,
7602 &per_cpu(blocked_vcpu_on_cpu,
7604 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7608 old.control = new.control = pi_desc->control;
7610 WARN((pi_desc->sn == 1),
7611 "Warning: SN field of posted-interrupts "
7612 "is set before blocking\n");
7615 * Since vCPU can be preempted during this process,
7616 * vcpu->cpu could be different with pre_pcpu, we
7617 * need to set pre_pcpu as the destination of wakeup
7618 * notification event, then we can find the right vCPU
7619 * to wakeup in wakeup handler if interrupts happen
7620 * when the vCPU is in blocked state.
7622 dest = cpu_physical_id(vcpu->pre_pcpu);
7624 if (x2apic_enabled())
7627 new.ndst = (dest << 8) & 0xFF00;
7629 /* set 'NV' to 'wakeup vector' */
7630 new.nv = POSTED_INTR_WAKEUP_VECTOR;
7631 } while (cmpxchg64(&pi_desc->control, old.control,
7632 new.control) != old.control);
7634 /* We should not block the vCPU if an interrupt is posted for it. */
7635 if (pi_test_on(pi_desc) == 1)
7636 __pi_post_block(vcpu);
7639 return (vcpu->pre_pcpu == -1);
7642 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7644 if (pi_pre_block(vcpu))
7647 if (kvm_lapic_hv_timer_in_use(vcpu))
7648 kvm_lapic_switch_to_sw_timer(vcpu);
7653 static void pi_post_block(struct kvm_vcpu *vcpu)
7655 if (vcpu->pre_pcpu == -1)
7658 WARN_ON(irqs_disabled());
7659 local_irq_disable();
7660 __pi_post_block(vcpu);
7664 static void vmx_post_block(struct kvm_vcpu *vcpu)
7666 if (kvm_x86_ops.set_hv_timer)
7667 kvm_lapic_switch_to_hv_timer(vcpu);
7669 pi_post_block(vcpu);
7673 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
7676 * @host_irq: host irq of the interrupt
7677 * @guest_irq: gsi of the interrupt
7678 * @set: set or unset PI
7679 * returns 0 on success, < 0 on failure
7681 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7682 uint32_t guest_irq, bool set)
7684 struct kvm_kernel_irq_routing_entry *e;
7685 struct kvm_irq_routing_table *irq_rt;
7686 struct kvm_lapic_irq irq;
7687 struct kvm_vcpu *vcpu;
7688 struct vcpu_data vcpu_info;
7691 if (!kvm_arch_has_assigned_device(kvm) ||
7692 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7693 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7696 idx = srcu_read_lock(&kvm->irq_srcu);
7697 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7698 if (guest_irq >= irq_rt->nr_rt_entries ||
7699 hlist_empty(&irq_rt->map[guest_irq])) {
7700 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7701 guest_irq, irq_rt->nr_rt_entries);
7705 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7706 if (e->type != KVM_IRQ_ROUTING_MSI)
7709 * VT-d PI cannot support posting multicast/broadcast
7710 * interrupts to a vCPU, we still use interrupt remapping
7711 * for these kind of interrupts.
7713 * For lowest-priority interrupts, we only support
7714 * those with single CPU as the destination, e.g. user
7715 * configures the interrupts via /proc/irq or uses
7716 * irqbalance to make the interrupts single-CPU.
7718 * We will support full lowest-priority interrupt later.
7720 * In addition, we can only inject generic interrupts using
7721 * the PI mechanism, refuse to route others through it.
7724 kvm_set_msi_irq(kvm, e, &irq);
7725 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
7726 !kvm_irq_is_postable(&irq)) {
7728 * Make sure the IRTE is in remapped mode if
7729 * we don't handle it in posted mode.
7731 ret = irq_set_vcpu_affinity(host_irq, NULL);
7734 "failed to back to remapped mode, irq: %u\n",
7742 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7743 vcpu_info.vector = irq.vector;
7745 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7746 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7749 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7751 ret = irq_set_vcpu_affinity(host_irq, NULL);
7754 printk(KERN_INFO "%s: failed to update PI IRTE\n",
7762 srcu_read_unlock(&kvm->irq_srcu, idx);
7766 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7768 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7769 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7770 FEAT_CTL_LMCE_ENABLED;
7772 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7773 ~FEAT_CTL_LMCE_ENABLED;
7776 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7778 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7779 if (to_vmx(vcpu)->nested.nested_run_pending)
7781 return !is_smm(vcpu);
7784 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7786 struct vcpu_vmx *vmx = to_vmx(vcpu);
7788 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7789 if (vmx->nested.smm.guest_mode)
7790 nested_vmx_vmexit(vcpu, -1, 0, 0);
7792 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7793 vmx->nested.vmxon = false;
7794 vmx_clear_hlt(vcpu);
7798 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7800 struct vcpu_vmx *vmx = to_vmx(vcpu);
7803 if (vmx->nested.smm.vmxon) {
7804 vmx->nested.vmxon = true;
7805 vmx->nested.smm.vmxon = false;
7808 if (vmx->nested.smm.guest_mode) {
7809 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7813 vmx->nested.smm.guest_mode = false;
7818 static void enable_smi_window(struct kvm_vcpu *vcpu)
7820 /* RSM will cause a vmexit anyway. */
7823 static bool vmx_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7828 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7830 return to_vmx(vcpu)->nested.vmxon;
7833 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7835 if (is_guest_mode(vcpu)) {
7836 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7838 if (hrtimer_try_to_cancel(timer) == 1)
7839 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7843 static void hardware_unsetup(void)
7846 nested_vmx_hardware_unsetup();
7851 static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7853 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7854 BIT(APICV_INHIBIT_REASON_HYPERV);
7856 return supported & BIT(bit);
7859 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7860 .hardware_unsetup = hardware_unsetup,
7862 .hardware_enable = hardware_enable,
7863 .hardware_disable = hardware_disable,
7864 .cpu_has_accelerated_tpr = report_flexpriority,
7865 .has_emulated_msr = vmx_has_emulated_msr,
7867 .vm_size = sizeof(struct kvm_vmx),
7868 .vm_init = vmx_vm_init,
7870 .vcpu_create = vmx_create_vcpu,
7871 .vcpu_free = vmx_free_vcpu,
7872 .vcpu_reset = vmx_vcpu_reset,
7874 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7875 .vcpu_load = vmx_vcpu_load,
7876 .vcpu_put = vmx_vcpu_put,
7878 .update_exception_bitmap = update_exception_bitmap,
7879 .get_msr_feature = vmx_get_msr_feature,
7880 .get_msr = vmx_get_msr,
7881 .set_msr = vmx_set_msr,
7882 .get_segment_base = vmx_get_segment_base,
7883 .get_segment = vmx_get_segment,
7884 .set_segment = vmx_set_segment,
7885 .get_cpl = vmx_get_cpl,
7886 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7887 .set_cr0 = vmx_set_cr0,
7888 .set_cr4 = vmx_set_cr4,
7889 .set_efer = vmx_set_efer,
7890 .get_idt = vmx_get_idt,
7891 .set_idt = vmx_set_idt,
7892 .get_gdt = vmx_get_gdt,
7893 .set_gdt = vmx_set_gdt,
7894 .set_dr7 = vmx_set_dr7,
7895 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7896 .cache_reg = vmx_cache_reg,
7897 .get_rflags = vmx_get_rflags,
7898 .set_rflags = vmx_set_rflags,
7900 .tlb_flush_all = vmx_flush_tlb_all,
7901 .tlb_flush_current = vmx_flush_tlb_current,
7902 .tlb_flush_gva = vmx_flush_tlb_gva,
7903 .tlb_flush_guest = vmx_flush_tlb_guest,
7905 .run = vmx_vcpu_run,
7906 .handle_exit = vmx_handle_exit,
7907 .skip_emulated_instruction = vmx_skip_emulated_instruction,
7908 .update_emulated_instruction = vmx_update_emulated_instruction,
7909 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7910 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7911 .patch_hypercall = vmx_patch_hypercall,
7912 .set_irq = vmx_inject_irq,
7913 .set_nmi = vmx_inject_nmi,
7914 .queue_exception = vmx_queue_exception,
7915 .cancel_injection = vmx_cancel_injection,
7916 .interrupt_allowed = vmx_interrupt_allowed,
7917 .nmi_allowed = vmx_nmi_allowed,
7918 .get_nmi_mask = vmx_get_nmi_mask,
7919 .set_nmi_mask = vmx_set_nmi_mask,
7920 .enable_nmi_window = enable_nmi_window,
7921 .enable_irq_window = enable_irq_window,
7922 .update_cr8_intercept = update_cr8_intercept,
7923 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7924 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7925 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7926 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7927 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7928 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7929 .hwapic_irr_update = vmx_hwapic_irr_update,
7930 .hwapic_isr_update = vmx_hwapic_isr_update,
7931 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7932 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7933 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7934 .dy_apicv_has_pending_interrupt = vmx_dy_apicv_has_pending_interrupt,
7936 .set_tss_addr = vmx_set_tss_addr,
7937 .set_identity_map_addr = vmx_set_identity_map_addr,
7938 .get_tdp_level = vmx_get_tdp_level,
7939 .get_mt_mask = vmx_get_mt_mask,
7941 .get_exit_info = vmx_get_exit_info,
7943 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
7945 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7947 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7949 .load_mmu_pgd = vmx_load_mmu_pgd,
7951 .check_intercept = vmx_check_intercept,
7952 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7954 .request_immediate_exit = vmx_request_immediate_exit,
7956 .sched_in = vmx_sched_in,
7958 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7959 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7960 .flush_log_dirty = vmx_flush_log_dirty,
7961 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7963 .pre_block = vmx_pre_block,
7964 .post_block = vmx_post_block,
7966 .pmu_ops = &intel_pmu_ops,
7967 .nested_ops = &vmx_nested_ops,
7969 .update_pi_irte = vmx_update_pi_irte,
7971 #ifdef CONFIG_X86_64
7972 .set_hv_timer = vmx_set_hv_timer,
7973 .cancel_hv_timer = vmx_cancel_hv_timer,
7976 .setup_mce = vmx_setup_mce,
7978 .smi_allowed = vmx_smi_allowed,
7979 .pre_enter_smm = vmx_pre_enter_smm,
7980 .pre_leave_smm = vmx_pre_leave_smm,
7981 .enable_smi_window = enable_smi_window,
7983 .need_emulation_on_page_fault = vmx_need_emulation_on_page_fault,
7984 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7985 .migrate_timers = vmx_migrate_timers,
7988 static __init int hardware_setup(void)
7990 unsigned long host_bndcfgs;
7992 int r, i, ept_lpage_level;
7995 host_idt_base = dt.address;
7997 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7998 kvm_define_shared_msr(i, vmx_msr_index[i]);
8000 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
8003 if (boot_cpu_has(X86_FEATURE_NX))
8004 kvm_enable_efer_bits(EFER_NX);
8006 if (boot_cpu_has(X86_FEATURE_MPX)) {
8007 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
8008 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
8011 if (!cpu_has_vmx_mpx())
8012 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
8013 XFEATURE_MASK_BNDCSR);
8015 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
8016 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
8019 if (!cpu_has_vmx_ept() ||
8020 !cpu_has_vmx_ept_4levels() ||
8021 !cpu_has_vmx_ept_mt_wb() ||
8022 !cpu_has_vmx_invept_global())
8025 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
8026 enable_ept_ad_bits = 0;
8028 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
8029 enable_unrestricted_guest = 0;
8031 if (!cpu_has_vmx_flexpriority())
8032 flexpriority_enabled = 0;
8034 if (!cpu_has_virtual_nmis())
8038 * set_apic_access_page_addr() is used to reload apic access
8039 * page upon invalidation. No need to do anything if not
8040 * using the APIC_ACCESS_ADDR VMCS field.
8042 if (!flexpriority_enabled)
8043 vmx_x86_ops.set_apic_access_page_addr = NULL;
8045 if (!cpu_has_vmx_tpr_shadow())
8046 vmx_x86_ops.update_cr8_intercept = NULL;
8048 #if IS_ENABLED(CONFIG_HYPERV)
8049 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
8051 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
8052 vmx_x86_ops.tlb_remote_flush_with_range =
8053 hv_remote_flush_tlb_with_range;
8057 if (!cpu_has_vmx_ple()) {
8060 ple_window_grow = 0;
8062 ple_window_shrink = 0;
8065 if (!cpu_has_vmx_apicv()) {
8067 vmx_x86_ops.sync_pir_to_irr = NULL;
8070 if (cpu_has_vmx_tsc_scaling()) {
8071 kvm_has_tsc_control = true;
8072 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
8073 kvm_tsc_scaling_ratio_frac_bits = 48;
8076 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8082 ept_lpage_level = 0;
8083 else if (cpu_has_vmx_ept_1g_page())
8084 ept_lpage_level = PG_LEVEL_1G;
8085 else if (cpu_has_vmx_ept_2m_page())
8086 ept_lpage_level = PG_LEVEL_2M;
8088 ept_lpage_level = PG_LEVEL_4K;
8089 kvm_configure_mmu(enable_ept, ept_lpage_level);
8092 * Only enable PML when hardware supports PML feature, and both EPT
8093 * and EPT A/D bit features are enabled -- PML depends on them to work.
8095 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8099 vmx_x86_ops.slot_enable_log_dirty = NULL;
8100 vmx_x86_ops.slot_disable_log_dirty = NULL;
8101 vmx_x86_ops.flush_log_dirty = NULL;
8102 vmx_x86_ops.enable_log_dirty_pt_masked = NULL;
8105 if (!cpu_has_vmx_preemption_timer())
8106 enable_preemption_timer = false;
8108 if (enable_preemption_timer) {
8109 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8112 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
8113 cpu_preemption_timer_multi =
8114 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8117 use_timer_freq = (u64)tsc_khz * 1000;
8118 use_timer_freq >>= cpu_preemption_timer_multi;
8121 * KVM "disables" the preemption timer by setting it to its max
8122 * value. Don't use the timer if it might cause spurious exits
8123 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8125 if (use_timer_freq > 0xffffffffu / 10)
8126 enable_preemption_timer = false;
8129 if (!enable_preemption_timer) {
8130 vmx_x86_ops.set_hv_timer = NULL;
8131 vmx_x86_ops.cancel_hv_timer = NULL;
8132 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8135 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
8137 kvm_mce_cap_supported |= MCG_LMCE_P;
8139 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8141 if (!enable_ept || !cpu_has_vmx_intel_pt())
8142 pt_mode = PT_MODE_SYSTEM;
8145 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
8146 vmx_capability.ept);
8148 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8155 r = alloc_kvm_area();
8157 nested_vmx_hardware_unsetup();
8161 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8162 .cpu_has_kvm_support = cpu_has_kvm_support,
8163 .disabled_by_bios = vmx_disabled_by_bios,
8164 .check_processor_compatibility = vmx_check_processor_compat,
8165 .hardware_setup = hardware_setup,
8167 .runtime_ops = &vmx_x86_ops,
8170 static void vmx_cleanup_l1d_flush(void)
8172 if (vmx_l1d_flush_pages) {
8173 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8174 vmx_l1d_flush_pages = NULL;
8176 /* Restore state so sysfs ignores VMX */
8177 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8180 static void vmx_exit(void)
8182 #ifdef CONFIG_KEXEC_CORE
8183 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8189 #if IS_ENABLED(CONFIG_HYPERV)
8190 if (static_branch_unlikely(&enable_evmcs)) {
8192 struct hv_vp_assist_page *vp_ap;
8194 * Reset everything to support using non-enlightened VMCS
8195 * access later (e.g. when we reload the module with
8196 * enlightened_vmcs=0)
8198 for_each_online_cpu(cpu) {
8199 vp_ap = hv_get_vp_assist_page(cpu);
8204 vp_ap->nested_control.features.directhypercall = 0;
8205 vp_ap->current_nested_vmcs = 0;
8206 vp_ap->enlighten_vmentry = 0;
8209 static_branch_disable(&enable_evmcs);
8212 vmx_cleanup_l1d_flush();
8214 module_exit(vmx_exit);
8216 static int __init vmx_init(void)
8220 #if IS_ENABLED(CONFIG_HYPERV)
8222 * Enlightened VMCS usage should be recommended and the host needs
8223 * to support eVMCS v1 or above. We can also disable eVMCS support
8224 * with module parameter.
8226 if (enlightened_vmcs &&
8227 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8228 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8229 KVM_EVMCS_VERSION) {
8232 /* Check that we have assist pages on all online CPUs */
8233 for_each_online_cpu(cpu) {
8234 if (!hv_get_vp_assist_page(cpu)) {
8235 enlightened_vmcs = false;
8240 if (enlightened_vmcs) {
8241 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8242 static_branch_enable(&enable_evmcs);
8245 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8246 vmx_x86_ops.enable_direct_tlbflush
8247 = hv_enable_direct_tlbflush;
8250 enlightened_vmcs = false;
8254 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8255 __alignof__(struct vcpu_vmx), THIS_MODULE);
8260 * Must be called after kvm_init() so enable_ept is properly set
8261 * up. Hand the parameter mitigation value in which was stored in
8262 * the pre module init parser. If no parameter was given, it will
8263 * contain 'auto' which will be turned into the default 'cond'
8266 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8272 for_each_possible_cpu(cpu) {
8273 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8274 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
8275 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
8278 #ifdef CONFIG_KEXEC_CORE
8279 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8280 crash_vmclear_local_loaded_vmcss);
8282 vmx_check_vmcs12_offsets();
8286 module_init(vmx_init);