1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <linux/frame.h>
17 #include <linux/highmem.h>
18 #include <linux/hrtimer.h>
19 #include <linux/kernel.h>
20 #include <linux/kvm_host.h>
21 #include <linux/module.h>
22 #include <linux/moduleparam.h>
23 #include <linux/mod_devicetable.h>
25 #include <linux/sched.h>
26 #include <linux/sched/smt.h>
27 #include <linux/slab.h>
28 #include <linux/tboot.h>
29 #include <linux/trace_events.h>
30 #include <linux/entry-kvm.h>
35 #include <asm/cpu_device_id.h>
36 #include <asm/debugreg.h>
38 #include <asm/fpu/internal.h>
40 #include <asm/irq_remapping.h>
41 #include <asm/kexec.h>
42 #include <asm/perf_event.h>
44 #include <asm/mmu_context.h>
45 #include <asm/mshyperv.h>
46 #include <asm/mwait.h>
47 #include <asm/spec-ctrl.h>
48 #include <asm/virtext.h>
51 #include "capabilities.h"
55 #include "kvm_cache_regs.h"
67 MODULE_AUTHOR("Qumranet");
68 MODULE_LICENSE("GPL");
71 static const struct x86_cpu_id vmx_cpu_id[] = {
72 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
75 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
78 bool __read_mostly enable_vpid = 1;
79 module_param_named(vpid, enable_vpid, bool, 0444);
81 static bool __read_mostly enable_vnmi = 1;
82 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
84 bool __read_mostly flexpriority_enabled = 1;
85 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
87 bool __read_mostly enable_ept = 1;
88 module_param_named(ept, enable_ept, bool, S_IRUGO);
90 bool __read_mostly enable_unrestricted_guest = 1;
91 module_param_named(unrestricted_guest,
92 enable_unrestricted_guest, bool, S_IRUGO);
94 bool __read_mostly enable_ept_ad_bits = 1;
95 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
97 static bool __read_mostly emulate_invalid_guest_state = true;
98 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
100 static bool __read_mostly fasteoi = 1;
101 module_param(fasteoi, bool, S_IRUGO);
103 bool __read_mostly enable_apicv = 1;
104 module_param(enable_apicv, bool, S_IRUGO);
107 * If nested=1, nested virtualization is supported, i.e., guests may use
108 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
109 * use VMX instructions.
111 static bool __read_mostly nested = 1;
112 module_param(nested, bool, S_IRUGO);
114 bool __read_mostly enable_pml = 1;
115 module_param_named(pml, enable_pml, bool, S_IRUGO);
117 static bool __read_mostly dump_invalid_vmcs = 0;
118 module_param(dump_invalid_vmcs, bool, 0644);
120 #define MSR_BITMAP_MODE_X2APIC 1
121 #define MSR_BITMAP_MODE_X2APIC_APICV 2
123 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
125 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
126 static int __read_mostly cpu_preemption_timer_multi;
127 static bool __read_mostly enable_preemption_timer = 1;
129 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
132 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
133 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
134 #define KVM_VM_CR0_ALWAYS_ON \
135 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
136 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
138 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
139 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
140 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
142 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
144 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
145 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
146 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
147 RTIT_STATUS_BYTECNT))
150 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
151 * ple_gap: upper bound on the amount of time between two successive
152 * executions of PAUSE in a loop. Also indicate if ple enabled.
153 * According to test, this time is usually smaller than 128 cycles.
154 * ple_window: upper bound on the amount of time a guest is allowed to execute
155 * in a PAUSE loop. Tests indicate that most spinlocks are held for
156 * less than 2^12 cycles
157 * Time is measured based on a counter that runs at the same rate as the TSC,
158 * refer SDM volume 3b section 21.6.13 & 22.1.3.
160 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
161 module_param(ple_gap, uint, 0444);
163 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
164 module_param(ple_window, uint, 0444);
166 /* Default doubles per-vcpu window every exit. */
167 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
168 module_param(ple_window_grow, uint, 0444);
170 /* Default resets per-vcpu window every exit to ple_window. */
171 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
172 module_param(ple_window_shrink, uint, 0444);
174 /* Default is to compute the maximum so we can never overflow. */
175 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
176 module_param(ple_window_max, uint, 0444);
178 /* Default is SYSTEM mode, 1 for host-guest mode */
179 int __read_mostly pt_mode = PT_MODE_SYSTEM;
180 module_param(pt_mode, int, S_IRUGO);
182 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
183 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
184 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
186 /* Storage for pre module init parameter parsing */
187 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
189 static const struct {
192 } vmentry_l1d_param[] = {
193 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
194 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
195 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
196 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
197 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
198 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
201 #define L1D_CACHE_ORDER 4
202 static void *vmx_l1d_flush_pages;
204 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
209 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
210 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
215 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
219 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
222 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
223 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
224 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
229 /* If set to auto use the default l1tf mitigation method */
230 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
231 switch (l1tf_mitigation) {
232 case L1TF_MITIGATION_OFF:
233 l1tf = VMENTER_L1D_FLUSH_NEVER;
235 case L1TF_MITIGATION_FLUSH_NOWARN:
236 case L1TF_MITIGATION_FLUSH:
237 case L1TF_MITIGATION_FLUSH_NOSMT:
238 l1tf = VMENTER_L1D_FLUSH_COND;
240 case L1TF_MITIGATION_FULL:
241 case L1TF_MITIGATION_FULL_FORCE:
242 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
245 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
246 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
249 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
250 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
252 * This allocation for vmx_l1d_flush_pages is not tied to a VM
253 * lifetime and so should not be charged to a memcg.
255 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
258 vmx_l1d_flush_pages = page_address(page);
261 * Initialize each page with a different pattern in
262 * order to protect against KSM in the nested
263 * virtualization case.
265 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
266 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
271 l1tf_vmx_mitigation = l1tf;
273 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
274 static_branch_enable(&vmx_l1d_should_flush);
276 static_branch_disable(&vmx_l1d_should_flush);
278 if (l1tf == VMENTER_L1D_FLUSH_COND)
279 static_branch_enable(&vmx_l1d_flush_cond);
281 static_branch_disable(&vmx_l1d_flush_cond);
285 static int vmentry_l1d_flush_parse(const char *s)
290 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
291 if (vmentry_l1d_param[i].for_parse &&
292 sysfs_streq(s, vmentry_l1d_param[i].option))
299 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
303 l1tf = vmentry_l1d_flush_parse(s);
307 if (!boot_cpu_has(X86_BUG_L1TF))
311 * Has vmx_init() run already? If not then this is the pre init
312 * parameter parsing. In that case just store the value and let
313 * vmx_init() do the proper setup after enable_ept has been
316 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
317 vmentry_l1d_flush_param = l1tf;
321 mutex_lock(&vmx_l1d_flush_mutex);
322 ret = vmx_setup_l1d_flush(l1tf);
323 mutex_unlock(&vmx_l1d_flush_mutex);
327 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
329 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
330 return sprintf(s, "???\n");
332 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
335 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
336 .set = vmentry_l1d_flush_set,
337 .get = vmentry_l1d_flush_get,
339 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
341 static bool guest_state_valid(struct kvm_vcpu *vcpu);
342 static u32 vmx_segment_access_rights(struct kvm_segment *var);
343 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
346 void vmx_vmexit(void);
348 #define vmx_insn_failed(fmt...) \
351 pr_warn_ratelimited(fmt); \
354 asmlinkage void vmread_error(unsigned long field, bool fault)
357 kvm_spurious_fault();
359 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
362 noinline void vmwrite_error(unsigned long field, unsigned long value)
364 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
365 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
368 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
370 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
373 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
375 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
378 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
380 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
384 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
386 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
390 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
391 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
393 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
394 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
396 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
399 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
400 * can find which vCPU should be waken up.
402 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
403 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
405 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
406 static DEFINE_SPINLOCK(vmx_vpid_lock);
408 struct vmcs_config vmcs_config;
409 struct vmx_capability vmx_capability;
411 #define VMX_SEGMENT_FIELD(seg) \
412 [VCPU_SREG_##seg] = { \
413 .selector = GUEST_##seg##_SELECTOR, \
414 .base = GUEST_##seg##_BASE, \
415 .limit = GUEST_##seg##_LIMIT, \
416 .ar_bytes = GUEST_##seg##_AR_BYTES, \
419 static const struct kvm_vmx_segment_field {
424 } kvm_vmx_segment_fields[] = {
425 VMX_SEGMENT_FIELD(CS),
426 VMX_SEGMENT_FIELD(DS),
427 VMX_SEGMENT_FIELD(ES),
428 VMX_SEGMENT_FIELD(FS),
429 VMX_SEGMENT_FIELD(GS),
430 VMX_SEGMENT_FIELD(SS),
431 VMX_SEGMENT_FIELD(TR),
432 VMX_SEGMENT_FIELD(LDTR),
435 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
437 vmx->segment_cache.bitmask = 0;
440 static unsigned long host_idt_base;
443 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
444 * will emulate SYSCALL in legacy mode if the vendor string in guest
445 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
446 * support this emulation, IA32_STAR must always be included in
447 * vmx_msr_index[], even in i386 builds.
449 const u32 vmx_msr_index[] = {
451 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
453 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
457 #if IS_ENABLED(CONFIG_HYPERV)
458 static bool __read_mostly enlightened_vmcs = true;
459 module_param(enlightened_vmcs, bool, 0444);
461 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
462 static void check_ept_pointer_match(struct kvm *kvm)
464 struct kvm_vcpu *vcpu;
465 u64 tmp_eptp = INVALID_PAGE;
468 kvm_for_each_vcpu(i, vcpu, kvm) {
469 if (!VALID_PAGE(tmp_eptp)) {
470 tmp_eptp = to_vmx(vcpu)->ept_pointer;
471 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
472 to_kvm_vmx(kvm)->ept_pointers_match
473 = EPT_POINTERS_MISMATCH;
478 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
481 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
484 struct kvm_tlb_range *range = data;
486 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
490 static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
491 struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
493 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
496 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
497 * of the base of EPT PML4 table, strip off EPT configuration
501 return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
502 kvm_fill_hv_flush_list_func, (void *)range);
504 return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
507 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
508 struct kvm_tlb_range *range)
510 struct kvm_vcpu *vcpu;
513 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
515 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
516 check_ept_pointer_match(kvm);
518 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
519 kvm_for_each_vcpu(i, vcpu, kvm) {
520 /* If ept_pointer is invalid pointer, bypass flush request. */
521 if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
522 ret |= __hv_remote_flush_tlb_with_range(
526 ret = __hv_remote_flush_tlb_with_range(kvm,
527 kvm_get_vcpu(kvm, 0), range);
530 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
533 static int hv_remote_flush_tlb(struct kvm *kvm)
535 return hv_remote_flush_tlb_with_range(kvm, NULL);
538 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
540 struct hv_enlightened_vmcs *evmcs;
541 struct hv_partition_assist_pg **p_hv_pa_pg =
542 &vcpu->kvm->arch.hyperv.hv_pa_pg;
544 * Synthetic VM-Exit is not enabled in current code and so All
545 * evmcs in singe VM shares same assist page.
548 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL);
553 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
555 evmcs->partition_assist_page =
557 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
558 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
563 #endif /* IS_ENABLED(CONFIG_HYPERV) */
566 * Comment's format: document - errata name - stepping - processor name.
568 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
570 static u32 vmx_preemption_cpu_tfms[] = {
571 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
573 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
574 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
575 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
577 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
579 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
580 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
582 * 320767.pdf - AAP86 - B1 -
583 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
586 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
588 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
590 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
592 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
593 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
594 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
596 /* Xeon E3-1220 V2 */
600 static inline bool cpu_has_broken_vmx_preemption_timer(void)
602 u32 eax = cpuid_eax(0x00000001), i;
604 /* Clear the reserved bits */
605 eax &= ~(0x3U << 14 | 0xfU << 28);
606 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
607 if (eax == vmx_preemption_cpu_tfms[i])
613 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
615 return flexpriority_enabled && lapic_in_kernel(vcpu);
618 static inline bool report_flexpriority(void)
620 return flexpriority_enabled;
623 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
627 for (i = 0; i < vmx->nmsrs; ++i)
628 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
633 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
637 i = __find_msr_index(vmx, msr);
639 return &vmx->guest_msrs[i];
643 static int vmx_set_guest_msr(struct vcpu_vmx *vmx, struct shared_msr_entry *msr, u64 data)
647 u64 old_msr_data = msr->data;
649 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
651 ret = kvm_set_shared_msr(msr->index, msr->data,
655 msr->data = old_msr_data;
660 #ifdef CONFIG_KEXEC_CORE
661 static void crash_vmclear_local_loaded_vmcss(void)
663 int cpu = raw_smp_processor_id();
664 struct loaded_vmcs *v;
666 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
667 loaded_vmcss_on_cpu_link)
670 #endif /* CONFIG_KEXEC_CORE */
672 static void __loaded_vmcs_clear(void *arg)
674 struct loaded_vmcs *loaded_vmcs = arg;
675 int cpu = raw_smp_processor_id();
677 if (loaded_vmcs->cpu != cpu)
678 return; /* vcpu migration can race with cpu offline */
679 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
680 per_cpu(current_vmcs, cpu) = NULL;
682 vmcs_clear(loaded_vmcs->vmcs);
683 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
684 vmcs_clear(loaded_vmcs->shadow_vmcs);
686 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
689 * Ensure all writes to loaded_vmcs, including deleting it from its
690 * current percpu list, complete before setting loaded_vmcs->vcpu to
691 * -1, otherwise a different cpu can see vcpu == -1 first and add
692 * loaded_vmcs to its percpu list before it's deleted from this cpu's
693 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
697 loaded_vmcs->cpu = -1;
698 loaded_vmcs->launched = 0;
701 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
703 int cpu = loaded_vmcs->cpu;
706 smp_call_function_single(cpu,
707 __loaded_vmcs_clear, loaded_vmcs, 1);
710 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
714 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
716 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
717 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
718 vmx->segment_cache.bitmask = 0;
720 ret = vmx->segment_cache.bitmask & mask;
721 vmx->segment_cache.bitmask |= mask;
725 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
727 u16 *p = &vmx->segment_cache.seg[seg].selector;
729 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
730 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
734 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
736 ulong *p = &vmx->segment_cache.seg[seg].base;
738 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
739 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
743 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
745 u32 *p = &vmx->segment_cache.seg[seg].limit;
747 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
748 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
752 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
754 u32 *p = &vmx->segment_cache.seg[seg].ar;
756 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
757 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
761 void update_exception_bitmap(struct kvm_vcpu *vcpu)
765 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
766 (1u << DB_VECTOR) | (1u << AC_VECTOR);
768 * Guest access to VMware backdoor ports could legitimately
769 * trigger #GP because of TSS I/O permission bitmap.
770 * We intercept those #GP and allow access to them anyway
773 if (enable_vmware_backdoor)
774 eb |= (1u << GP_VECTOR);
775 if ((vcpu->guest_debug &
776 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
777 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
778 eb |= 1u << BP_VECTOR;
779 if (to_vmx(vcpu)->rmode.vm86_active)
781 if (!vmx_need_pf_intercept(vcpu))
782 eb &= ~(1u << PF_VECTOR);
784 /* When we are running a nested L2 guest and L1 specified for it a
785 * certain exception bitmap, we must trap the same exceptions and pass
786 * them to L1. When running L2, we will only handle the exceptions
787 * specified above if L1 did not want them.
789 if (is_guest_mode(vcpu))
790 eb |= get_vmcs12(vcpu)->exception_bitmap;
792 vmcs_write32(EXCEPTION_BITMAP, eb);
796 * Check if MSR is intercepted for currently loaded MSR bitmap.
798 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
800 unsigned long *msr_bitmap;
801 int f = sizeof(unsigned long);
803 if (!cpu_has_vmx_msr_bitmap())
806 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
809 return !!test_bit(msr, msr_bitmap + 0x800 / f);
810 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
812 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
818 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
819 unsigned long entry, unsigned long exit)
821 vm_entry_controls_clearbit(vmx, entry);
822 vm_exit_controls_clearbit(vmx, exit);
825 int vmx_find_msr_index(struct vmx_msrs *m, u32 msr)
829 for (i = 0; i < m->nr; ++i) {
830 if (m->val[i].index == msr)
836 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
839 struct msr_autoload *m = &vmx->msr_autoload;
843 if (cpu_has_load_ia32_efer()) {
844 clear_atomic_switch_msr_special(vmx,
845 VM_ENTRY_LOAD_IA32_EFER,
846 VM_EXIT_LOAD_IA32_EFER);
850 case MSR_CORE_PERF_GLOBAL_CTRL:
851 if (cpu_has_load_perf_global_ctrl()) {
852 clear_atomic_switch_msr_special(vmx,
853 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
854 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
859 i = vmx_find_msr_index(&m->guest, msr);
863 m->guest.val[i] = m->guest.val[m->guest.nr];
864 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
867 i = vmx_find_msr_index(&m->host, msr);
872 m->host.val[i] = m->host.val[m->host.nr];
873 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
876 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
877 unsigned long entry, unsigned long exit,
878 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
879 u64 guest_val, u64 host_val)
881 vmcs_write64(guest_val_vmcs, guest_val);
882 if (host_val_vmcs != HOST_IA32_EFER)
883 vmcs_write64(host_val_vmcs, host_val);
884 vm_entry_controls_setbit(vmx, entry);
885 vm_exit_controls_setbit(vmx, exit);
888 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
889 u64 guest_val, u64 host_val, bool entry_only)
892 struct msr_autoload *m = &vmx->msr_autoload;
896 if (cpu_has_load_ia32_efer()) {
897 add_atomic_switch_msr_special(vmx,
898 VM_ENTRY_LOAD_IA32_EFER,
899 VM_EXIT_LOAD_IA32_EFER,
902 guest_val, host_val);
906 case MSR_CORE_PERF_GLOBAL_CTRL:
907 if (cpu_has_load_perf_global_ctrl()) {
908 add_atomic_switch_msr_special(vmx,
909 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
910 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
911 GUEST_IA32_PERF_GLOBAL_CTRL,
912 HOST_IA32_PERF_GLOBAL_CTRL,
913 guest_val, host_val);
917 case MSR_IA32_PEBS_ENABLE:
918 /* PEBS needs a quiescent period after being disabled (to write
919 * a record). Disabling PEBS through VMX MSR swapping doesn't
920 * provide that period, so a CPU could write host's record into
923 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
926 i = vmx_find_msr_index(&m->guest, msr);
928 j = vmx_find_msr_index(&m->host, msr);
930 if ((i < 0 && m->guest.nr == NR_LOADSTORE_MSRS) ||
931 (j < 0 && m->host.nr == NR_LOADSTORE_MSRS)) {
932 printk_once(KERN_WARNING "Not enough msr switch entries. "
933 "Can't add msr %x\n", msr);
938 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
940 m->guest.val[i].index = msr;
941 m->guest.val[i].value = guest_val;
948 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
950 m->host.val[j].index = msr;
951 m->host.val[j].value = host_val;
954 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
956 u64 guest_efer = vmx->vcpu.arch.efer;
959 /* Shadow paging assumes NX to be available. */
961 guest_efer |= EFER_NX;
964 * LMA and LME handled by hardware; SCE meaningless outside long mode.
966 ignore_bits |= EFER_SCE;
968 ignore_bits |= EFER_LMA | EFER_LME;
969 /* SCE is meaningful only in long mode on Intel */
970 if (guest_efer & EFER_LMA)
971 ignore_bits &= ~(u64)EFER_SCE;
975 * On EPT, we can't emulate NX, so we must switch EFER atomically.
976 * On CPUs that support "load IA32_EFER", always switch EFER
977 * atomically, since it's faster than switching it manually.
979 if (cpu_has_load_ia32_efer() ||
980 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
981 if (!(guest_efer & EFER_LMA))
982 guest_efer &= ~EFER_LME;
983 if (guest_efer != host_efer)
984 add_atomic_switch_msr(vmx, MSR_EFER,
985 guest_efer, host_efer, false);
987 clear_atomic_switch_msr(vmx, MSR_EFER);
990 clear_atomic_switch_msr(vmx, MSR_EFER);
992 guest_efer &= ~ignore_bits;
993 guest_efer |= host_efer & ignore_bits;
995 vmx->guest_msrs[efer_offset].data = guest_efer;
996 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
1002 #ifdef CONFIG_X86_32
1004 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1005 * VMCS rather than the segment table. KVM uses this helper to figure
1006 * out the current bases to poke them into the VMCS before entry.
1008 static unsigned long segment_base(u16 selector)
1010 struct desc_struct *table;
1013 if (!(selector & ~SEGMENT_RPL_MASK))
1016 table = get_current_gdt_ro();
1018 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1019 u16 ldt_selector = kvm_read_ldt();
1021 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1024 table = (struct desc_struct *)segment_base(ldt_selector);
1026 v = get_desc_base(&table[selector >> 3]);
1031 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1033 return vmx_pt_mode_is_host_guest() &&
1034 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1037 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1039 /* The base must be 128-byte aligned and a legal physical address. */
1040 return !(base & (~((1UL << cpuid_maxphyaddr(vcpu)) - 1) | 0x7f));
1043 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1047 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1048 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1049 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1050 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1051 for (i = 0; i < addr_range; i++) {
1052 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1053 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1057 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1061 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1062 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1063 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1064 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1065 for (i = 0; i < addr_range; i++) {
1066 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1067 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1071 static void pt_guest_enter(struct vcpu_vmx *vmx)
1073 if (vmx_pt_mode_is_system())
1077 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1078 * Save host state before VM entry.
1080 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1081 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1082 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1083 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1084 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1088 static void pt_guest_exit(struct vcpu_vmx *vmx)
1090 if (vmx_pt_mode_is_system())
1093 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1094 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1095 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1098 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1099 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1102 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1103 unsigned long fs_base, unsigned long gs_base)
1105 if (unlikely(fs_sel != host->fs_sel)) {
1107 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1109 vmcs_write16(HOST_FS_SELECTOR, 0);
1110 host->fs_sel = fs_sel;
1112 if (unlikely(gs_sel != host->gs_sel)) {
1114 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1116 vmcs_write16(HOST_GS_SELECTOR, 0);
1117 host->gs_sel = gs_sel;
1119 if (unlikely(fs_base != host->fs_base)) {
1120 vmcs_writel(HOST_FS_BASE, fs_base);
1121 host->fs_base = fs_base;
1123 if (unlikely(gs_base != host->gs_base)) {
1124 vmcs_writel(HOST_GS_BASE, gs_base);
1125 host->gs_base = gs_base;
1129 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1131 struct vcpu_vmx *vmx = to_vmx(vcpu);
1132 struct vmcs_host_state *host_state;
1133 #ifdef CONFIG_X86_64
1134 int cpu = raw_smp_processor_id();
1136 unsigned long fs_base, gs_base;
1140 vmx->req_immediate_exit = false;
1143 * Note that guest MSRs to be saved/restored can also be changed
1144 * when guest state is loaded. This happens when guest transitions
1145 * to/from long-mode by setting MSR_EFER.LMA.
1147 if (!vmx->guest_msrs_ready) {
1148 vmx->guest_msrs_ready = true;
1149 for (i = 0; i < vmx->save_nmsrs; ++i)
1150 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1151 vmx->guest_msrs[i].data,
1152 vmx->guest_msrs[i].mask);
1156 if (vmx->nested.need_vmcs12_to_shadow_sync)
1157 nested_sync_vmcs12_to_shadow(vcpu);
1159 if (vmx->guest_state_loaded)
1162 host_state = &vmx->loaded_vmcs->host_state;
1165 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1166 * allow segment selectors with cpl > 0 or ti == 1.
1168 host_state->ldt_sel = kvm_read_ldt();
1170 #ifdef CONFIG_X86_64
1171 savesegment(ds, host_state->ds_sel);
1172 savesegment(es, host_state->es_sel);
1174 gs_base = cpu_kernelmode_gs_base(cpu);
1175 if (likely(is_64bit_mm(current->mm))) {
1176 current_save_fsgs();
1177 fs_sel = current->thread.fsindex;
1178 gs_sel = current->thread.gsindex;
1179 fs_base = current->thread.fsbase;
1180 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1182 savesegment(fs, fs_sel);
1183 savesegment(gs, gs_sel);
1184 fs_base = read_msr(MSR_FS_BASE);
1185 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1188 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1190 savesegment(fs, fs_sel);
1191 savesegment(gs, gs_sel);
1192 fs_base = segment_base(fs_sel);
1193 gs_base = segment_base(gs_sel);
1196 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1197 vmx->guest_state_loaded = true;
1200 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1202 struct vmcs_host_state *host_state;
1204 if (!vmx->guest_state_loaded)
1207 host_state = &vmx->loaded_vmcs->host_state;
1209 ++vmx->vcpu.stat.host_state_reload;
1211 #ifdef CONFIG_X86_64
1212 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1214 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1215 kvm_load_ldt(host_state->ldt_sel);
1216 #ifdef CONFIG_X86_64
1217 load_gs_index(host_state->gs_sel);
1219 loadsegment(gs, host_state->gs_sel);
1222 if (host_state->fs_sel & 7)
1223 loadsegment(fs, host_state->fs_sel);
1224 #ifdef CONFIG_X86_64
1225 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1226 loadsegment(ds, host_state->ds_sel);
1227 loadsegment(es, host_state->es_sel);
1230 invalidate_tss_limit();
1231 #ifdef CONFIG_X86_64
1232 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1234 load_fixmap_gdt(raw_smp_processor_id());
1235 vmx->guest_state_loaded = false;
1236 vmx->guest_msrs_ready = false;
1239 #ifdef CONFIG_X86_64
1240 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1243 if (vmx->guest_state_loaded)
1244 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1246 return vmx->msr_guest_kernel_gs_base;
1249 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1252 if (vmx->guest_state_loaded)
1253 wrmsrl(MSR_KERNEL_GS_BASE, data);
1255 vmx->msr_guest_kernel_gs_base = data;
1259 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1261 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1262 struct pi_desc old, new;
1266 * In case of hot-plug or hot-unplug, we may have to undo
1267 * vmx_vcpu_pi_put even if there is no assigned device. And we
1268 * always keep PI.NDST up to date for simplicity: it makes the
1269 * code easier, and CPU migration is not a fast path.
1271 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1275 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
1276 * PI.NDST: pi_post_block is the one expected to change PID.NDST and the
1277 * wakeup handler expects the vCPU to be on the blocked_vcpu_list that
1278 * matches PI.NDST. Otherwise, a vcpu may not be able to be woken up
1281 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR || vcpu->cpu == cpu) {
1282 pi_clear_sn(pi_desc);
1283 goto after_clear_sn;
1286 /* The full case. */
1288 old.control = new.control = pi_desc->control;
1290 dest = cpu_physical_id(cpu);
1292 if (x2apic_enabled())
1295 new.ndst = (dest << 8) & 0xFF00;
1298 } while (cmpxchg64(&pi_desc->control, old.control,
1299 new.control) != old.control);
1304 * Clear SN before reading the bitmap. The VT-d firmware
1305 * writes the bitmap and reads SN atomically (5.2.3 in the
1306 * spec), so it doesn't really have a memory barrier that
1307 * pairs with this, but we cannot do that and we need one.
1309 smp_mb__after_atomic();
1311 if (!pi_is_pir_empty(pi_desc))
1315 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1316 struct loaded_vmcs *buddy)
1318 struct vcpu_vmx *vmx = to_vmx(vcpu);
1319 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1322 if (!already_loaded) {
1323 loaded_vmcs_clear(vmx->loaded_vmcs);
1324 local_irq_disable();
1327 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1328 * this cpu's percpu list, otherwise it may not yet be deleted
1329 * from its previous cpu's percpu list. Pairs with the
1330 * smb_wmb() in __loaded_vmcs_clear().
1334 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1335 &per_cpu(loaded_vmcss_on_cpu, cpu));
1339 prev = per_cpu(current_vmcs, cpu);
1340 if (prev != vmx->loaded_vmcs->vmcs) {
1341 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1342 vmcs_load(vmx->loaded_vmcs->vmcs);
1345 * No indirect branch prediction barrier needed when switching
1346 * the active VMCS within a guest, e.g. on nested VM-Enter.
1347 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1349 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1350 indirect_branch_prediction_barrier();
1353 if (!already_loaded) {
1354 void *gdt = get_current_gdt_ro();
1355 unsigned long sysenter_esp;
1358 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1359 * TLB entries from its previous association with the vCPU.
1361 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1364 * Linux uses per-cpu TSS and GDT, so set these when switching
1365 * processors. See 22.2.4.
1367 vmcs_writel(HOST_TR_BASE,
1368 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1369 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1371 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1372 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1374 vmx->loaded_vmcs->cpu = cpu;
1377 /* Setup TSC multiplier */
1378 if (kvm_has_tsc_control &&
1379 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1380 decache_tsc_multiplier(vmx);
1384 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1385 * vcpu mutex is already taken.
1387 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1389 struct vcpu_vmx *vmx = to_vmx(vcpu);
1391 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1393 vmx_vcpu_pi_load(vcpu, cpu);
1395 vmx->host_debugctlmsr = get_debugctlmsr();
1398 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1400 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1402 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1403 !irq_remapping_cap(IRQ_POSTING_CAP) ||
1404 !kvm_vcpu_apicv_active(vcpu))
1407 /* Set SN when the vCPU is preempted */
1408 if (vcpu->preempted)
1412 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1414 vmx_vcpu_pi_put(vcpu);
1416 vmx_prepare_switch_to_host(to_vmx(vcpu));
1419 static bool emulation_required(struct kvm_vcpu *vcpu)
1421 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1424 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1426 struct vcpu_vmx *vmx = to_vmx(vcpu);
1427 unsigned long rflags, save_rflags;
1429 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1430 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1431 rflags = vmcs_readl(GUEST_RFLAGS);
1432 if (vmx->rmode.vm86_active) {
1433 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1434 save_rflags = vmx->rmode.save_rflags;
1435 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1437 vmx->rflags = rflags;
1442 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1444 struct vcpu_vmx *vmx = to_vmx(vcpu);
1445 unsigned long old_rflags;
1447 if (is_unrestricted_guest(vcpu)) {
1448 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1449 vmx->rflags = rflags;
1450 vmcs_writel(GUEST_RFLAGS, rflags);
1454 old_rflags = vmx_get_rflags(vcpu);
1455 vmx->rflags = rflags;
1456 if (vmx->rmode.vm86_active) {
1457 vmx->rmode.save_rflags = rflags;
1458 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1460 vmcs_writel(GUEST_RFLAGS, rflags);
1462 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1463 vmx->emulation_required = emulation_required(vcpu);
1466 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1468 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1471 if (interruptibility & GUEST_INTR_STATE_STI)
1472 ret |= KVM_X86_SHADOW_INT_STI;
1473 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1474 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1479 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1481 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1482 u32 interruptibility = interruptibility_old;
1484 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1486 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1487 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1488 else if (mask & KVM_X86_SHADOW_INT_STI)
1489 interruptibility |= GUEST_INTR_STATE_STI;
1491 if ((interruptibility != interruptibility_old))
1492 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1495 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1497 struct vcpu_vmx *vmx = to_vmx(vcpu);
1498 unsigned long value;
1501 * Any MSR write that attempts to change bits marked reserved will
1504 if (data & vmx->pt_desc.ctl_bitmask)
1508 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1509 * result in a #GP unless the same write also clears TraceEn.
1511 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1512 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1516 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1517 * and FabricEn would cause #GP, if
1518 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1520 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1521 !(data & RTIT_CTL_FABRIC_EN) &&
1522 !intel_pt_validate_cap(vmx->pt_desc.caps,
1523 PT_CAP_single_range_output))
1527 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1528 * utilize encodings marked reserved will casue a #GP fault.
1530 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1531 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1532 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1533 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1535 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1536 PT_CAP_cycle_thresholds);
1537 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1538 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1539 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1541 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1542 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1543 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1544 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1548 * If ADDRx_CFG is reserved or the encodings is >2 will
1549 * cause a #GP fault.
1551 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1552 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1554 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1555 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1557 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1558 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1560 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1561 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1567 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
1572 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1574 unsigned long rip, orig_rip;
1577 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1578 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1579 * set when EPT misconfig occurs. In practice, real hardware updates
1580 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1581 * (namely Hyper-V) don't set it due to it being undefined behavior,
1582 * i.e. we end up advancing IP with some random value.
1584 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1585 to_vmx(vcpu)->exit_reason != EXIT_REASON_EPT_MISCONFIG) {
1586 orig_rip = kvm_rip_read(vcpu);
1587 rip = orig_rip + vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1588 #ifdef CONFIG_X86_64
1590 * We need to mask out the high 32 bits of RIP if not in 64-bit
1591 * mode, but just finding out that we are in 64-bit mode is
1592 * quite expensive. Only do it if there was a carry.
1594 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1597 kvm_rip_write(vcpu, rip);
1599 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1603 /* skipping an emulated instruction also counts */
1604 vmx_set_interrupt_shadow(vcpu, 0);
1610 * Recognizes a pending MTF VM-exit and records the nested state for later
1613 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1615 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1616 struct vcpu_vmx *vmx = to_vmx(vcpu);
1618 if (!is_guest_mode(vcpu))
1622 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1623 * T-bit traps. As instruction emulation is completed (i.e. at the
1624 * instruction boundary), any #DB exception pending delivery must be a
1625 * debug-trap. Record the pending MTF state to be delivered in
1626 * vmx_check_nested_events().
1628 if (nested_cpu_has_mtf(vmcs12) &&
1629 (!vcpu->arch.exception.pending ||
1630 vcpu->arch.exception.nr == DB_VECTOR))
1631 vmx->nested.mtf_pending = true;
1633 vmx->nested.mtf_pending = false;
1636 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1638 vmx_update_emulated_instruction(vcpu);
1639 return skip_emulated_instruction(vcpu);
1642 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1645 * Ensure that we clear the HLT state in the VMCS. We don't need to
1646 * explicitly skip the instruction because if the HLT state is set,
1647 * then the instruction is already executing and RIP has already been
1650 if (kvm_hlt_in_guest(vcpu->kvm) &&
1651 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1652 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1655 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1657 struct vcpu_vmx *vmx = to_vmx(vcpu);
1658 unsigned nr = vcpu->arch.exception.nr;
1659 bool has_error_code = vcpu->arch.exception.has_error_code;
1660 u32 error_code = vcpu->arch.exception.error_code;
1661 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1663 kvm_deliver_exception_payload(vcpu);
1665 if (has_error_code) {
1666 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1667 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1670 if (vmx->rmode.vm86_active) {
1672 if (kvm_exception_is_soft(nr))
1673 inc_eip = vcpu->arch.event_exit_inst_len;
1674 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1678 WARN_ON_ONCE(vmx->emulation_required);
1680 if (kvm_exception_is_soft(nr)) {
1681 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1682 vmx->vcpu.arch.event_exit_inst_len);
1683 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1685 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1687 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1689 vmx_clear_hlt(vcpu);
1693 * Swap MSR entry in host/guest MSR entry array.
1695 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1697 struct shared_msr_entry tmp;
1699 tmp = vmx->guest_msrs[to];
1700 vmx->guest_msrs[to] = vmx->guest_msrs[from];
1701 vmx->guest_msrs[from] = tmp;
1705 * Set up the vmcs to automatically save and restore system
1706 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1707 * mode, as fiddling with msrs is very expensive.
1709 static void setup_msrs(struct vcpu_vmx *vmx)
1711 int save_nmsrs, index;
1714 #ifdef CONFIG_X86_64
1716 * The SYSCALL MSRs are only needed on long mode guests, and only
1717 * when EFER.SCE is set.
1719 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1720 index = __find_msr_index(vmx, MSR_STAR);
1722 move_msr_up(vmx, index, save_nmsrs++);
1723 index = __find_msr_index(vmx, MSR_LSTAR);
1725 move_msr_up(vmx, index, save_nmsrs++);
1726 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1728 move_msr_up(vmx, index, save_nmsrs++);
1731 index = __find_msr_index(vmx, MSR_EFER);
1732 if (index >= 0 && update_transition_efer(vmx, index))
1733 move_msr_up(vmx, index, save_nmsrs++);
1734 index = __find_msr_index(vmx, MSR_TSC_AUX);
1735 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1736 move_msr_up(vmx, index, save_nmsrs++);
1737 index = __find_msr_index(vmx, MSR_IA32_TSX_CTRL);
1739 move_msr_up(vmx, index, save_nmsrs++);
1741 vmx->save_nmsrs = save_nmsrs;
1742 vmx->guest_msrs_ready = false;
1744 if (cpu_has_vmx_msr_bitmap())
1745 vmx_update_msr_bitmap(&vmx->vcpu);
1748 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1750 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1751 u64 g_tsc_offset = 0;
1754 * We're here if L1 chose not to trap WRMSR to TSC. According
1755 * to the spec, this should set L1's TSC; The offset that L1
1756 * set for L2 remains unchanged, and still needs to be added
1757 * to the newly set TSC to get L2's TSC.
1759 if (is_guest_mode(vcpu) &&
1760 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
1761 g_tsc_offset = vmcs12->tsc_offset;
1763 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1764 vcpu->arch.tsc_offset - g_tsc_offset,
1766 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1767 return offset + g_tsc_offset;
1771 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1772 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1773 * all guests if the "nested" module option is off, and can also be disabled
1774 * for a single guest by disabling its VMX cpuid bit.
1776 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1778 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1781 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1784 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1786 return !(val & ~valid_bits);
1789 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1791 switch (msr->index) {
1792 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1795 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1796 case MSR_IA32_PERF_CAPABILITIES:
1797 msr->data = vmx_get_perf_capabilities();
1800 return KVM_MSR_RET_INVALID;
1805 * Reads an msr value (of 'msr_index') into 'pdata'.
1806 * Returns 0 on success, non-0 otherwise.
1807 * Assumes vcpu_load() was already called.
1809 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1811 struct vcpu_vmx *vmx = to_vmx(vcpu);
1812 struct shared_msr_entry *msr;
1815 switch (msr_info->index) {
1816 #ifdef CONFIG_X86_64
1818 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1821 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1823 case MSR_KERNEL_GS_BASE:
1824 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1828 return kvm_get_msr_common(vcpu, msr_info);
1829 case MSR_IA32_TSX_CTRL:
1830 if (!msr_info->host_initiated &&
1831 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1833 goto find_shared_msr;
1834 case MSR_IA32_UMWAIT_CONTROL:
1835 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1838 msr_info->data = vmx->msr_ia32_umwait_control;
1840 case MSR_IA32_SPEC_CTRL:
1841 if (!msr_info->host_initiated &&
1842 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1845 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1847 case MSR_IA32_SYSENTER_CS:
1848 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1850 case MSR_IA32_SYSENTER_EIP:
1851 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1853 case MSR_IA32_SYSENTER_ESP:
1854 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1856 case MSR_IA32_BNDCFGS:
1857 if (!kvm_mpx_supported() ||
1858 (!msr_info->host_initiated &&
1859 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1861 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1863 case MSR_IA32_MCG_EXT_CTL:
1864 if (!msr_info->host_initiated &&
1865 !(vmx->msr_ia32_feature_control &
1866 FEAT_CTL_LMCE_ENABLED))
1868 msr_info->data = vcpu->arch.mcg_ext_ctl;
1870 case MSR_IA32_FEAT_CTL:
1871 msr_info->data = vmx->msr_ia32_feature_control;
1873 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1874 if (!nested_vmx_allowed(vcpu))
1876 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1880 * Enlightened VMCS v1 doesn't have certain fields, but buggy
1881 * Hyper-V versions are still trying to use corresponding
1882 * features when they are exposed. Filter out the essential
1885 if (!msr_info->host_initiated &&
1886 vmx->nested.enlightened_vmcs_enabled)
1887 nested_evmcs_filter_control_msr(msr_info->index,
1890 case MSR_IA32_RTIT_CTL:
1891 if (!vmx_pt_mode_is_host_guest())
1893 msr_info->data = vmx->pt_desc.guest.ctl;
1895 case MSR_IA32_RTIT_STATUS:
1896 if (!vmx_pt_mode_is_host_guest())
1898 msr_info->data = vmx->pt_desc.guest.status;
1900 case MSR_IA32_RTIT_CR3_MATCH:
1901 if (!vmx_pt_mode_is_host_guest() ||
1902 !intel_pt_validate_cap(vmx->pt_desc.caps,
1903 PT_CAP_cr3_filtering))
1905 msr_info->data = vmx->pt_desc.guest.cr3_match;
1907 case MSR_IA32_RTIT_OUTPUT_BASE:
1908 if (!vmx_pt_mode_is_host_guest() ||
1909 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1910 PT_CAP_topa_output) &&
1911 !intel_pt_validate_cap(vmx->pt_desc.caps,
1912 PT_CAP_single_range_output)))
1914 msr_info->data = vmx->pt_desc.guest.output_base;
1916 case MSR_IA32_RTIT_OUTPUT_MASK:
1917 if (!vmx_pt_mode_is_host_guest() ||
1918 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1919 PT_CAP_topa_output) &&
1920 !intel_pt_validate_cap(vmx->pt_desc.caps,
1921 PT_CAP_single_range_output)))
1923 msr_info->data = vmx->pt_desc.guest.output_mask;
1925 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1926 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1927 if (!vmx_pt_mode_is_host_guest() ||
1928 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1929 PT_CAP_num_address_ranges)))
1932 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1934 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1937 if (!msr_info->host_initiated &&
1938 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1940 goto find_shared_msr;
1943 msr = find_msr_entry(vmx, msr_info->index);
1945 msr_info->data = msr->data;
1948 return kvm_get_msr_common(vcpu, msr_info);
1954 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
1957 #ifdef CONFIG_X86_64
1958 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
1961 return (unsigned long)data;
1965 * Writes msr value into the appropriate "register".
1966 * Returns 0 on success, non-0 otherwise.
1967 * Assumes vcpu_load() was already called.
1969 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1971 struct vcpu_vmx *vmx = to_vmx(vcpu);
1972 struct shared_msr_entry *msr;
1974 u32 msr_index = msr_info->index;
1975 u64 data = msr_info->data;
1978 switch (msr_index) {
1980 ret = kvm_set_msr_common(vcpu, msr_info);
1982 #ifdef CONFIG_X86_64
1984 vmx_segment_cache_clear(vmx);
1985 vmcs_writel(GUEST_FS_BASE, data);
1988 vmx_segment_cache_clear(vmx);
1989 vmcs_writel(GUEST_GS_BASE, data);
1991 case MSR_KERNEL_GS_BASE:
1992 vmx_write_guest_kernel_gs_base(vmx, data);
1995 case MSR_IA32_SYSENTER_CS:
1996 if (is_guest_mode(vcpu))
1997 get_vmcs12(vcpu)->guest_sysenter_cs = data;
1998 vmcs_write32(GUEST_SYSENTER_CS, data);
2000 case MSR_IA32_SYSENTER_EIP:
2001 if (is_guest_mode(vcpu)) {
2002 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2003 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2005 vmcs_writel(GUEST_SYSENTER_EIP, data);
2007 case MSR_IA32_SYSENTER_ESP:
2008 if (is_guest_mode(vcpu)) {
2009 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2010 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2012 vmcs_writel(GUEST_SYSENTER_ESP, data);
2014 case MSR_IA32_DEBUGCTLMSR:
2015 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2016 VM_EXIT_SAVE_DEBUG_CONTROLS)
2017 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2019 ret = kvm_set_msr_common(vcpu, msr_info);
2022 case MSR_IA32_BNDCFGS:
2023 if (!kvm_mpx_supported() ||
2024 (!msr_info->host_initiated &&
2025 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2027 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2028 (data & MSR_IA32_BNDCFGS_RSVD))
2030 vmcs_write64(GUEST_BNDCFGS, data);
2032 case MSR_IA32_UMWAIT_CONTROL:
2033 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2036 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2037 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2040 vmx->msr_ia32_umwait_control = data;
2042 case MSR_IA32_SPEC_CTRL:
2043 if (!msr_info->host_initiated &&
2044 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
2047 if (kvm_spec_ctrl_test_value(data))
2050 vmx->spec_ctrl = data;
2056 * When it's written (to non-zero) for the first time, pass
2060 * The handling of the MSR bitmap for L2 guests is done in
2061 * nested_vmx_prepare_msr_bitmap. We should not touch the
2062 * vmcs02.msr_bitmap here since it gets completely overwritten
2063 * in the merging. We update the vmcs01 here for L1 as well
2064 * since it will end up touching the MSR anyway now.
2066 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
2070 case MSR_IA32_TSX_CTRL:
2071 if (!msr_info->host_initiated &&
2072 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2074 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2076 goto find_shared_msr;
2077 case MSR_IA32_PRED_CMD:
2078 if (!msr_info->host_initiated &&
2079 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
2082 if (data & ~PRED_CMD_IBPB)
2084 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL))
2089 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2093 * When it's written (to non-zero) for the first time, pass
2097 * The handling of the MSR bitmap for L2 guests is done in
2098 * nested_vmx_prepare_msr_bitmap. We should not touch the
2099 * vmcs02.msr_bitmap here since it gets completely overwritten
2102 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
2105 case MSR_IA32_CR_PAT:
2106 if (!kvm_pat_valid(data))
2109 if (is_guest_mode(vcpu) &&
2110 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2111 get_vmcs12(vcpu)->guest_ia32_pat = data;
2113 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2114 vmcs_write64(GUEST_IA32_PAT, data);
2115 vcpu->arch.pat = data;
2118 ret = kvm_set_msr_common(vcpu, msr_info);
2120 case MSR_IA32_TSC_ADJUST:
2121 ret = kvm_set_msr_common(vcpu, msr_info);
2123 case MSR_IA32_MCG_EXT_CTL:
2124 if ((!msr_info->host_initiated &&
2125 !(to_vmx(vcpu)->msr_ia32_feature_control &
2126 FEAT_CTL_LMCE_ENABLED)) ||
2127 (data & ~MCG_EXT_CTL_LMCE_EN))
2129 vcpu->arch.mcg_ext_ctl = data;
2131 case MSR_IA32_FEAT_CTL:
2132 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2133 (to_vmx(vcpu)->msr_ia32_feature_control &
2134 FEAT_CTL_LOCKED && !msr_info->host_initiated))
2136 vmx->msr_ia32_feature_control = data;
2137 if (msr_info->host_initiated && data == 0)
2138 vmx_leave_nested(vcpu);
2140 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2141 if (!msr_info->host_initiated)
2142 return 1; /* they are read-only */
2143 if (!nested_vmx_allowed(vcpu))
2145 return vmx_set_vmx_msr(vcpu, msr_index, data);
2146 case MSR_IA32_RTIT_CTL:
2147 if (!vmx_pt_mode_is_host_guest() ||
2148 vmx_rtit_ctl_check(vcpu, data) ||
2151 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2152 vmx->pt_desc.guest.ctl = data;
2153 pt_update_intercept_for_msr(vmx);
2155 case MSR_IA32_RTIT_STATUS:
2156 if (!pt_can_write_msr(vmx))
2158 if (data & MSR_IA32_RTIT_STATUS_MASK)
2160 vmx->pt_desc.guest.status = data;
2162 case MSR_IA32_RTIT_CR3_MATCH:
2163 if (!pt_can_write_msr(vmx))
2165 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2166 PT_CAP_cr3_filtering))
2168 vmx->pt_desc.guest.cr3_match = data;
2170 case MSR_IA32_RTIT_OUTPUT_BASE:
2171 if (!pt_can_write_msr(vmx))
2173 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2174 PT_CAP_topa_output) &&
2175 !intel_pt_validate_cap(vmx->pt_desc.caps,
2176 PT_CAP_single_range_output))
2178 if (!pt_output_base_valid(vcpu, data))
2180 vmx->pt_desc.guest.output_base = data;
2182 case MSR_IA32_RTIT_OUTPUT_MASK:
2183 if (!pt_can_write_msr(vmx))
2185 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2186 PT_CAP_topa_output) &&
2187 !intel_pt_validate_cap(vmx->pt_desc.caps,
2188 PT_CAP_single_range_output))
2190 vmx->pt_desc.guest.output_mask = data;
2192 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2193 if (!pt_can_write_msr(vmx))
2195 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2196 if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2197 PT_CAP_num_address_ranges))
2199 if (is_noncanonical_address(data, vcpu))
2202 vmx->pt_desc.guest.addr_b[index / 2] = data;
2204 vmx->pt_desc.guest.addr_a[index / 2] = data;
2207 if (!msr_info->host_initiated &&
2208 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2210 /* Check reserved bit, higher 32 bits should be zero */
2211 if ((data >> 32) != 0)
2213 goto find_shared_msr;
2217 msr = find_msr_entry(vmx, msr_index);
2219 ret = vmx_set_guest_msr(vmx, msr, data);
2221 ret = kvm_set_msr_common(vcpu, msr_info);
2227 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2229 unsigned long guest_owned_bits;
2231 kvm_register_mark_available(vcpu, reg);
2235 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2238 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2240 case VCPU_EXREG_PDPTR:
2242 ept_save_pdptrs(vcpu);
2244 case VCPU_EXREG_CR0:
2245 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2247 vcpu->arch.cr0 &= ~guest_owned_bits;
2248 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2250 case VCPU_EXREG_CR3:
2251 if (is_unrestricted_guest(vcpu) ||
2252 (enable_ept && is_paging(vcpu)))
2253 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2255 case VCPU_EXREG_CR4:
2256 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2258 vcpu->arch.cr4 &= ~guest_owned_bits;
2259 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2267 static __init int cpu_has_kvm_support(void)
2269 return cpu_has_vmx();
2272 static __init int vmx_disabled_by_bios(void)
2274 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2275 !boot_cpu_has(X86_FEATURE_VMX);
2278 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2282 cr4_set_bits(X86_CR4_VMXE);
2283 intel_pt_handle_vmx(1);
2285 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2286 _ASM_EXTABLE(1b, %l[fault])
2287 : : [vmxon_pointer] "m"(vmxon_pointer)
2292 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2293 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2294 intel_pt_handle_vmx(0);
2295 cr4_clear_bits(X86_CR4_VMXE);
2300 static int hardware_enable(void)
2302 int cpu = raw_smp_processor_id();
2303 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2306 if (cr4_read_shadow() & X86_CR4_VMXE)
2310 * This can happen if we hot-added a CPU but failed to allocate
2311 * VP assist page for it.
2313 if (static_branch_unlikely(&enable_evmcs) &&
2314 !hv_get_vp_assist_page(cpu))
2317 r = kvm_cpu_vmxon(phys_addr);
2327 static void vmclear_local_loaded_vmcss(void)
2329 int cpu = raw_smp_processor_id();
2330 struct loaded_vmcs *v, *n;
2332 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2333 loaded_vmcss_on_cpu_link)
2334 __loaded_vmcs_clear(v);
2338 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2341 static void kvm_cpu_vmxoff(void)
2343 asm volatile (__ex("vmxoff"));
2345 intel_pt_handle_vmx(0);
2346 cr4_clear_bits(X86_CR4_VMXE);
2349 static void hardware_disable(void)
2351 vmclear_local_loaded_vmcss();
2356 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2357 * directly instead of going through cpu_has(), to ensure KVM is trapping
2358 * ENCLS whenever it's supported in hardware. It does not matter whether
2359 * the host OS supports or has enabled SGX.
2361 static bool cpu_has_sgx(void)
2363 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2366 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2367 u32 msr, u32 *result)
2369 u32 vmx_msr_low, vmx_msr_high;
2370 u32 ctl = ctl_min | ctl_opt;
2372 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2374 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2375 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2377 /* Ensure minimum (required) set of control bits are supported. */
2385 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2386 struct vmx_capability *vmx_cap)
2388 u32 vmx_msr_low, vmx_msr_high;
2389 u32 min, opt, min2, opt2;
2390 u32 _pin_based_exec_control = 0;
2391 u32 _cpu_based_exec_control = 0;
2392 u32 _cpu_based_2nd_exec_control = 0;
2393 u32 _vmexit_control = 0;
2394 u32 _vmentry_control = 0;
2396 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2397 min = CPU_BASED_HLT_EXITING |
2398 #ifdef CONFIG_X86_64
2399 CPU_BASED_CR8_LOAD_EXITING |
2400 CPU_BASED_CR8_STORE_EXITING |
2402 CPU_BASED_CR3_LOAD_EXITING |
2403 CPU_BASED_CR3_STORE_EXITING |
2404 CPU_BASED_UNCOND_IO_EXITING |
2405 CPU_BASED_MOV_DR_EXITING |
2406 CPU_BASED_USE_TSC_OFFSETTING |
2407 CPU_BASED_MWAIT_EXITING |
2408 CPU_BASED_MONITOR_EXITING |
2409 CPU_BASED_INVLPG_EXITING |
2410 CPU_BASED_RDPMC_EXITING;
2412 opt = CPU_BASED_TPR_SHADOW |
2413 CPU_BASED_USE_MSR_BITMAPS |
2414 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2415 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2416 &_cpu_based_exec_control) < 0)
2418 #ifdef CONFIG_X86_64
2419 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2420 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2421 ~CPU_BASED_CR8_STORE_EXITING;
2423 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2425 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2426 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2427 SECONDARY_EXEC_WBINVD_EXITING |
2428 SECONDARY_EXEC_ENABLE_VPID |
2429 SECONDARY_EXEC_ENABLE_EPT |
2430 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2431 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2432 SECONDARY_EXEC_DESC |
2433 SECONDARY_EXEC_RDTSCP |
2434 SECONDARY_EXEC_ENABLE_INVPCID |
2435 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2436 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2437 SECONDARY_EXEC_SHADOW_VMCS |
2438 SECONDARY_EXEC_XSAVES |
2439 SECONDARY_EXEC_RDSEED_EXITING |
2440 SECONDARY_EXEC_RDRAND_EXITING |
2441 SECONDARY_EXEC_ENABLE_PML |
2442 SECONDARY_EXEC_TSC_SCALING |
2443 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2444 SECONDARY_EXEC_PT_USE_GPA |
2445 SECONDARY_EXEC_PT_CONCEAL_VMX |
2446 SECONDARY_EXEC_ENABLE_VMFUNC;
2448 opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2449 if (adjust_vmx_controls(min2, opt2,
2450 MSR_IA32_VMX_PROCBASED_CTLS2,
2451 &_cpu_based_2nd_exec_control) < 0)
2454 #ifndef CONFIG_X86_64
2455 if (!(_cpu_based_2nd_exec_control &
2456 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2457 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2460 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2461 _cpu_based_2nd_exec_control &= ~(
2462 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2463 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2464 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2466 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2467 &vmx_cap->ept, &vmx_cap->vpid);
2469 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2470 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2472 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2473 CPU_BASED_CR3_STORE_EXITING |
2474 CPU_BASED_INVLPG_EXITING);
2475 } else if (vmx_cap->ept) {
2477 pr_warn_once("EPT CAP should not exist if not support "
2478 "1-setting enable EPT VM-execution control\n");
2480 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2483 pr_warn_once("VPID CAP should not exist if not support "
2484 "1-setting enable VPID VM-execution control\n");
2487 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2488 #ifdef CONFIG_X86_64
2489 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2491 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2492 VM_EXIT_LOAD_IA32_PAT |
2493 VM_EXIT_LOAD_IA32_EFER |
2494 VM_EXIT_CLEAR_BNDCFGS |
2495 VM_EXIT_PT_CONCEAL_PIP |
2496 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2497 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2498 &_vmexit_control) < 0)
2501 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2502 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2503 PIN_BASED_VMX_PREEMPTION_TIMER;
2504 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2505 &_pin_based_exec_control) < 0)
2508 if (cpu_has_broken_vmx_preemption_timer())
2509 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2510 if (!(_cpu_based_2nd_exec_control &
2511 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2512 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2514 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2515 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2516 VM_ENTRY_LOAD_IA32_PAT |
2517 VM_ENTRY_LOAD_IA32_EFER |
2518 VM_ENTRY_LOAD_BNDCFGS |
2519 VM_ENTRY_PT_CONCEAL_PIP |
2520 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2521 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2522 &_vmentry_control) < 0)
2526 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2527 * can't be used due to an errata where VM Exit may incorrectly clear
2528 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2529 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2531 if (boot_cpu_data.x86 == 0x6) {
2532 switch (boot_cpu_data.x86_model) {
2533 case 26: /* AAK155 */
2534 case 30: /* AAP115 */
2535 case 37: /* AAT100 */
2536 case 44: /* BC86,AAY89,BD102 */
2538 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2539 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2540 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2541 "does not work properly. Using workaround\n");
2549 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2551 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2552 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2555 #ifdef CONFIG_X86_64
2556 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2557 if (vmx_msr_high & (1u<<16))
2561 /* Require Write-Back (WB) memory type for VMCS accesses. */
2562 if (((vmx_msr_high >> 18) & 15) != 6)
2565 vmcs_conf->size = vmx_msr_high & 0x1fff;
2566 vmcs_conf->order = get_order(vmcs_conf->size);
2567 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2569 vmcs_conf->revision_id = vmx_msr_low;
2571 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2572 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2573 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2574 vmcs_conf->vmexit_ctrl = _vmexit_control;
2575 vmcs_conf->vmentry_ctrl = _vmentry_control;
2577 if (static_branch_unlikely(&enable_evmcs))
2578 evmcs_sanitize_exec_ctrls(vmcs_conf);
2583 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2585 int node = cpu_to_node(cpu);
2589 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2592 vmcs = page_address(pages);
2593 memset(vmcs, 0, vmcs_config.size);
2595 /* KVM supports Enlightened VMCS v1 only */
2596 if (static_branch_unlikely(&enable_evmcs))
2597 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2599 vmcs->hdr.revision_id = vmcs_config.revision_id;
2602 vmcs->hdr.shadow_vmcs = 1;
2606 void free_vmcs(struct vmcs *vmcs)
2608 free_pages((unsigned long)vmcs, vmcs_config.order);
2612 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2614 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2616 if (!loaded_vmcs->vmcs)
2618 loaded_vmcs_clear(loaded_vmcs);
2619 free_vmcs(loaded_vmcs->vmcs);
2620 loaded_vmcs->vmcs = NULL;
2621 if (loaded_vmcs->msr_bitmap)
2622 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2623 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2626 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2628 loaded_vmcs->vmcs = alloc_vmcs(false);
2629 if (!loaded_vmcs->vmcs)
2632 vmcs_clear(loaded_vmcs->vmcs);
2634 loaded_vmcs->shadow_vmcs = NULL;
2635 loaded_vmcs->hv_timer_soft_disabled = false;
2636 loaded_vmcs->cpu = -1;
2637 loaded_vmcs->launched = 0;
2639 if (cpu_has_vmx_msr_bitmap()) {
2640 loaded_vmcs->msr_bitmap = (unsigned long *)
2641 __get_free_page(GFP_KERNEL_ACCOUNT);
2642 if (!loaded_vmcs->msr_bitmap)
2644 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2646 if (IS_ENABLED(CONFIG_HYPERV) &&
2647 static_branch_unlikely(&enable_evmcs) &&
2648 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2649 struct hv_enlightened_vmcs *evmcs =
2650 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2652 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2656 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2657 memset(&loaded_vmcs->controls_shadow, 0,
2658 sizeof(struct vmcs_controls_shadow));
2663 free_loaded_vmcs(loaded_vmcs);
2667 static void free_kvm_area(void)
2671 for_each_possible_cpu(cpu) {
2672 free_vmcs(per_cpu(vmxarea, cpu));
2673 per_cpu(vmxarea, cpu) = NULL;
2677 static __init int alloc_kvm_area(void)
2681 for_each_possible_cpu(cpu) {
2684 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2691 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2692 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2693 * revision_id reported by MSR_IA32_VMX_BASIC.
2695 * However, even though not explicitly documented by
2696 * TLFS, VMXArea passed as VMXON argument should
2697 * still be marked with revision_id reported by
2700 if (static_branch_unlikely(&enable_evmcs))
2701 vmcs->hdr.revision_id = vmcs_config.revision_id;
2703 per_cpu(vmxarea, cpu) = vmcs;
2708 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2709 struct kvm_segment *save)
2711 if (!emulate_invalid_guest_state) {
2713 * CS and SS RPL should be equal during guest entry according
2714 * to VMX spec, but in reality it is not always so. Since vcpu
2715 * is in the middle of the transition from real mode to
2716 * protected mode it is safe to assume that RPL 0 is a good
2719 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2720 save->selector &= ~SEGMENT_RPL_MASK;
2721 save->dpl = save->selector & SEGMENT_RPL_MASK;
2724 vmx_set_segment(vcpu, save, seg);
2727 static void enter_pmode(struct kvm_vcpu *vcpu)
2729 unsigned long flags;
2730 struct vcpu_vmx *vmx = to_vmx(vcpu);
2733 * Update real mode segment cache. It may be not up-to-date if sement
2734 * register was written while vcpu was in a guest mode.
2736 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2737 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2738 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2739 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2740 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2741 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2743 vmx->rmode.vm86_active = 0;
2745 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2747 flags = vmcs_readl(GUEST_RFLAGS);
2748 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2749 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2750 vmcs_writel(GUEST_RFLAGS, flags);
2752 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2753 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2755 update_exception_bitmap(vcpu);
2757 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2758 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2759 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2760 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2761 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2762 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2765 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2767 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2768 struct kvm_segment var = *save;
2771 if (seg == VCPU_SREG_CS)
2774 if (!emulate_invalid_guest_state) {
2775 var.selector = var.base >> 4;
2776 var.base = var.base & 0xffff0;
2786 if (save->base & 0xf)
2787 printk_once(KERN_WARNING "kvm: segment base is not "
2788 "paragraph aligned when entering "
2789 "protected mode (seg=%d)", seg);
2792 vmcs_write16(sf->selector, var.selector);
2793 vmcs_writel(sf->base, var.base);
2794 vmcs_write32(sf->limit, var.limit);
2795 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2798 static void enter_rmode(struct kvm_vcpu *vcpu)
2800 unsigned long flags;
2801 struct vcpu_vmx *vmx = to_vmx(vcpu);
2802 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2804 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2805 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2806 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2807 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2808 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2809 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2810 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2812 vmx->rmode.vm86_active = 1;
2815 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2816 * vcpu. Warn the user that an update is overdue.
2818 if (!kvm_vmx->tss_addr)
2819 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2820 "called before entering vcpu\n");
2822 vmx_segment_cache_clear(vmx);
2824 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2825 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2826 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2828 flags = vmcs_readl(GUEST_RFLAGS);
2829 vmx->rmode.save_rflags = flags;
2831 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2833 vmcs_writel(GUEST_RFLAGS, flags);
2834 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2835 update_exception_bitmap(vcpu);
2837 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2838 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2839 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2840 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2841 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2842 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2844 kvm_mmu_reset_context(vcpu);
2847 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2849 struct vcpu_vmx *vmx = to_vmx(vcpu);
2850 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2855 vcpu->arch.efer = efer;
2856 if (efer & EFER_LMA) {
2857 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2860 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2862 msr->data = efer & ~EFER_LME;
2867 #ifdef CONFIG_X86_64
2869 static void enter_lmode(struct kvm_vcpu *vcpu)
2873 vmx_segment_cache_clear(to_vmx(vcpu));
2875 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2876 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2877 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2879 vmcs_write32(GUEST_TR_AR_BYTES,
2880 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2881 | VMX_AR_TYPE_BUSY_64_TSS);
2883 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2886 static void exit_lmode(struct kvm_vcpu *vcpu)
2888 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2889 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2894 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
2896 struct vcpu_vmx *vmx = to_vmx(vcpu);
2899 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
2900 * the CPU is not required to invalidate guest-physical mappings on
2901 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
2902 * associated with the root EPT structure and not any particular VPID
2903 * (INVVPID also isn't required to invalidate guest-physical mappings).
2907 } else if (enable_vpid) {
2908 if (cpu_has_vmx_invvpid_global()) {
2909 vpid_sync_vcpu_global();
2911 vpid_sync_vcpu_single(vmx->vpid);
2912 vpid_sync_vcpu_single(vmx->nested.vpid02);
2917 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
2919 struct kvm_mmu *mmu = vcpu->arch.mmu;
2920 u64 root_hpa = mmu->root_hpa;
2922 /* No flush required if the current context is invalid. */
2923 if (!VALID_PAGE(root_hpa))
2927 ept_sync_context(construct_eptp(vcpu, root_hpa,
2928 mmu->shadow_root_level));
2929 else if (!is_guest_mode(vcpu))
2930 vpid_sync_context(to_vmx(vcpu)->vpid);
2932 vpid_sync_context(nested_get_vpid02(vcpu));
2935 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2938 * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
2939 * vmx_flush_tlb_guest() for an explanation of why this is ok.
2941 vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
2944 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
2947 * vpid_sync_context() is a nop if vmx->vpid==0, e.g. if enable_vpid==0
2948 * or a vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit
2949 * are required to flush GVA->{G,H}PA mappings from the TLB if vpid is
2950 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
2951 * i.e. no explicit INVVPID is necessary.
2953 vpid_sync_context(to_vmx(vcpu)->vpid);
2956 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
2958 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2960 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
2963 if (is_pae_paging(vcpu)) {
2964 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2965 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2966 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2967 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2971 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2973 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2975 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
2978 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2979 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2980 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2981 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2983 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
2986 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2988 struct kvm_vcpu *vcpu)
2990 struct vcpu_vmx *vmx = to_vmx(vcpu);
2992 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
2993 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
2994 if (!(cr0 & X86_CR0_PG)) {
2995 /* From paging/starting to nonpaging */
2996 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
2997 CPU_BASED_CR3_STORE_EXITING);
2998 vcpu->arch.cr0 = cr0;
2999 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3000 } else if (!is_paging(vcpu)) {
3001 /* From nonpaging to paging */
3002 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3003 CPU_BASED_CR3_STORE_EXITING);
3004 vcpu->arch.cr0 = cr0;
3005 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3008 if (!(cr0 & X86_CR0_WP))
3009 *hw_cr0 &= ~X86_CR0_WP;
3012 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3014 struct vcpu_vmx *vmx = to_vmx(vcpu);
3015 unsigned long hw_cr0;
3017 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3018 if (is_unrestricted_guest(vcpu))
3019 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3021 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3023 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3026 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3030 #ifdef CONFIG_X86_64
3031 if (vcpu->arch.efer & EFER_LME) {
3032 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3034 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3039 if (enable_ept && !is_unrestricted_guest(vcpu))
3040 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3042 vmcs_writel(CR0_READ_SHADOW, cr0);
3043 vmcs_writel(GUEST_CR0, hw_cr0);
3044 vcpu->arch.cr0 = cr0;
3045 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3047 /* depends on vcpu->arch.cr0 to be set to a new value */
3048 vmx->emulation_required = emulation_required(vcpu);
3051 static int vmx_get_max_tdp_level(void)
3053 if (cpu_has_vmx_ept_5levels())
3058 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa,
3061 u64 eptp = VMX_EPTP_MT_WB;
3063 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3065 if (enable_ept_ad_bits &&
3066 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3067 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3068 eptp |= (root_hpa & PAGE_MASK);
3073 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, unsigned long pgd,
3076 struct kvm *kvm = vcpu->kvm;
3077 bool update_guest_cr3 = true;
3078 unsigned long guest_cr3;
3082 eptp = construct_eptp(vcpu, pgd, pgd_level);
3083 vmcs_write64(EPT_POINTER, eptp);
3085 if (kvm_x86_ops.tlb_remote_flush) {
3086 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3087 to_vmx(vcpu)->ept_pointer = eptp;
3088 to_kvm_vmx(kvm)->ept_pointers_match
3089 = EPT_POINTERS_CHECK;
3090 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3093 if (!enable_unrestricted_guest && !is_paging(vcpu))
3094 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3095 else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3096 guest_cr3 = vcpu->arch.cr3;
3097 else /* vmcs01.GUEST_CR3 is already up-to-date. */
3098 update_guest_cr3 = false;
3099 vmx_ept_load_pdptrs(vcpu);
3104 if (update_guest_cr3)
3105 vmcs_writel(GUEST_CR3, guest_cr3);
3108 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3110 struct vcpu_vmx *vmx = to_vmx(vcpu);
3112 * Pass through host's Machine Check Enable value to hw_cr4, which
3113 * is in force while we are in guest mode. Do not let guests control
3114 * this bit, even if host CR4.MCE == 0.
3116 unsigned long hw_cr4;
3118 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3119 if (is_unrestricted_guest(vcpu))
3120 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3121 else if (vmx->rmode.vm86_active)
3122 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3124 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3126 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3127 if (cr4 & X86_CR4_UMIP) {
3128 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3129 hw_cr4 &= ~X86_CR4_UMIP;
3130 } else if (!is_guest_mode(vcpu) ||
3131 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3132 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3136 if (cr4 & X86_CR4_VMXE) {
3138 * To use VMXON (and later other VMX instructions), a guest
3139 * must first be able to turn on cr4.VMXE (see handle_vmon()).
3140 * So basically the check on whether to allow nested VMX
3141 * is here. We operate under the default treatment of SMM,
3142 * so VMX cannot be enabled under SMM.
3144 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
3148 if (vmx->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3151 vcpu->arch.cr4 = cr4;
3152 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3154 if (!is_unrestricted_guest(vcpu)) {
3156 if (!is_paging(vcpu)) {
3157 hw_cr4 &= ~X86_CR4_PAE;
3158 hw_cr4 |= X86_CR4_PSE;
3159 } else if (!(cr4 & X86_CR4_PAE)) {
3160 hw_cr4 &= ~X86_CR4_PAE;
3165 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3166 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3167 * to be manually disabled when guest switches to non-paging
3170 * If !enable_unrestricted_guest, the CPU is always running
3171 * with CR0.PG=1 and CR4 needs to be modified.
3172 * If enable_unrestricted_guest, the CPU automatically
3173 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3175 if (!is_paging(vcpu))
3176 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3179 vmcs_writel(CR4_READ_SHADOW, cr4);
3180 vmcs_writel(GUEST_CR4, hw_cr4);
3184 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3186 struct vcpu_vmx *vmx = to_vmx(vcpu);
3189 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3190 *var = vmx->rmode.segs[seg];
3191 if (seg == VCPU_SREG_TR
3192 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3194 var->base = vmx_read_guest_seg_base(vmx, seg);
3195 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3198 var->base = vmx_read_guest_seg_base(vmx, seg);
3199 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3200 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3201 ar = vmx_read_guest_seg_ar(vmx, seg);
3202 var->unusable = (ar >> 16) & 1;
3203 var->type = ar & 15;
3204 var->s = (ar >> 4) & 1;
3205 var->dpl = (ar >> 5) & 3;
3207 * Some userspaces do not preserve unusable property. Since usable
3208 * segment has to be present according to VMX spec we can use present
3209 * property to amend userspace bug by making unusable segment always
3210 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3211 * segment as unusable.
3213 var->present = !var->unusable;
3214 var->avl = (ar >> 12) & 1;
3215 var->l = (ar >> 13) & 1;
3216 var->db = (ar >> 14) & 1;
3217 var->g = (ar >> 15) & 1;
3220 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3222 struct kvm_segment s;
3224 if (to_vmx(vcpu)->rmode.vm86_active) {
3225 vmx_get_segment(vcpu, &s, seg);
3228 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3231 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3233 struct vcpu_vmx *vmx = to_vmx(vcpu);
3235 if (unlikely(vmx->rmode.vm86_active))
3238 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3239 return VMX_AR_DPL(ar);
3243 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3247 if (var->unusable || !var->present)
3250 ar = var->type & 15;
3251 ar |= (var->s & 1) << 4;
3252 ar |= (var->dpl & 3) << 5;
3253 ar |= (var->present & 1) << 7;
3254 ar |= (var->avl & 1) << 12;
3255 ar |= (var->l & 1) << 13;
3256 ar |= (var->db & 1) << 14;
3257 ar |= (var->g & 1) << 15;
3263 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3265 struct vcpu_vmx *vmx = to_vmx(vcpu);
3266 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3268 vmx_segment_cache_clear(vmx);
3270 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3271 vmx->rmode.segs[seg] = *var;
3272 if (seg == VCPU_SREG_TR)
3273 vmcs_write16(sf->selector, var->selector);
3275 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3279 vmcs_writel(sf->base, var->base);
3280 vmcs_write32(sf->limit, var->limit);
3281 vmcs_write16(sf->selector, var->selector);
3284 * Fix the "Accessed" bit in AR field of segment registers for older
3286 * IA32 arch specifies that at the time of processor reset the
3287 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3288 * is setting it to 0 in the userland code. This causes invalid guest
3289 * state vmexit when "unrestricted guest" mode is turned on.
3290 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3291 * tree. Newer qemu binaries with that qemu fix would not need this
3294 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3295 var->type |= 0x1; /* Accessed */
3297 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3300 vmx->emulation_required = emulation_required(vcpu);
3303 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3305 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3307 *db = (ar >> 14) & 1;
3308 *l = (ar >> 13) & 1;
3311 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3313 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3314 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3317 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3319 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3320 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3323 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3325 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3326 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3329 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3331 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3332 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3335 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3337 struct kvm_segment var;
3340 vmx_get_segment(vcpu, &var, seg);
3342 if (seg == VCPU_SREG_CS)
3344 ar = vmx_segment_access_rights(&var);
3346 if (var.base != (var.selector << 4))
3348 if (var.limit != 0xffff)
3356 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3358 struct kvm_segment cs;
3359 unsigned int cs_rpl;
3361 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3362 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3366 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3370 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3371 if (cs.dpl > cs_rpl)
3374 if (cs.dpl != cs_rpl)
3380 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3384 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3386 struct kvm_segment ss;
3387 unsigned int ss_rpl;
3389 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3390 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3394 if (ss.type != 3 && ss.type != 7)
3398 if (ss.dpl != ss_rpl) /* DPL != RPL */
3406 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3408 struct kvm_segment var;
3411 vmx_get_segment(vcpu, &var, seg);
3412 rpl = var.selector & SEGMENT_RPL_MASK;
3420 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3421 if (var.dpl < rpl) /* DPL < RPL */
3425 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3431 static bool tr_valid(struct kvm_vcpu *vcpu)
3433 struct kvm_segment tr;
3435 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3439 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3441 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3449 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3451 struct kvm_segment ldtr;
3453 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3457 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3467 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3469 struct kvm_segment cs, ss;
3471 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3472 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3474 return ((cs.selector & SEGMENT_RPL_MASK) ==
3475 (ss.selector & SEGMENT_RPL_MASK));
3479 * Check if guest state is valid. Returns true if valid, false if
3481 * We assume that registers are always usable
3483 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3485 if (is_unrestricted_guest(vcpu))
3488 /* real mode guest state checks */
3489 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3490 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3492 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3494 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3496 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3498 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3500 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3503 /* protected mode guest state checks */
3504 if (!cs_ss_rpl_check(vcpu))
3506 if (!code_segment_valid(vcpu))
3508 if (!stack_segment_valid(vcpu))
3510 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3512 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3514 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3516 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3518 if (!tr_valid(vcpu))
3520 if (!ldtr_valid(vcpu))
3524 * - Add checks on RIP
3525 * - Add checks on RFLAGS
3531 static int init_rmode_tss(struct kvm *kvm)
3537 idx = srcu_read_lock(&kvm->srcu);
3538 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3539 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3542 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3543 r = kvm_write_guest_page(kvm, fn++, &data,
3544 TSS_IOPB_BASE_OFFSET, sizeof(u16));
3547 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3550 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3554 r = kvm_write_guest_page(kvm, fn, &data,
3555 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3558 srcu_read_unlock(&kvm->srcu, idx);
3562 static int init_rmode_identity_map(struct kvm *kvm)
3564 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3566 kvm_pfn_t identity_map_pfn;
3569 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3570 mutex_lock(&kvm->slots_lock);
3572 if (likely(kvm_vmx->ept_identity_pagetable_done))
3575 if (!kvm_vmx->ept_identity_map_addr)
3576 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3577 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3579 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3580 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3584 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3587 /* Set up identity-mapping pagetable for EPT in real mode */
3588 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3589 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3590 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3591 r = kvm_write_guest_page(kvm, identity_map_pfn,
3592 &tmp, i * sizeof(tmp), sizeof(tmp));
3596 kvm_vmx->ept_identity_pagetable_done = true;
3599 mutex_unlock(&kvm->slots_lock);
3603 static void seg_setup(int seg)
3605 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3608 vmcs_write16(sf->selector, 0);
3609 vmcs_writel(sf->base, 0);
3610 vmcs_write32(sf->limit, 0xffff);
3612 if (seg == VCPU_SREG_CS)
3613 ar |= 0x08; /* code segment */
3615 vmcs_write32(sf->ar_bytes, ar);
3618 static int alloc_apic_access_page(struct kvm *kvm)
3623 mutex_lock(&kvm->slots_lock);
3624 if (kvm->arch.apic_access_page_done)
3626 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3627 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3631 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3632 if (is_error_page(page)) {
3638 * Do not pin the page in memory, so that memory hot-unplug
3639 * is able to migrate it.
3642 kvm->arch.apic_access_page_done = true;
3644 mutex_unlock(&kvm->slots_lock);
3648 int allocate_vpid(void)
3654 spin_lock(&vmx_vpid_lock);
3655 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3656 if (vpid < VMX_NR_VPIDS)
3657 __set_bit(vpid, vmx_vpid_bitmap);
3660 spin_unlock(&vmx_vpid_lock);
3664 void free_vpid(int vpid)
3666 if (!enable_vpid || vpid == 0)
3668 spin_lock(&vmx_vpid_lock);
3669 __clear_bit(vpid, vmx_vpid_bitmap);
3670 spin_unlock(&vmx_vpid_lock);
3673 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3676 int f = sizeof(unsigned long);
3678 if (!cpu_has_vmx_msr_bitmap())
3681 if (static_branch_unlikely(&enable_evmcs))
3682 evmcs_touch_msr_bitmap();
3685 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3686 * have the write-low and read-high bitmap offsets the wrong way round.
3687 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3689 if (msr <= 0x1fff) {
3690 if (type & MSR_TYPE_R)
3692 __clear_bit(msr, msr_bitmap + 0x000 / f);
3694 if (type & MSR_TYPE_W)
3696 __clear_bit(msr, msr_bitmap + 0x800 / f);
3698 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3700 if (type & MSR_TYPE_R)
3702 __clear_bit(msr, msr_bitmap + 0x400 / f);
3704 if (type & MSR_TYPE_W)
3706 __clear_bit(msr, msr_bitmap + 0xc00 / f);
3711 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3714 int f = sizeof(unsigned long);
3716 if (!cpu_has_vmx_msr_bitmap())
3719 if (static_branch_unlikely(&enable_evmcs))
3720 evmcs_touch_msr_bitmap();
3723 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3724 * have the write-low and read-high bitmap offsets the wrong way round.
3725 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3727 if (msr <= 0x1fff) {
3728 if (type & MSR_TYPE_R)
3730 __set_bit(msr, msr_bitmap + 0x000 / f);
3732 if (type & MSR_TYPE_W)
3734 __set_bit(msr, msr_bitmap + 0x800 / f);
3736 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3738 if (type & MSR_TYPE_R)
3740 __set_bit(msr, msr_bitmap + 0x400 / f);
3742 if (type & MSR_TYPE_W)
3744 __set_bit(msr, msr_bitmap + 0xc00 / f);
3749 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3750 u32 msr, int type, bool value)
3753 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3755 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3758 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3762 if (cpu_has_secondary_exec_ctrls() &&
3763 (secondary_exec_controls_get(to_vmx(vcpu)) &
3764 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3765 mode |= MSR_BITMAP_MODE_X2APIC;
3766 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3767 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3773 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3778 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3779 unsigned word = msr / BITS_PER_LONG;
3780 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3781 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3784 if (mode & MSR_BITMAP_MODE_X2APIC) {
3786 * TPR reads and writes can be virtualized even if virtual interrupt
3787 * delivery is not in use.
3789 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3790 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3791 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3792 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3793 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3798 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3800 struct vcpu_vmx *vmx = to_vmx(vcpu);
3801 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3802 u8 mode = vmx_msr_bitmap_mode(vcpu);
3803 u8 changed = mode ^ vmx->msr_bitmap_mode;
3808 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3809 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3811 vmx->msr_bitmap_mode = mode;
3814 void pt_update_intercept_for_msr(struct vcpu_vmx *vmx)
3816 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3817 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3820 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_STATUS,
3822 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_BASE,
3824 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_MASK,
3826 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_CR3_MATCH,
3828 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3829 vmx_set_intercept_for_msr(msr_bitmap,
3830 MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3831 vmx_set_intercept_for_msr(msr_bitmap,
3832 MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3836 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3838 struct vcpu_vmx *vmx = to_vmx(vcpu);
3843 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3844 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3845 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3848 rvi = vmx_get_rvi();
3850 vapic_page = vmx->nested.virtual_apic_map.hva;
3851 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3853 return ((rvi & 0xf0) > (vppr & 0xf0));
3856 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3860 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3862 if (vcpu->mode == IN_GUEST_MODE) {
3864 * The vector of interrupt to be delivered to vcpu had
3865 * been set in PIR before this function.
3867 * Following cases will be reached in this block, and
3868 * we always send a notification event in all cases as
3871 * Case 1: vcpu keeps in non-root mode. Sending a
3872 * notification event posts the interrupt to vcpu.
3874 * Case 2: vcpu exits to root mode and is still
3875 * runnable. PIR will be synced to vIRR before the
3876 * next vcpu entry. Sending a notification event in
3877 * this case has no effect, as vcpu is not in root
3880 * Case 3: vcpu exits to root mode and is blocked.
3881 * vcpu_block() has already synced PIR to vIRR and
3882 * never blocks vcpu if vIRR is not cleared. Therefore,
3883 * a blocked vcpu here does not wait for any requested
3884 * interrupts in PIR, and sending a notification event
3885 * which has no effect is safe here.
3888 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3895 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3898 struct vcpu_vmx *vmx = to_vmx(vcpu);
3900 if (is_guest_mode(vcpu) &&
3901 vector == vmx->nested.posted_intr_nv) {
3903 * If a posted intr is not recognized by hardware,
3904 * we will accomplish it in the next vmentry.
3906 vmx->nested.pi_pending = true;
3907 kvm_make_request(KVM_REQ_EVENT, vcpu);
3908 /* the PIR and ON have been set by L1. */
3909 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3910 kvm_vcpu_kick(vcpu);
3916 * Send interrupt to vcpu via posted interrupt way.
3917 * 1. If target vcpu is running(non-root mode), send posted interrupt
3918 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3919 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3920 * interrupt from PIR in next vmentry.
3922 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3924 struct vcpu_vmx *vmx = to_vmx(vcpu);
3927 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3931 if (!vcpu->arch.apicv_active)
3934 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3937 /* If a previous notification has sent the IPI, nothing to do. */
3938 if (pi_test_and_set_on(&vmx->pi_desc))
3941 if (vcpu != kvm_get_running_vcpu() &&
3942 !kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3943 kvm_vcpu_kick(vcpu);
3949 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3950 * will not change in the lifetime of the guest.
3951 * Note that host-state that does change is set elsewhere. E.g., host-state
3952 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3954 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3958 unsigned long cr0, cr3, cr4;
3961 WARN_ON(cr0 & X86_CR0_TS);
3962 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
3965 * Save the most likely value for this task's CR3 in the VMCS.
3966 * We can't use __get_current_cr3_fast() because we're not atomic.
3969 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
3970 vmx->loaded_vmcs->host_state.cr3 = cr3;
3972 /* Save the most likely value for this task's CR4 in the VMCS. */
3973 cr4 = cr4_read_shadow();
3974 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
3975 vmx->loaded_vmcs->host_state.cr4 = cr4;
3977 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
3978 #ifdef CONFIG_X86_64
3980 * Load null selectors, so we can avoid reloading them in
3981 * vmx_prepare_switch_to_host(), in case userspace uses
3982 * the null selectors too (the expected case).
3984 vmcs_write16(HOST_DS_SELECTOR, 0);
3985 vmcs_write16(HOST_ES_SELECTOR, 0);
3987 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3988 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3990 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3991 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
3993 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
3995 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
3997 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3998 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3999 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4000 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4002 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4003 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4004 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4007 if (cpu_has_load_ia32_efer())
4008 vmcs_write64(HOST_IA32_EFER, host_efer);
4011 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4013 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS;
4015 vmx->vcpu.arch.cr4_guest_owned_bits &= ~X86_CR4_PGE;
4016 if (is_guest_mode(&vmx->vcpu))
4017 vmx->vcpu.arch.cr4_guest_owned_bits &=
4018 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
4019 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
4022 u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4024 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4026 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4027 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4030 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4032 if (!enable_preemption_timer)
4033 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4035 return pin_based_exec_ctrl;
4038 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4040 struct vcpu_vmx *vmx = to_vmx(vcpu);
4042 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4043 if (cpu_has_secondary_exec_ctrls()) {
4044 if (kvm_vcpu_apicv_active(vcpu))
4045 secondary_exec_controls_setbit(vmx,
4046 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4047 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4049 secondary_exec_controls_clearbit(vmx,
4050 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4051 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4054 if (cpu_has_vmx_msr_bitmap())
4055 vmx_update_msr_bitmap(vcpu);
4058 u32 vmx_exec_control(struct vcpu_vmx *vmx)
4060 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4062 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4063 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4065 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4066 exec_control &= ~CPU_BASED_TPR_SHADOW;
4067 #ifdef CONFIG_X86_64
4068 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4069 CPU_BASED_CR8_LOAD_EXITING;
4073 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4074 CPU_BASED_CR3_LOAD_EXITING |
4075 CPU_BASED_INVLPG_EXITING;
4076 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4077 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4078 CPU_BASED_MONITOR_EXITING);
4079 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4080 exec_control &= ~CPU_BASED_HLT_EXITING;
4081 return exec_control;
4085 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
4087 struct kvm_vcpu *vcpu = &vmx->vcpu;
4089 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4091 if (vmx_pt_mode_is_system())
4092 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4093 if (!cpu_need_virtualize_apic_accesses(vcpu))
4094 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4096 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4098 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4099 enable_unrestricted_guest = 0;
4101 if (!enable_unrestricted_guest)
4102 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4103 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4104 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4105 if (!kvm_vcpu_apicv_active(vcpu))
4106 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4107 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4108 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4110 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4111 * in vmx_set_cr4. */
4112 exec_control &= ~SECONDARY_EXEC_DESC;
4114 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4116 We can NOT enable shadow_vmcs here because we don't have yet
4119 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4122 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4124 if (vmx_xsaves_supported()) {
4125 /* Exposing XSAVES only when XSAVE is exposed */
4126 bool xsaves_enabled =
4127 boot_cpu_has(X86_FEATURE_XSAVE) &&
4128 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4129 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4131 vcpu->arch.xsaves_enabled = xsaves_enabled;
4133 if (!xsaves_enabled)
4134 exec_control &= ~SECONDARY_EXEC_XSAVES;
4138 vmx->nested.msrs.secondary_ctls_high |=
4139 SECONDARY_EXEC_XSAVES;
4141 vmx->nested.msrs.secondary_ctls_high &=
4142 ~SECONDARY_EXEC_XSAVES;
4146 if (cpu_has_vmx_rdtscp()) {
4147 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
4148 if (!rdtscp_enabled)
4149 exec_control &= ~SECONDARY_EXEC_RDTSCP;
4153 vmx->nested.msrs.secondary_ctls_high |=
4154 SECONDARY_EXEC_RDTSCP;
4156 vmx->nested.msrs.secondary_ctls_high &=
4157 ~SECONDARY_EXEC_RDTSCP;
4161 if (cpu_has_vmx_invpcid()) {
4162 /* Exposing INVPCID only when PCID is exposed */
4163 bool invpcid_enabled =
4164 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
4165 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
4167 if (!invpcid_enabled) {
4168 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
4169 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
4173 if (invpcid_enabled)
4174 vmx->nested.msrs.secondary_ctls_high |=
4175 SECONDARY_EXEC_ENABLE_INVPCID;
4177 vmx->nested.msrs.secondary_ctls_high &=
4178 ~SECONDARY_EXEC_ENABLE_INVPCID;
4182 if (vmx_rdrand_supported()) {
4183 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
4185 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
4189 vmx->nested.msrs.secondary_ctls_high |=
4190 SECONDARY_EXEC_RDRAND_EXITING;
4192 vmx->nested.msrs.secondary_ctls_high &=
4193 ~SECONDARY_EXEC_RDRAND_EXITING;
4197 if (vmx_rdseed_supported()) {
4198 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
4200 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
4204 vmx->nested.msrs.secondary_ctls_high |=
4205 SECONDARY_EXEC_RDSEED_EXITING;
4207 vmx->nested.msrs.secondary_ctls_high &=
4208 ~SECONDARY_EXEC_RDSEED_EXITING;
4212 if (vmx_waitpkg_supported()) {
4213 bool waitpkg_enabled =
4214 guest_cpuid_has(vcpu, X86_FEATURE_WAITPKG);
4216 if (!waitpkg_enabled)
4217 exec_control &= ~SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4220 if (waitpkg_enabled)
4221 vmx->nested.msrs.secondary_ctls_high |=
4222 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4224 vmx->nested.msrs.secondary_ctls_high &=
4225 ~SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4229 vmx->secondary_exec_control = exec_control;
4232 static void ept_set_mmio_spte_mask(void)
4235 * EPT Misconfigurations can be generated if the value of bits 2:0
4236 * of an EPT paging-structure entry is 110b (write/execute).
4238 kvm_mmu_set_mmio_spte_mask(VMX_EPT_MISCONFIG_WX_VALUE, 0);
4241 #define VMX_XSS_EXIT_BITMAP 0
4244 * Noting that the initialization of Guest-state Area of VMCS is in
4247 static void init_vmcs(struct vcpu_vmx *vmx)
4250 nested_vmx_set_vmcs_shadowing_bitmap();
4252 if (cpu_has_vmx_msr_bitmap())
4253 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4255 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4258 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4260 exec_controls_set(vmx, vmx_exec_control(vmx));
4262 if (cpu_has_secondary_exec_ctrls()) {
4263 vmx_compute_secondary_exec_control(vmx);
4264 secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
4267 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4268 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4269 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4270 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4271 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4273 vmcs_write16(GUEST_INTR_STATUS, 0);
4275 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4276 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4279 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4280 vmcs_write32(PLE_GAP, ple_gap);
4281 vmx->ple_window = ple_window;
4282 vmx->ple_window_dirty = true;
4285 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4286 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4287 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4289 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4290 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4291 vmx_set_constant_host_state(vmx);
4292 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4293 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4295 if (cpu_has_vmx_vmfunc())
4296 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4298 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4299 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4300 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4301 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4302 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4304 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4305 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4307 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4309 /* 22.2.1, 20.8.1 */
4310 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4312 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4313 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4315 set_cr4_guest_host_mask(vmx);
4318 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4320 if (vmx_xsaves_supported())
4321 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4324 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4325 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4328 if (cpu_has_vmx_encls_vmexit())
4329 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
4331 if (vmx_pt_mode_is_host_guest()) {
4332 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4333 /* Bit[6~0] are forced to 1, writes are ignored. */
4334 vmx->pt_desc.guest.output_mask = 0x7F;
4335 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4339 * If EPT is enabled, #PF is only trapped if MAXPHYADDR is mismatched
4340 * between guest and host. In that case we only care about present
4344 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, PFERR_PRESENT_MASK);
4345 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, PFERR_PRESENT_MASK);
4349 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4351 struct vcpu_vmx *vmx = to_vmx(vcpu);
4352 struct msr_data apic_base_msr;
4355 vmx->rmode.vm86_active = 0;
4358 vmx->msr_ia32_umwait_control = 0;
4360 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4361 vmx->hv_deadline_tsc = -1;
4362 kvm_set_cr8(vcpu, 0);
4365 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4366 MSR_IA32_APICBASE_ENABLE;
4367 if (kvm_vcpu_is_reset_bsp(vcpu))
4368 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4369 apic_base_msr.host_initiated = true;
4370 kvm_set_apic_base(vcpu, &apic_base_msr);
4373 vmx_segment_cache_clear(vmx);
4375 seg_setup(VCPU_SREG_CS);
4376 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4377 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4379 seg_setup(VCPU_SREG_DS);
4380 seg_setup(VCPU_SREG_ES);
4381 seg_setup(VCPU_SREG_FS);
4382 seg_setup(VCPU_SREG_GS);
4383 seg_setup(VCPU_SREG_SS);
4385 vmcs_write16(GUEST_TR_SELECTOR, 0);
4386 vmcs_writel(GUEST_TR_BASE, 0);
4387 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4388 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4390 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4391 vmcs_writel(GUEST_LDTR_BASE, 0);
4392 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4393 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4396 vmcs_write32(GUEST_SYSENTER_CS, 0);
4397 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4398 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4399 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4402 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4403 kvm_rip_write(vcpu, 0xfff0);
4405 vmcs_writel(GUEST_GDTR_BASE, 0);
4406 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4408 vmcs_writel(GUEST_IDTR_BASE, 0);
4409 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4411 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4412 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4413 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4414 if (kvm_mpx_supported())
4415 vmcs_write64(GUEST_BNDCFGS, 0);
4419 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4421 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4422 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4423 if (cpu_need_tpr_shadow(vcpu))
4424 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4425 __pa(vcpu->arch.apic->regs));
4426 vmcs_write32(TPR_THRESHOLD, 0);
4429 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4431 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4432 vmx->vcpu.arch.cr0 = cr0;
4433 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4434 vmx_set_cr4(vcpu, 0);
4435 vmx_set_efer(vcpu, 0);
4437 update_exception_bitmap(vcpu);
4439 vpid_sync_context(vmx->vpid);
4441 vmx_clear_hlt(vcpu);
4444 static void enable_irq_window(struct kvm_vcpu *vcpu)
4446 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4449 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4452 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4453 enable_irq_window(vcpu);
4457 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4460 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4462 struct vcpu_vmx *vmx = to_vmx(vcpu);
4464 int irq = vcpu->arch.interrupt.nr;
4466 trace_kvm_inj_virq(irq);
4468 ++vcpu->stat.irq_injections;
4469 if (vmx->rmode.vm86_active) {
4471 if (vcpu->arch.interrupt.soft)
4472 inc_eip = vcpu->arch.event_exit_inst_len;
4473 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4476 intr = irq | INTR_INFO_VALID_MASK;
4477 if (vcpu->arch.interrupt.soft) {
4478 intr |= INTR_TYPE_SOFT_INTR;
4479 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4480 vmx->vcpu.arch.event_exit_inst_len);
4482 intr |= INTR_TYPE_EXT_INTR;
4483 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4485 vmx_clear_hlt(vcpu);
4488 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4490 struct vcpu_vmx *vmx = to_vmx(vcpu);
4494 * Tracking the NMI-blocked state in software is built upon
4495 * finding the next open IRQ window. This, in turn, depends on
4496 * well-behaving guests: They have to keep IRQs disabled at
4497 * least as long as the NMI handler runs. Otherwise we may
4498 * cause NMI nesting, maybe breaking the guest. But as this is
4499 * highly unlikely, we can live with the residual risk.
4501 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4502 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4505 ++vcpu->stat.nmi_injections;
4506 vmx->loaded_vmcs->nmi_known_unmasked = false;
4508 if (vmx->rmode.vm86_active) {
4509 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4513 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4514 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4516 vmx_clear_hlt(vcpu);
4519 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4521 struct vcpu_vmx *vmx = to_vmx(vcpu);
4525 return vmx->loaded_vmcs->soft_vnmi_blocked;
4526 if (vmx->loaded_vmcs->nmi_known_unmasked)
4528 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4529 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4533 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4535 struct vcpu_vmx *vmx = to_vmx(vcpu);
4538 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4539 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4540 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4543 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4545 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4546 GUEST_INTR_STATE_NMI);
4548 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4549 GUEST_INTR_STATE_NMI);
4553 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4555 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4558 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4561 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4562 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4563 GUEST_INTR_STATE_NMI));
4566 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4568 if (to_vmx(vcpu)->nested.nested_run_pending)
4571 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4572 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4575 return !vmx_nmi_blocked(vcpu);
4578 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4580 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4583 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4584 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4585 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4588 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4590 if (to_vmx(vcpu)->nested.nested_run_pending)
4594 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4595 * e.g. if the IRQ arrived asynchronously after checking nested events.
4597 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4600 return !vmx_interrupt_blocked(vcpu);
4603 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4607 if (enable_unrestricted_guest)
4610 mutex_lock(&kvm->slots_lock);
4611 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4613 mutex_unlock(&kvm->slots_lock);
4617 to_kvm_vmx(kvm)->tss_addr = addr;
4618 return init_rmode_tss(kvm);
4621 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4623 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4627 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4632 * Update instruction length as we may reinject the exception
4633 * from user space while in guest debugging mode.
4635 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4636 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4637 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4641 return !(vcpu->guest_debug &
4642 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4656 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4657 int vec, u32 err_code)
4660 * Instruction with address size override prefix opcode 0x67
4661 * Cause the #SS fault with 0 error code in VM86 mode.
4663 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4664 if (kvm_emulate_instruction(vcpu, 0)) {
4665 if (vcpu->arch.halt_request) {
4666 vcpu->arch.halt_request = 0;
4667 return kvm_vcpu_halt(vcpu);
4675 * Forward all other exceptions that are valid in real mode.
4676 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4677 * the required debugging infrastructure rework.
4679 kvm_queue_exception(vcpu, vec);
4684 * Trigger machine check on the host. We assume all the MSRs are already set up
4685 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4686 * We pass a fake environment to the machine check handler because we want
4687 * the guest to be always treated like user space, no matter what context
4688 * it used internally.
4690 static void kvm_machine_check(void)
4692 #if defined(CONFIG_X86_MCE)
4693 struct pt_regs regs = {
4694 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4695 .flags = X86_EFLAGS_IF,
4698 do_machine_check(®s);
4702 static int handle_machine_check(struct kvm_vcpu *vcpu)
4704 /* handled by vmx_vcpu_run() */
4709 * If the host has split lock detection disabled, then #AC is
4710 * unconditionally injected into the guest, which is the pre split lock
4711 * detection behaviour.
4713 * If the host has split lock detection enabled then #AC is
4714 * only injected into the guest when:
4715 * - Guest CPL == 3 (user mode)
4716 * - Guest has #AC detection enabled in CR0
4717 * - Guest EFLAGS has AC bit set
4719 static inline bool guest_inject_ac(struct kvm_vcpu *vcpu)
4721 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4724 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4725 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4728 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4730 struct vcpu_vmx *vmx = to_vmx(vcpu);
4731 struct kvm_run *kvm_run = vcpu->run;
4732 u32 intr_info, ex_no, error_code;
4733 unsigned long cr2, rip, dr6;
4736 vect_info = vmx->idt_vectoring_info;
4737 intr_info = vmx_get_intr_info(vcpu);
4739 if (is_machine_check(intr_info) || is_nmi(intr_info))
4740 return 1; /* handled by handle_exception_nmi_irqoff() */
4742 if (is_invalid_opcode(intr_info))
4743 return handle_ud(vcpu);
4746 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4747 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4749 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4750 WARN_ON_ONCE(!enable_vmware_backdoor);
4753 * VMware backdoor emulation on #GP interception only handles
4754 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4755 * error code on #GP.
4758 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4761 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4765 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4766 * MMIO, it is better to report an internal error.
4767 * See the comments in vmx_handle_exit.
4769 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4770 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4771 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4772 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4773 vcpu->run->internal.ndata = 4;
4774 vcpu->run->internal.data[0] = vect_info;
4775 vcpu->run->internal.data[1] = intr_info;
4776 vcpu->run->internal.data[2] = error_code;
4777 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
4781 if (is_page_fault(intr_info)) {
4782 cr2 = vmx_get_exit_qual(vcpu);
4783 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
4785 * EPT will cause page fault only if we need to
4786 * detect illegal GPAs.
4788 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
4791 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4794 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4796 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4797 return handle_rmode_exception(vcpu, ex_no, error_code);
4801 dr6 = vmx_get_exit_qual(vcpu);
4802 if (!(vcpu->guest_debug &
4803 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4804 if (is_icebp(intr_info))
4805 WARN_ON(!skip_emulated_instruction(vcpu));
4807 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
4810 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
4811 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4815 * Update instruction length as we may reinject #BP from
4816 * user space while in guest debugging mode. Reading it for
4817 * #DB as well causes no harm, it is not used in that case.
4819 vmx->vcpu.arch.event_exit_inst_len =
4820 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4821 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4822 rip = kvm_rip_read(vcpu);
4823 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4824 kvm_run->debug.arch.exception = ex_no;
4827 if (guest_inject_ac(vcpu)) {
4828 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4833 * Handle split lock. Depending on detection mode this will
4834 * either warn and disable split lock detection for this
4835 * task or force SIGBUS on it.
4837 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4841 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4842 kvm_run->ex.exception = ex_no;
4843 kvm_run->ex.error_code = error_code;
4849 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4851 ++vcpu->stat.irq_exits;
4855 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4857 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4858 vcpu->mmio_needed = 0;
4862 static int handle_io(struct kvm_vcpu *vcpu)
4864 unsigned long exit_qualification;
4865 int size, in, string;
4868 exit_qualification = vmx_get_exit_qual(vcpu);
4869 string = (exit_qualification & 16) != 0;
4871 ++vcpu->stat.io_exits;
4874 return kvm_emulate_instruction(vcpu, 0);
4876 port = exit_qualification >> 16;
4877 size = (exit_qualification & 7) + 1;
4878 in = (exit_qualification & 8) != 0;
4880 return kvm_fast_pio(vcpu, size, port, in);
4884 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4887 * Patch in the VMCALL instruction:
4889 hypercall[0] = 0x0f;
4890 hypercall[1] = 0x01;
4891 hypercall[2] = 0xc1;
4894 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4895 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4897 if (is_guest_mode(vcpu)) {
4898 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4899 unsigned long orig_val = val;
4902 * We get here when L2 changed cr0 in a way that did not change
4903 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4904 * but did change L0 shadowed bits. So we first calculate the
4905 * effective cr0 value that L1 would like to write into the
4906 * hardware. It consists of the L2-owned bits from the new
4907 * value combined with the L1-owned bits from L1's guest_cr0.
4909 val = (val & ~vmcs12->cr0_guest_host_mask) |
4910 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4912 if (!nested_guest_cr0_valid(vcpu, val))
4915 if (kvm_set_cr0(vcpu, val))
4917 vmcs_writel(CR0_READ_SHADOW, orig_val);
4920 if (to_vmx(vcpu)->nested.vmxon &&
4921 !nested_host_cr0_valid(vcpu, val))
4924 return kvm_set_cr0(vcpu, val);
4928 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4930 if (is_guest_mode(vcpu)) {
4931 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4932 unsigned long orig_val = val;
4934 /* analogously to handle_set_cr0 */
4935 val = (val & ~vmcs12->cr4_guest_host_mask) |
4936 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4937 if (kvm_set_cr4(vcpu, val))
4939 vmcs_writel(CR4_READ_SHADOW, orig_val);
4942 return kvm_set_cr4(vcpu, val);
4945 static int handle_desc(struct kvm_vcpu *vcpu)
4947 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4948 return kvm_emulate_instruction(vcpu, 0);
4951 static int handle_cr(struct kvm_vcpu *vcpu)
4953 unsigned long exit_qualification, val;
4959 exit_qualification = vmx_get_exit_qual(vcpu);
4960 cr = exit_qualification & 15;
4961 reg = (exit_qualification >> 8) & 15;
4962 switch ((exit_qualification >> 4) & 3) {
4963 case 0: /* mov to cr */
4964 val = kvm_register_readl(vcpu, reg);
4965 trace_kvm_cr_write(cr, val);
4968 err = handle_set_cr0(vcpu, val);
4969 return kvm_complete_insn_gp(vcpu, err);
4971 WARN_ON_ONCE(enable_unrestricted_guest);
4972 err = kvm_set_cr3(vcpu, val);
4973 return kvm_complete_insn_gp(vcpu, err);
4975 err = handle_set_cr4(vcpu, val);
4976 return kvm_complete_insn_gp(vcpu, err);
4978 u8 cr8_prev = kvm_get_cr8(vcpu);
4980 err = kvm_set_cr8(vcpu, cr8);
4981 ret = kvm_complete_insn_gp(vcpu, err);
4982 if (lapic_in_kernel(vcpu))
4984 if (cr8_prev <= cr8)
4987 * TODO: we might be squashing a
4988 * KVM_GUESTDBG_SINGLESTEP-triggered
4989 * KVM_EXIT_DEBUG here.
4991 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4997 WARN_ONCE(1, "Guest should always own CR0.TS");
4998 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4999 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5000 return kvm_skip_emulated_instruction(vcpu);
5001 case 1: /*mov from cr*/
5004 WARN_ON_ONCE(enable_unrestricted_guest);
5005 val = kvm_read_cr3(vcpu);
5006 kvm_register_write(vcpu, reg, val);
5007 trace_kvm_cr_read(cr, val);
5008 return kvm_skip_emulated_instruction(vcpu);
5010 val = kvm_get_cr8(vcpu);
5011 kvm_register_write(vcpu, reg, val);
5012 trace_kvm_cr_read(cr, val);
5013 return kvm_skip_emulated_instruction(vcpu);
5017 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5018 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5019 kvm_lmsw(vcpu, val);
5021 return kvm_skip_emulated_instruction(vcpu);
5025 vcpu->run->exit_reason = 0;
5026 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5027 (int)(exit_qualification >> 4) & 3, cr);
5031 static int handle_dr(struct kvm_vcpu *vcpu)
5033 unsigned long exit_qualification;
5036 exit_qualification = vmx_get_exit_qual(vcpu);
5037 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5039 /* First, if DR does not exist, trigger UD */
5040 if (!kvm_require_dr(vcpu, dr))
5043 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
5044 if (!kvm_require_cpl(vcpu, 0))
5046 dr7 = vmcs_readl(GUEST_DR7);
5049 * As the vm-exit takes precedence over the debug trap, we
5050 * need to emulate the latter, either for the host or the
5051 * guest debugging itself.
5053 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5054 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_RTM | DR6_FIXED_1;
5055 vcpu->run->debug.arch.dr7 = dr7;
5056 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5057 vcpu->run->debug.arch.exception = DB_VECTOR;
5058 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5061 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5066 if (vcpu->guest_debug == 0) {
5067 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5070 * No more DR vmexits; force a reload of the debug registers
5071 * and reenter on this instruction. The next vmexit will
5072 * retrieve the full state of the debug registers.
5074 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5078 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5079 if (exit_qualification & TYPE_MOV_FROM_DR) {
5082 if (kvm_get_dr(vcpu, dr, &val))
5084 kvm_register_write(vcpu, reg, val);
5086 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
5089 return kvm_skip_emulated_instruction(vcpu);
5092 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5094 get_debugreg(vcpu->arch.db[0], 0);
5095 get_debugreg(vcpu->arch.db[1], 1);
5096 get_debugreg(vcpu->arch.db[2], 2);
5097 get_debugreg(vcpu->arch.db[3], 3);
5098 get_debugreg(vcpu->arch.dr6, 6);
5099 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5101 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5102 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5105 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5107 vmcs_writel(GUEST_DR7, val);
5110 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5112 kvm_apic_update_ppr(vcpu);
5116 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5118 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5120 kvm_make_request(KVM_REQ_EVENT, vcpu);
5122 ++vcpu->stat.irq_window_exits;
5126 static int handle_vmcall(struct kvm_vcpu *vcpu)
5128 return kvm_emulate_hypercall(vcpu);
5131 static int handle_invd(struct kvm_vcpu *vcpu)
5133 /* Treat an INVD instruction as a NOP and just skip it. */
5134 return kvm_skip_emulated_instruction(vcpu);
5137 static int handle_invlpg(struct kvm_vcpu *vcpu)
5139 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5141 kvm_mmu_invlpg(vcpu, exit_qualification);
5142 return kvm_skip_emulated_instruction(vcpu);
5145 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5149 err = kvm_rdpmc(vcpu);
5150 return kvm_complete_insn_gp(vcpu, err);
5153 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5155 return kvm_emulate_wbinvd(vcpu);
5158 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5160 u64 new_bv = kvm_read_edx_eax(vcpu);
5161 u32 index = kvm_rcx_read(vcpu);
5163 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5164 return kvm_skip_emulated_instruction(vcpu);
5168 static int handle_apic_access(struct kvm_vcpu *vcpu)
5170 if (likely(fasteoi)) {
5171 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5172 int access_type, offset;
5174 access_type = exit_qualification & APIC_ACCESS_TYPE;
5175 offset = exit_qualification & APIC_ACCESS_OFFSET;
5177 * Sane guest uses MOV to write EOI, with written value
5178 * not cared. So make a short-circuit here by avoiding
5179 * heavy instruction emulation.
5181 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5182 (offset == APIC_EOI)) {
5183 kvm_lapic_set_eoi(vcpu);
5184 return kvm_skip_emulated_instruction(vcpu);
5187 return kvm_emulate_instruction(vcpu, 0);
5190 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5192 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5193 int vector = exit_qualification & 0xff;
5195 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5196 kvm_apic_set_eoi_accelerated(vcpu, vector);
5200 static int handle_apic_write(struct kvm_vcpu *vcpu)
5202 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5203 u32 offset = exit_qualification & 0xfff;
5205 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5206 kvm_apic_write_nodecode(vcpu, offset);
5210 static int handle_task_switch(struct kvm_vcpu *vcpu)
5212 struct vcpu_vmx *vmx = to_vmx(vcpu);
5213 unsigned long exit_qualification;
5214 bool has_error_code = false;
5217 int reason, type, idt_v, idt_index;
5219 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5220 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5221 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5223 exit_qualification = vmx_get_exit_qual(vcpu);
5225 reason = (u32)exit_qualification >> 30;
5226 if (reason == TASK_SWITCH_GATE && idt_v) {
5228 case INTR_TYPE_NMI_INTR:
5229 vcpu->arch.nmi_injected = false;
5230 vmx_set_nmi_mask(vcpu, true);
5232 case INTR_TYPE_EXT_INTR:
5233 case INTR_TYPE_SOFT_INTR:
5234 kvm_clear_interrupt_queue(vcpu);
5236 case INTR_TYPE_HARD_EXCEPTION:
5237 if (vmx->idt_vectoring_info &
5238 VECTORING_INFO_DELIVER_CODE_MASK) {
5239 has_error_code = true;
5241 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5244 case INTR_TYPE_SOFT_EXCEPTION:
5245 kvm_clear_exception_queue(vcpu);
5251 tss_selector = exit_qualification;
5253 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5254 type != INTR_TYPE_EXT_INTR &&
5255 type != INTR_TYPE_NMI_INTR))
5256 WARN_ON(!skip_emulated_instruction(vcpu));
5259 * TODO: What about debug traps on tss switch?
5260 * Are we supposed to inject them and update dr6?
5262 return kvm_task_switch(vcpu, tss_selector,
5263 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5264 reason, has_error_code, error_code);
5267 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5269 unsigned long exit_qualification;
5273 exit_qualification = vmx_get_exit_qual(vcpu);
5276 * EPT violation happened while executing iret from NMI,
5277 * "blocked by NMI" bit has to be set before next VM entry.
5278 * There are errata that may cause this bit to not be set:
5281 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5283 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5284 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5286 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5287 trace_kvm_page_fault(gpa, exit_qualification);
5289 /* Is it a read fault? */
5290 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5291 ? PFERR_USER_MASK : 0;
5292 /* Is it a write fault? */
5293 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5294 ? PFERR_WRITE_MASK : 0;
5295 /* Is it a fetch fault? */
5296 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5297 ? PFERR_FETCH_MASK : 0;
5298 /* ept page table entry is present? */
5299 error_code |= (exit_qualification &
5300 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5301 EPT_VIOLATION_EXECUTABLE))
5302 ? PFERR_PRESENT_MASK : 0;
5304 error_code |= (exit_qualification & 0x100) != 0 ?
5305 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5307 vcpu->arch.exit_qualification = exit_qualification;
5310 * Check that the GPA doesn't exceed physical memory limits, as that is
5311 * a guest page fault. We have to emulate the instruction here, because
5312 * if the illegal address is that of a paging structure, then
5313 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5314 * would also use advanced VM-exit information for EPT violations to
5315 * reconstruct the page fault error code.
5317 if (unlikely(kvm_mmu_is_illegal_gpa(vcpu, gpa)))
5318 return kvm_emulate_instruction(vcpu, 0);
5320 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5323 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5328 * A nested guest cannot optimize MMIO vmexits, because we have an
5329 * nGPA here instead of the required GPA.
5331 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5332 if (!is_guest_mode(vcpu) &&
5333 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5334 trace_kvm_fast_mmio(gpa);
5335 return kvm_skip_emulated_instruction(vcpu);
5338 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5341 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5343 WARN_ON_ONCE(!enable_vnmi);
5344 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5345 ++vcpu->stat.nmi_window_exits;
5346 kvm_make_request(KVM_REQ_EVENT, vcpu);
5351 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5353 struct vcpu_vmx *vmx = to_vmx(vcpu);
5354 bool intr_window_requested;
5355 unsigned count = 130;
5357 intr_window_requested = exec_controls_get(vmx) &
5358 CPU_BASED_INTR_WINDOW_EXITING;
5360 while (vmx->emulation_required && count-- != 0) {
5361 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5362 return handle_interrupt_window(&vmx->vcpu);
5364 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5367 if (!kvm_emulate_instruction(vcpu, 0))
5370 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5371 vcpu->arch.exception.pending) {
5372 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5373 vcpu->run->internal.suberror =
5374 KVM_INTERNAL_ERROR_EMULATION;
5375 vcpu->run->internal.ndata = 0;
5379 if (vcpu->arch.halt_request) {
5380 vcpu->arch.halt_request = 0;
5381 return kvm_vcpu_halt(vcpu);
5385 * Note, return 1 and not 0, vcpu_run() will invoke
5386 * xfer_to_guest_mode() which will create a proper return
5389 if (__xfer_to_guest_mode_work_pending())
5396 static void grow_ple_window(struct kvm_vcpu *vcpu)
5398 struct vcpu_vmx *vmx = to_vmx(vcpu);
5399 unsigned int old = vmx->ple_window;
5401 vmx->ple_window = __grow_ple_window(old, ple_window,
5405 if (vmx->ple_window != old) {
5406 vmx->ple_window_dirty = true;
5407 trace_kvm_ple_window_update(vcpu->vcpu_id,
5408 vmx->ple_window, old);
5412 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5414 struct vcpu_vmx *vmx = to_vmx(vcpu);
5415 unsigned int old = vmx->ple_window;
5417 vmx->ple_window = __shrink_ple_window(old, ple_window,
5421 if (vmx->ple_window != old) {
5422 vmx->ple_window_dirty = true;
5423 trace_kvm_ple_window_update(vcpu->vcpu_id,
5424 vmx->ple_window, old);
5429 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5431 static void wakeup_handler(void)
5433 struct kvm_vcpu *vcpu;
5434 int cpu = smp_processor_id();
5436 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5437 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5438 blocked_vcpu_list) {
5439 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5441 if (pi_test_on(pi_desc) == 1)
5442 kvm_vcpu_kick(vcpu);
5444 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5447 static void vmx_enable_tdp(void)
5449 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5450 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5451 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5452 0ull, VMX_EPT_EXECUTABLE_MASK,
5453 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5454 VMX_EPT_RWX_MASK, 0ull);
5456 ept_set_mmio_spte_mask();
5460 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5461 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5463 static int handle_pause(struct kvm_vcpu *vcpu)
5465 if (!kvm_pause_in_guest(vcpu->kvm))
5466 grow_ple_window(vcpu);
5469 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5470 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5471 * never set PAUSE_EXITING and just set PLE if supported,
5472 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5474 kvm_vcpu_on_spin(vcpu, true);
5475 return kvm_skip_emulated_instruction(vcpu);
5478 static int handle_nop(struct kvm_vcpu *vcpu)
5480 return kvm_skip_emulated_instruction(vcpu);
5483 static int handle_mwait(struct kvm_vcpu *vcpu)
5485 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5486 return handle_nop(vcpu);
5489 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5491 kvm_queue_exception(vcpu, UD_VECTOR);
5495 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5500 static int handle_monitor(struct kvm_vcpu *vcpu)
5502 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5503 return handle_nop(vcpu);
5506 static int handle_invpcid(struct kvm_vcpu *vcpu)
5508 u32 vmx_instruction_info;
5516 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5517 kvm_queue_exception(vcpu, UD_VECTOR);
5521 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5522 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5525 kvm_inject_gp(vcpu, 0);
5529 /* According to the Intel instruction reference, the memory operand
5530 * is read even if it isn't needed (e.g., for type==all)
5532 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5533 vmx_instruction_info, false,
5534 sizeof(operand), &gva))
5537 return kvm_handle_invpcid(vcpu, type, gva);
5540 static int handle_pml_full(struct kvm_vcpu *vcpu)
5542 unsigned long exit_qualification;
5544 trace_kvm_pml_full(vcpu->vcpu_id);
5546 exit_qualification = vmx_get_exit_qual(vcpu);
5549 * PML buffer FULL happened while executing iret from NMI,
5550 * "blocked by NMI" bit has to be set before next VM entry.
5552 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5554 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5555 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5556 GUEST_INTR_STATE_NMI);
5559 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5560 * here.., and there's no userspace involvement needed for PML.
5565 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5567 struct vcpu_vmx *vmx = to_vmx(vcpu);
5569 if (!vmx->req_immediate_exit &&
5570 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5571 kvm_lapic_expired_hv_timer(vcpu);
5572 return EXIT_FASTPATH_REENTER_GUEST;
5575 return EXIT_FASTPATH_NONE;
5578 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5580 handle_fastpath_preemption_timer(vcpu);
5585 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5586 * are overwritten by nested_vmx_setup() when nested=1.
5588 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5590 kvm_queue_exception(vcpu, UD_VECTOR);
5594 static int handle_encls(struct kvm_vcpu *vcpu)
5597 * SGX virtualization is not yet supported. There is no software
5598 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5599 * to prevent the guest from executing ENCLS.
5601 kvm_queue_exception(vcpu, UD_VECTOR);
5606 * The exit handlers return 1 if the exit was handled fully and guest execution
5607 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5608 * to be done to userspace and return 0.
5610 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5611 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5612 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5613 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5614 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5615 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5616 [EXIT_REASON_CR_ACCESS] = handle_cr,
5617 [EXIT_REASON_DR_ACCESS] = handle_dr,
5618 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5619 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5620 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
5621 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
5622 [EXIT_REASON_HLT] = kvm_emulate_halt,
5623 [EXIT_REASON_INVD] = handle_invd,
5624 [EXIT_REASON_INVLPG] = handle_invlpg,
5625 [EXIT_REASON_RDPMC] = handle_rdpmc,
5626 [EXIT_REASON_VMCALL] = handle_vmcall,
5627 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5628 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5629 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5630 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5631 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5632 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5633 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5634 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5635 [EXIT_REASON_VMON] = handle_vmx_instruction,
5636 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5637 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5638 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5639 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5640 [EXIT_REASON_WBINVD] = handle_wbinvd,
5641 [EXIT_REASON_XSETBV] = handle_xsetbv,
5642 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5643 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5644 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5645 [EXIT_REASON_LDTR_TR] = handle_desc,
5646 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5647 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5648 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5649 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5650 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5651 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5652 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5653 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5654 [EXIT_REASON_RDRAND] = handle_invalid_op,
5655 [EXIT_REASON_RDSEED] = handle_invalid_op,
5656 [EXIT_REASON_PML_FULL] = handle_pml_full,
5657 [EXIT_REASON_INVPCID] = handle_invpcid,
5658 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5659 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5660 [EXIT_REASON_ENCLS] = handle_encls,
5663 static const int kvm_vmx_max_exit_handlers =
5664 ARRAY_SIZE(kvm_vmx_exit_handlers);
5666 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5668 *info1 = vmx_get_exit_qual(vcpu);
5669 *info2 = vmx_get_intr_info(vcpu);
5672 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5675 __free_page(vmx->pml_pg);
5680 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5682 struct vcpu_vmx *vmx = to_vmx(vcpu);
5686 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5688 /* Do nothing if PML buffer is empty */
5689 if (pml_idx == (PML_ENTITY_NUM - 1))
5692 /* PML index always points to next available PML buffer entity */
5693 if (pml_idx >= PML_ENTITY_NUM)
5698 pml_buf = page_address(vmx->pml_pg);
5699 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5702 gpa = pml_buf[pml_idx];
5703 WARN_ON(gpa & (PAGE_SIZE - 1));
5704 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5707 /* reset PML index */
5708 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5712 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5713 * Called before reporting dirty_bitmap to userspace.
5715 static void kvm_flush_pml_buffers(struct kvm *kvm)
5718 struct kvm_vcpu *vcpu;
5720 * We only need to kick vcpu out of guest mode here, as PML buffer
5721 * is flushed at beginning of all VMEXITs, and it's obvious that only
5722 * vcpus running in guest are possible to have unflushed GPAs in PML
5725 kvm_for_each_vcpu(i, vcpu, kvm)
5726 kvm_vcpu_kick(vcpu);
5729 static void vmx_dump_sel(char *name, uint32_t sel)
5731 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5732 name, vmcs_read16(sel),
5733 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5734 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5735 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5738 static void vmx_dump_dtsel(char *name, uint32_t limit)
5740 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5741 name, vmcs_read32(limit),
5742 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5745 void dump_vmcs(void)
5747 u32 vmentry_ctl, vmexit_ctl;
5748 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5752 if (!dump_invalid_vmcs) {
5753 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5757 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5758 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5759 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5760 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5761 cr4 = vmcs_readl(GUEST_CR4);
5762 efer = vmcs_read64(GUEST_IA32_EFER);
5763 secondary_exec_control = 0;
5764 if (cpu_has_secondary_exec_ctrls())
5765 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5767 pr_err("*** Guest State ***\n");
5768 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5769 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5770 vmcs_readl(CR0_GUEST_HOST_MASK));
5771 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5772 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5773 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5774 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5775 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5777 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5778 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5779 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5780 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5782 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5783 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5784 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5785 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5786 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5787 vmcs_readl(GUEST_SYSENTER_ESP),
5788 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5789 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5790 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5791 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5792 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5793 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5794 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5795 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5796 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5797 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5798 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5799 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5800 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5801 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5802 efer, vmcs_read64(GUEST_IA32_PAT));
5803 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5804 vmcs_read64(GUEST_IA32_DEBUGCTL),
5805 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5806 if (cpu_has_load_perf_global_ctrl() &&
5807 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5808 pr_err("PerfGlobCtl = 0x%016llx\n",
5809 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5810 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5811 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5812 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5813 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5814 vmcs_read32(GUEST_ACTIVITY_STATE));
5815 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5816 pr_err("InterruptStatus = %04x\n",
5817 vmcs_read16(GUEST_INTR_STATUS));
5819 pr_err("*** Host State ***\n");
5820 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5821 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5822 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5823 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5824 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5825 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5826 vmcs_read16(HOST_TR_SELECTOR));
5827 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5828 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5829 vmcs_readl(HOST_TR_BASE));
5830 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5831 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5832 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5833 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5834 vmcs_readl(HOST_CR4));
5835 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5836 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5837 vmcs_read32(HOST_IA32_SYSENTER_CS),
5838 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5839 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5840 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5841 vmcs_read64(HOST_IA32_EFER),
5842 vmcs_read64(HOST_IA32_PAT));
5843 if (cpu_has_load_perf_global_ctrl() &&
5844 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5845 pr_err("PerfGlobCtl = 0x%016llx\n",
5846 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5848 pr_err("*** Control State ***\n");
5849 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5850 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5851 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5852 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5853 vmcs_read32(EXCEPTION_BITMAP),
5854 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5855 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5856 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5857 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5858 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5859 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5860 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5861 vmcs_read32(VM_EXIT_INTR_INFO),
5862 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5863 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5864 pr_err(" reason=%08x qualification=%016lx\n",
5865 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5866 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5867 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5868 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5869 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5870 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5871 pr_err("TSC Multiplier = 0x%016llx\n",
5872 vmcs_read64(TSC_MULTIPLIER));
5873 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5874 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5875 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5876 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5878 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5879 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5880 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5881 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5883 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5884 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5885 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5886 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5887 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5888 pr_err("PLE Gap=%08x Window=%08x\n",
5889 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5890 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5891 pr_err("Virtual processor ID = 0x%04x\n",
5892 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5896 * The guest has exited. See if we can fix it or if we need userspace
5899 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
5901 struct vcpu_vmx *vmx = to_vmx(vcpu);
5902 u32 exit_reason = vmx->exit_reason;
5903 u32 vectoring_info = vmx->idt_vectoring_info;
5906 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5907 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5908 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5909 * mode as if vcpus is in root mode, the PML buffer must has been
5913 vmx_flush_pml_buffer(vcpu);
5916 * We should never reach this point with a pending nested VM-Enter, and
5917 * more specifically emulation of L2 due to invalid guest state (see
5918 * below) should never happen as that means we incorrectly allowed a
5919 * nested VM-Enter with an invalid vmcs12.
5921 WARN_ON_ONCE(vmx->nested.nested_run_pending);
5923 /* If guest state is invalid, start emulating */
5924 if (vmx->emulation_required)
5925 return handle_invalid_guest_state(vcpu);
5927 if (is_guest_mode(vcpu)) {
5929 * The host physical addresses of some pages of guest memory
5930 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
5931 * Page). The CPU may write to these pages via their host
5932 * physical address while L2 is running, bypassing any
5933 * address-translation-based dirty tracking (e.g. EPT write
5936 * Mark them dirty on every exit from L2 to prevent them from
5937 * getting out of sync with dirty tracking.
5939 nested_mark_vmcs12_pages_dirty(vcpu);
5941 if (nested_vmx_reflect_vmexit(vcpu))
5945 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5947 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5948 vcpu->run->fail_entry.hardware_entry_failure_reason
5950 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
5954 if (unlikely(vmx->fail)) {
5956 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5957 vcpu->run->fail_entry.hardware_entry_failure_reason
5958 = vmcs_read32(VM_INSTRUCTION_ERROR);
5959 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
5965 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5966 * delivery event since it indicates guest is accessing MMIO.
5967 * The vm-exit can be triggered again after return to guest that
5968 * will cause infinite loop.
5970 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5971 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5972 exit_reason != EXIT_REASON_EPT_VIOLATION &&
5973 exit_reason != EXIT_REASON_PML_FULL &&
5974 exit_reason != EXIT_REASON_APIC_ACCESS &&
5975 exit_reason != EXIT_REASON_TASK_SWITCH)) {
5976 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5977 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
5978 vcpu->run->internal.ndata = 3;
5979 vcpu->run->internal.data[0] = vectoring_info;
5980 vcpu->run->internal.data[1] = exit_reason;
5981 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
5982 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
5983 vcpu->run->internal.ndata++;
5984 vcpu->run->internal.data[3] =
5985 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5987 vcpu->run->internal.data[vcpu->run->internal.ndata++] =
5988 vcpu->arch.last_vmentry_cpu;
5992 if (unlikely(!enable_vnmi &&
5993 vmx->loaded_vmcs->soft_vnmi_blocked)) {
5994 if (!vmx_interrupt_blocked(vcpu)) {
5995 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5996 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
5997 vcpu->arch.nmi_pending) {
5999 * This CPU don't support us in finding the end of an
6000 * NMI-blocked window if the guest runs with IRQs
6001 * disabled. So we pull the trigger after 1 s of
6002 * futile waiting, but inform the user about this.
6004 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6005 "state on VCPU %d after 1 s timeout\n",
6006 __func__, vcpu->vcpu_id);
6007 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6011 if (exit_fastpath != EXIT_FASTPATH_NONE)
6014 if (exit_reason >= kvm_vmx_max_exit_handlers)
6015 goto unexpected_vmexit;
6016 #ifdef CONFIG_RETPOLINE
6017 if (exit_reason == EXIT_REASON_MSR_WRITE)
6018 return kvm_emulate_wrmsr(vcpu);
6019 else if (exit_reason == EXIT_REASON_PREEMPTION_TIMER)
6020 return handle_preemption_timer(vcpu);
6021 else if (exit_reason == EXIT_REASON_INTERRUPT_WINDOW)
6022 return handle_interrupt_window(vcpu);
6023 else if (exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6024 return handle_external_interrupt(vcpu);
6025 else if (exit_reason == EXIT_REASON_HLT)
6026 return kvm_emulate_halt(vcpu);
6027 else if (exit_reason == EXIT_REASON_EPT_MISCONFIG)
6028 return handle_ept_misconfig(vcpu);
6031 exit_reason = array_index_nospec(exit_reason,
6032 kvm_vmx_max_exit_handlers);
6033 if (!kvm_vmx_exit_handlers[exit_reason])
6034 goto unexpected_vmexit;
6036 return kvm_vmx_exit_handlers[exit_reason](vcpu);
6039 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n", exit_reason);
6041 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6042 vcpu->run->internal.suberror =
6043 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6044 vcpu->run->internal.ndata = 2;
6045 vcpu->run->internal.data[0] = exit_reason;
6046 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6051 * Software based L1D cache flush which is used when microcode providing
6052 * the cache control MSR is not loaded.
6054 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6055 * flush it is required to read in 64 KiB because the replacement algorithm
6056 * is not exactly LRU. This could be sized at runtime via topology
6057 * information but as all relevant affected CPUs have 32KiB L1D cache size
6058 * there is no point in doing so.
6060 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6062 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6065 * This code is only executed when the the flush mode is 'cond' or
6068 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6072 * Clear the per-vcpu flush bit, it gets set again
6073 * either from vcpu_run() or from one of the unsafe
6076 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6077 vcpu->arch.l1tf_flush_l1d = false;
6080 * Clear the per-cpu flush bit, it gets set again from
6081 * the interrupt handlers.
6083 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6084 kvm_clear_cpu_l1tf_flush_l1d();
6090 vcpu->stat.l1d_flush++;
6092 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6093 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6098 /* First ensure the pages are in the TLB */
6099 "xorl %%eax, %%eax\n"
6100 ".Lpopulate_tlb:\n\t"
6101 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6102 "addl $4096, %%eax\n\t"
6103 "cmpl %%eax, %[size]\n\t"
6104 "jne .Lpopulate_tlb\n\t"
6105 "xorl %%eax, %%eax\n\t"
6107 /* Now fill the cache */
6108 "xorl %%eax, %%eax\n"
6110 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6111 "addl $64, %%eax\n\t"
6112 "cmpl %%eax, %[size]\n\t"
6113 "jne .Lfill_cache\n\t"
6115 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6117 : "eax", "ebx", "ecx", "edx");
6120 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6122 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6125 if (is_guest_mode(vcpu) &&
6126 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6129 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6130 if (is_guest_mode(vcpu))
6131 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6133 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6136 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6138 struct vcpu_vmx *vmx = to_vmx(vcpu);
6139 u32 sec_exec_control;
6141 if (!lapic_in_kernel(vcpu))
6144 if (!flexpriority_enabled &&
6145 !cpu_has_vmx_virtualize_x2apic_mode())
6148 /* Postpone execution until vmcs01 is the current VMCS. */
6149 if (is_guest_mode(vcpu)) {
6150 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6154 sec_exec_control = secondary_exec_controls_get(vmx);
6155 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6156 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6158 switch (kvm_get_apic_mode(vcpu)) {
6159 case LAPIC_MODE_INVALID:
6160 WARN_ONCE(true, "Invalid local APIC state");
6161 case LAPIC_MODE_DISABLED:
6163 case LAPIC_MODE_XAPIC:
6164 if (flexpriority_enabled) {
6166 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6167 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6170 * Flush the TLB, reloading the APIC access page will
6171 * only do so if its physical address has changed, but
6172 * the guest may have inserted a non-APIC mapping into
6173 * the TLB while the APIC access page was disabled.
6175 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6178 case LAPIC_MODE_X2APIC:
6179 if (cpu_has_vmx_virtualize_x2apic_mode())
6181 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6184 secondary_exec_controls_set(vmx, sec_exec_control);
6186 vmx_update_msr_bitmap(vcpu);
6189 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6193 /* Defer reload until vmcs01 is the current VMCS. */
6194 if (is_guest_mode(vcpu)) {
6195 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6199 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6200 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6203 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6204 if (is_error_page(page))
6207 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6208 vmx_flush_tlb_current(vcpu);
6211 * Do not pin apic access page in memory, the MMU notifier
6212 * will call us again if it is migrated or swapped out.
6217 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6225 status = vmcs_read16(GUEST_INTR_STATUS);
6227 if (max_isr != old) {
6229 status |= max_isr << 8;
6230 vmcs_write16(GUEST_INTR_STATUS, status);
6234 static void vmx_set_rvi(int vector)
6242 status = vmcs_read16(GUEST_INTR_STATUS);
6243 old = (u8)status & 0xff;
6244 if ((u8)vector != old) {
6246 status |= (u8)vector;
6247 vmcs_write16(GUEST_INTR_STATUS, status);
6251 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6254 * When running L2, updating RVI is only relevant when
6255 * vmcs12 virtual-interrupt-delivery enabled.
6256 * However, it can be enabled only when L1 also
6257 * intercepts external-interrupts and in that case
6258 * we should not update vmcs02 RVI but instead intercept
6259 * interrupt. Therefore, do nothing when running L2.
6261 if (!is_guest_mode(vcpu))
6262 vmx_set_rvi(max_irr);
6265 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6267 struct vcpu_vmx *vmx = to_vmx(vcpu);
6269 bool max_irr_updated;
6271 WARN_ON(!vcpu->arch.apicv_active);
6272 if (pi_test_on(&vmx->pi_desc)) {
6273 pi_clear_on(&vmx->pi_desc);
6275 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6276 * But on x86 this is just a compiler barrier anyway.
6278 smp_mb__after_atomic();
6280 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6283 * If we are running L2 and L1 has a new pending interrupt
6284 * which can be injected, we should re-evaluate
6285 * what should be done with this new L1 interrupt.
6286 * If L1 intercepts external-interrupts, we should
6287 * exit from L2 to L1. Otherwise, interrupt should be
6288 * delivered directly to L2.
6290 if (is_guest_mode(vcpu) && max_irr_updated) {
6291 if (nested_exit_on_intr(vcpu))
6292 kvm_vcpu_exiting_guest_mode(vcpu);
6294 kvm_make_request(KVM_REQ_EVENT, vcpu);
6297 max_irr = kvm_lapic_find_highest_irr(vcpu);
6299 vmx_hwapic_irr_update(vcpu, max_irr);
6303 static bool vmx_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
6305 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6307 return pi_test_on(pi_desc) ||
6308 (pi_test_sn(pi_desc) && !pi_is_pir_empty(pi_desc));
6311 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6313 if (!kvm_vcpu_apicv_active(vcpu))
6316 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6317 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6318 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6319 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6322 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6324 struct vcpu_vmx *vmx = to_vmx(vcpu);
6326 pi_clear_on(&vmx->pi_desc);
6327 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6330 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6332 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu, u32 intr_info)
6334 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6335 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6337 kvm_before_interrupt(vcpu);
6338 vmx_do_interrupt_nmi_irqoff(gate_offset(desc));
6339 kvm_after_interrupt(vcpu);
6342 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6344 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6346 /* if exit due to PF check for async PF */
6347 if (is_page_fault(intr_info))
6348 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6349 /* Handle machine checks before interrupts are enabled */
6350 else if (is_machine_check(intr_info))
6351 kvm_machine_check();
6352 /* We need to handle NMIs before interrupts are enabled */
6353 else if (is_nmi(intr_info))
6354 handle_interrupt_nmi_irqoff(&vmx->vcpu, intr_info);
6357 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6359 u32 intr_info = vmx_get_intr_info(vcpu);
6361 if (WARN_ONCE(!is_external_intr(intr_info),
6362 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6365 handle_interrupt_nmi_irqoff(vcpu, intr_info);
6368 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6370 struct vcpu_vmx *vmx = to_vmx(vcpu);
6372 if (vmx->exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6373 handle_external_interrupt_irqoff(vcpu);
6374 else if (vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)
6375 handle_exception_nmi_irqoff(vmx);
6378 static bool vmx_has_emulated_msr(u32 index)
6381 case MSR_IA32_SMBASE:
6383 * We cannot do SMM unless we can run the guest in big
6386 return enable_unrestricted_guest || emulate_invalid_guest_state;
6387 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6389 case MSR_AMD64_VIRT_SPEC_CTRL:
6390 /* This is AMD only. */
6397 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6402 bool idtv_info_valid;
6404 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6407 if (vmx->loaded_vmcs->nmi_known_unmasked)
6410 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6411 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6412 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6414 * SDM 3: 27.7.1.2 (September 2008)
6415 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6416 * a guest IRET fault.
6417 * SDM 3: 23.2.2 (September 2008)
6418 * Bit 12 is undefined in any of the following cases:
6419 * If the VM exit sets the valid bit in the IDT-vectoring
6420 * information field.
6421 * If the VM exit is due to a double fault.
6423 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6424 vector != DF_VECTOR && !idtv_info_valid)
6425 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6426 GUEST_INTR_STATE_NMI);
6428 vmx->loaded_vmcs->nmi_known_unmasked =
6429 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6430 & GUEST_INTR_STATE_NMI);
6431 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6432 vmx->loaded_vmcs->vnmi_blocked_time +=
6433 ktime_to_ns(ktime_sub(ktime_get(),
6434 vmx->loaded_vmcs->entry_time));
6437 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6438 u32 idt_vectoring_info,
6439 int instr_len_field,
6440 int error_code_field)
6444 bool idtv_info_valid;
6446 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6448 vcpu->arch.nmi_injected = false;
6449 kvm_clear_exception_queue(vcpu);
6450 kvm_clear_interrupt_queue(vcpu);
6452 if (!idtv_info_valid)
6455 kvm_make_request(KVM_REQ_EVENT, vcpu);
6457 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6458 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6461 case INTR_TYPE_NMI_INTR:
6462 vcpu->arch.nmi_injected = true;
6464 * SDM 3: 27.7.1.2 (September 2008)
6465 * Clear bit "block by NMI" before VM entry if a NMI
6468 vmx_set_nmi_mask(vcpu, false);
6470 case INTR_TYPE_SOFT_EXCEPTION:
6471 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6473 case INTR_TYPE_HARD_EXCEPTION:
6474 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6475 u32 err = vmcs_read32(error_code_field);
6476 kvm_requeue_exception_e(vcpu, vector, err);
6478 kvm_requeue_exception(vcpu, vector);
6480 case INTR_TYPE_SOFT_INTR:
6481 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6483 case INTR_TYPE_EXT_INTR:
6484 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6491 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6493 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6494 VM_EXIT_INSTRUCTION_LEN,
6495 IDT_VECTORING_ERROR_CODE);
6498 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6500 __vmx_complete_interrupts(vcpu,
6501 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6502 VM_ENTRY_INSTRUCTION_LEN,
6503 VM_ENTRY_EXCEPTION_ERROR_CODE);
6505 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6508 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6511 struct perf_guest_switch_msr *msrs;
6513 msrs = perf_guest_get_msrs(&nr_msrs);
6518 for (i = 0; i < nr_msrs; i++)
6519 if (msrs[i].host == msrs[i].guest)
6520 clear_atomic_switch_msr(vmx, msrs[i].msr);
6522 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6523 msrs[i].host, false);
6526 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6528 struct vcpu_vmx *vmx = to_vmx(vcpu);
6532 if (vmx->req_immediate_exit) {
6533 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6534 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6535 } else if (vmx->hv_deadline_tsc != -1) {
6537 if (vmx->hv_deadline_tsc > tscl)
6538 /* set_hv_timer ensures the delta fits in 32-bits */
6539 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6540 cpu_preemption_timer_multi);
6544 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6545 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6546 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6547 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6548 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6552 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6554 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6555 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6556 vmcs_writel(HOST_RSP, host_rsp);
6560 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6562 switch (to_vmx(vcpu)->exit_reason) {
6563 case EXIT_REASON_MSR_WRITE:
6564 return handle_fastpath_set_msr_irqoff(vcpu);
6565 case EXIT_REASON_PREEMPTION_TIMER:
6566 return handle_fastpath_preemption_timer(vcpu);
6568 return EXIT_FASTPATH_NONE;
6572 bool __vmx_vcpu_run(struct vcpu_vmx *vmx, unsigned long *regs, bool launched);
6574 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6575 struct vcpu_vmx *vmx)
6578 * VMENTER enables interrupts (host state), but the kernel state is
6579 * interrupts disabled when this is invoked. Also tell RCU about
6580 * it. This is the same logic as for exit_to_user_mode().
6582 * This ensures that e.g. latency analysis on the host observes
6583 * guest mode as interrupt enabled.
6585 * guest_enter_irqoff() informs context tracking about the
6586 * transition to guest mode and if enabled adjusts RCU state
6589 instrumentation_begin();
6590 trace_hardirqs_on_prepare();
6591 lockdep_hardirqs_on_prepare(CALLER_ADDR0);
6592 instrumentation_end();
6594 guest_enter_irqoff();
6595 lockdep_hardirqs_on(CALLER_ADDR0);
6597 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6598 if (static_branch_unlikely(&vmx_l1d_should_flush))
6599 vmx_l1d_flush(vcpu);
6600 else if (static_branch_unlikely(&mds_user_clear))
6601 mds_clear_cpu_buffers();
6603 if (vcpu->arch.cr2 != native_read_cr2())
6604 native_write_cr2(vcpu->arch.cr2);
6606 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6607 vmx->loaded_vmcs->launched);
6609 vcpu->arch.cr2 = native_read_cr2();
6612 * VMEXIT disables interrupts (host state), but tracing and lockdep
6613 * have them in state 'on' as recorded before entering guest mode.
6614 * Same as enter_from_user_mode().
6616 * guest_exit_irqoff() restores host context and reinstates RCU if
6617 * enabled and required.
6619 * This needs to be done before the below as native_read_msr()
6620 * contains a tracepoint and x86_spec_ctrl_restore_host() calls
6621 * into world and some more.
6623 lockdep_hardirqs_off(CALLER_ADDR0);
6624 guest_exit_irqoff();
6626 instrumentation_begin();
6627 trace_hardirqs_off_finish();
6628 instrumentation_end();
6631 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6633 fastpath_t exit_fastpath;
6634 struct vcpu_vmx *vmx = to_vmx(vcpu);
6635 unsigned long cr3, cr4;
6638 /* Record the guest's net vcpu time for enforced NMI injections. */
6639 if (unlikely(!enable_vnmi &&
6640 vmx->loaded_vmcs->soft_vnmi_blocked))
6641 vmx->loaded_vmcs->entry_time = ktime_get();
6643 /* Don't enter VMX if guest state is invalid, let the exit handler
6644 start emulation until we arrive back to a valid state */
6645 if (vmx->emulation_required)
6646 return EXIT_FASTPATH_NONE;
6648 if (vmx->ple_window_dirty) {
6649 vmx->ple_window_dirty = false;
6650 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6654 * We did this in prepare_switch_to_guest, because it needs to
6655 * be within srcu_read_lock.
6657 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6659 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6660 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6661 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6662 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6664 cr3 = __get_current_cr3_fast();
6665 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6666 vmcs_writel(HOST_CR3, cr3);
6667 vmx->loaded_vmcs->host_state.cr3 = cr3;
6670 cr4 = cr4_read_shadow();
6671 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6672 vmcs_writel(HOST_CR4, cr4);
6673 vmx->loaded_vmcs->host_state.cr4 = cr4;
6676 /* When single-stepping over STI and MOV SS, we must clear the
6677 * corresponding interruptibility bits in the guest state. Otherwise
6678 * vmentry fails as it then expects bit 14 (BS) in pending debug
6679 * exceptions being set, but that's not correct for the guest debugging
6681 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6682 vmx_set_interrupt_shadow(vcpu, 0);
6684 kvm_load_guest_xsave_state(vcpu);
6686 pt_guest_enter(vmx);
6688 atomic_switch_perf_msrs(vmx);
6690 if (enable_preemption_timer)
6691 vmx_update_hv_timer(vcpu);
6693 kvm_wait_lapic_expire(vcpu);
6696 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6697 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6698 * is no need to worry about the conditional branch over the wrmsr
6699 * being speculatively taken.
6701 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6703 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6704 vmx_vcpu_enter_exit(vcpu, vmx);
6707 * We do not use IBRS in the kernel. If this vCPU has used the
6708 * SPEC_CTRL MSR it may have left it on; save the value and
6709 * turn it off. This is much more efficient than blindly adding
6710 * it to the atomic save/restore list. Especially as the former
6711 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6713 * For non-nested case:
6714 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6718 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6721 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6722 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6724 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6726 /* All fields are clean at this point */
6727 if (static_branch_unlikely(&enable_evmcs))
6728 current_evmcs->hv_clean_fields |=
6729 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6731 if (static_branch_unlikely(&enable_evmcs))
6732 current_evmcs->hv_vp_id = vcpu->arch.hyperv.vp_index;
6734 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6735 if (vmx->host_debugctlmsr)
6736 update_debugctlmsr(vmx->host_debugctlmsr);
6738 #ifndef CONFIG_X86_64
6740 * The sysexit path does not restore ds/es, so we must set them to
6741 * a reasonable value ourselves.
6743 * We can't defer this to vmx_prepare_switch_to_host() since that
6744 * function may be executed in interrupt context, which saves and
6745 * restore segments around it, nullifying its effect.
6747 loadsegment(ds, __USER_DS);
6748 loadsegment(es, __USER_DS);
6751 vmx_register_cache_reset(vcpu);
6755 kvm_load_host_xsave_state(vcpu);
6757 vmx->nested.nested_run_pending = 0;
6758 vmx->idt_vectoring_info = 0;
6760 if (unlikely(vmx->fail)) {
6761 vmx->exit_reason = 0xdead;
6762 return EXIT_FASTPATH_NONE;
6765 vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
6766 if (unlikely((u16)vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY))
6767 kvm_machine_check();
6769 trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
6771 if (unlikely(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6772 return EXIT_FASTPATH_NONE;
6774 vmx->loaded_vmcs->launched = 1;
6775 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6777 vmx_recover_nmi_blocking(vmx);
6778 vmx_complete_interrupts(vmx);
6780 if (is_guest_mode(vcpu))
6781 return EXIT_FASTPATH_NONE;
6783 exit_fastpath = vmx_exit_handlers_fastpath(vcpu);
6784 if (exit_fastpath == EXIT_FASTPATH_REENTER_GUEST) {
6785 if (!kvm_vcpu_exit_request(vcpu)) {
6787 * FIXME: this goto should be a loop in vcpu_enter_guest,
6788 * but it would incur the cost of a retpoline for now.
6789 * Revisit once static calls are available.
6791 if (vcpu->arch.apicv_active)
6792 vmx_sync_pir_to_irr(vcpu);
6795 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
6798 return exit_fastpath;
6801 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6803 struct vcpu_vmx *vmx = to_vmx(vcpu);
6806 vmx_destroy_pml_buffer(vmx);
6807 free_vpid(vmx->vpid);
6808 nested_vmx_free_vcpu(vcpu);
6809 free_loaded_vmcs(vmx->loaded_vmcs);
6812 static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
6814 struct vcpu_vmx *vmx;
6815 unsigned long *msr_bitmap;
6818 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6823 vmx->vpid = allocate_vpid();
6826 * If PML is turned on, failure on enabling PML just results in failure
6827 * of creating the vcpu, therefore we can simplify PML logic (by
6828 * avoiding dealing with cases, such as enabling PML partially on vcpus
6829 * for the guest), etc.
6832 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6837 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) != NR_SHARED_MSRS);
6839 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6840 u32 index = vmx_msr_index[i];
6841 u32 data_low, data_high;
6844 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6846 if (wrmsr_safe(index, data_low, data_high) < 0)
6849 vmx->guest_msrs[j].index = i;
6850 vmx->guest_msrs[j].data = 0;
6852 case MSR_IA32_TSX_CTRL:
6854 * No need to pass TSX_CTRL_CPUID_CLEAR through, so
6855 * let's avoid changing CPUID bits under the host
6858 vmx->guest_msrs[j].mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6861 vmx->guest_msrs[j].mask = -1ull;
6867 err = alloc_loaded_vmcs(&vmx->vmcs01);
6871 msr_bitmap = vmx->vmcs01.msr_bitmap;
6872 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6873 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6874 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6875 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6876 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6877 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6878 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6879 if (kvm_cstate_in_guest(vcpu->kvm)) {
6880 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C1_RES, MSR_TYPE_R);
6881 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6882 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6883 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6885 vmx->msr_bitmap_mode = 0;
6887 vmx->loaded_vmcs = &vmx->vmcs01;
6889 vmx_vcpu_load(vcpu, cpu);
6894 if (cpu_need_virtualize_apic_accesses(vcpu)) {
6895 err = alloc_apic_access_page(vcpu->kvm);
6900 if (enable_ept && !enable_unrestricted_guest) {
6901 err = init_rmode_identity_map(vcpu->kvm);
6907 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
6909 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6911 vmx->nested.posted_intr_nv = -1;
6912 vmx->nested.current_vmptr = -1ull;
6914 vcpu->arch.microcode_version = 0x100000000ULL;
6915 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
6918 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6919 * or POSTED_INTR_WAKEUP_VECTOR.
6921 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6922 vmx->pi_desc.sn = 1;
6924 vmx->ept_pointer = INVALID_PAGE;
6929 free_loaded_vmcs(vmx->loaded_vmcs);
6931 vmx_destroy_pml_buffer(vmx);
6933 free_vpid(vmx->vpid);
6937 #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"
6938 #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"
6940 static int vmx_vm_init(struct kvm *kvm)
6942 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
6945 kvm->arch.pause_in_guest = true;
6947 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6948 switch (l1tf_mitigation) {
6949 case L1TF_MITIGATION_OFF:
6950 case L1TF_MITIGATION_FLUSH_NOWARN:
6951 /* 'I explicitly don't care' is set */
6953 case L1TF_MITIGATION_FLUSH:
6954 case L1TF_MITIGATION_FLUSH_NOSMT:
6955 case L1TF_MITIGATION_FULL:
6957 * Warn upon starting the first VM in a potentially
6958 * insecure environment.
6960 if (sched_smt_active())
6961 pr_warn_once(L1TF_MSG_SMT);
6962 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6963 pr_warn_once(L1TF_MSG_L1D);
6965 case L1TF_MITIGATION_FULL_FORCE:
6966 /* Flush is enforced */
6970 kvm_apicv_init(kvm, enable_apicv);
6974 static int __init vmx_check_processor_compat(void)
6976 struct vmcs_config vmcs_conf;
6977 struct vmx_capability vmx_cap;
6979 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
6980 !this_cpu_has(X86_FEATURE_VMX)) {
6981 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
6985 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
6988 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
6989 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6990 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6991 smp_processor_id());
6997 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7002 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7003 * memory aliases with conflicting memory types and sometimes MCEs.
7004 * We have to be careful as to what are honored and when.
7006 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7007 * UC. The effective memory type is UC or WC depending on guest PAT.
7008 * This was historically the source of MCEs and we want to be
7011 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7012 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7013 * EPT memory type is set to WB. The effective memory type is forced
7016 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7017 * EPT memory type is used to emulate guest CD/MTRR.
7021 cache = MTRR_TYPE_UNCACHABLE;
7025 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7026 ipat = VMX_EPT_IPAT_BIT;
7027 cache = MTRR_TYPE_WRBACK;
7031 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7032 ipat = VMX_EPT_IPAT_BIT;
7033 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7034 cache = MTRR_TYPE_WRBACK;
7036 cache = MTRR_TYPE_UNCACHABLE;
7040 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
7043 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7046 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
7049 * These bits in the secondary execution controls field
7050 * are dynamic, the others are mostly based on the hypervisor
7051 * architecture and the guest's CPUID. Do not touch the
7055 SECONDARY_EXEC_SHADOW_VMCS |
7056 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7057 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7058 SECONDARY_EXEC_DESC;
7060 u32 new_ctl = vmx->secondary_exec_control;
7061 u32 cur_ctl = secondary_exec_controls_get(vmx);
7063 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7067 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7068 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7070 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7072 struct vcpu_vmx *vmx = to_vmx(vcpu);
7073 struct kvm_cpuid_entry2 *entry;
7075 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7076 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7078 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7079 if (entry && (entry->_reg & (_cpuid_mask))) \
7080 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7083 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7084 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7085 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7086 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7087 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7088 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7089 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7090 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7091 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7092 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7093 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7094 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7095 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7096 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7097 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7099 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7100 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7101 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7102 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7103 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7104 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7105 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7107 #undef cr4_fixed1_update
7110 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7112 struct vcpu_vmx *vmx = to_vmx(vcpu);
7114 if (kvm_mpx_supported()) {
7115 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7118 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7119 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7121 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7122 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7127 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7129 struct vcpu_vmx *vmx = to_vmx(vcpu);
7130 struct kvm_cpuid_entry2 *best = NULL;
7133 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7134 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7137 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7138 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7139 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7140 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7143 /* Get the number of configurable Address Ranges for filtering */
7144 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7145 PT_CAP_num_address_ranges);
7147 /* Initialize and clear the no dependency bits */
7148 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7149 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7152 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7153 * will inject an #GP
7155 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7156 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7159 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7160 * PSBFreq can be set
7162 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7163 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7164 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7167 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7168 * MTCFreq can be set
7170 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7171 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7172 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7174 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7175 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7176 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7179 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7180 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7181 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7183 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7184 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7185 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7187 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
7188 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7189 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7191 /* unmask address range configure area */
7192 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7193 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7196 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7198 struct vcpu_vmx *vmx = to_vmx(vcpu);
7200 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7201 vcpu->arch.xsaves_enabled = false;
7203 if (cpu_has_secondary_exec_ctrls()) {
7204 vmx_compute_secondary_exec_control(vmx);
7205 vmcs_set_secondary_exec_control(vmx);
7208 if (nested_vmx_allowed(vcpu))
7209 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7210 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7211 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7213 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7214 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7215 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7217 if (nested_vmx_allowed(vcpu)) {
7218 nested_vmx_cr_fixed1_bits_update(vcpu);
7219 nested_vmx_entry_exit_ctls_update(vcpu);
7222 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7223 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7224 update_intel_pt_cfg(vcpu);
7226 if (boot_cpu_has(X86_FEATURE_RTM)) {
7227 struct shared_msr_entry *msr;
7228 msr = find_msr_entry(vmx, MSR_IA32_TSX_CTRL);
7230 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7231 vmx_set_guest_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7236 static __init void vmx_set_cpu_caps(void)
7242 kvm_cpu_cap_set(X86_FEATURE_VMX);
7245 if (kvm_mpx_supported())
7246 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7247 if (cpu_has_vmx_invpcid())
7248 kvm_cpu_cap_check_and_set(X86_FEATURE_INVPCID);
7249 if (vmx_pt_mode_is_host_guest())
7250 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7252 if (vmx_umip_emulated())
7253 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7257 if (!vmx_xsaves_supported())
7258 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7260 /* CPUID 0x80000001 */
7261 if (!cpu_has_vmx_rdtscp())
7262 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7264 if (vmx_waitpkg_supported())
7265 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7268 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7270 to_vmx(vcpu)->req_immediate_exit = true;
7273 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7274 struct x86_instruction_info *info)
7276 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7277 unsigned short port;
7281 if (info->intercept == x86_intercept_in ||
7282 info->intercept == x86_intercept_ins) {
7283 port = info->src_val;
7284 size = info->dst_bytes;
7286 port = info->dst_val;
7287 size = info->src_bytes;
7291 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7292 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7295 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7297 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7298 intercept = nested_cpu_has(vmcs12,
7299 CPU_BASED_UNCOND_IO_EXITING);
7301 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7303 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7304 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7307 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7308 struct x86_instruction_info *info,
7309 enum x86_intercept_stage stage,
7310 struct x86_exception *exception)
7312 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7314 switch (info->intercept) {
7316 * RDPID causes #UD if disabled through secondary execution controls.
7317 * Because it is marked as EmulateOnUD, we need to intercept it here.
7319 case x86_intercept_rdtscp:
7320 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
7321 exception->vector = UD_VECTOR;
7322 exception->error_code_valid = false;
7323 return X86EMUL_PROPAGATE_FAULT;
7327 case x86_intercept_in:
7328 case x86_intercept_ins:
7329 case x86_intercept_out:
7330 case x86_intercept_outs:
7331 return vmx_check_intercept_io(vcpu, info);
7333 case x86_intercept_lgdt:
7334 case x86_intercept_lidt:
7335 case x86_intercept_lldt:
7336 case x86_intercept_ltr:
7337 case x86_intercept_sgdt:
7338 case x86_intercept_sidt:
7339 case x86_intercept_sldt:
7340 case x86_intercept_str:
7341 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7342 return X86EMUL_CONTINUE;
7344 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7347 /* TODO: check more intercepts... */
7352 return X86EMUL_UNHANDLEABLE;
7355 #ifdef CONFIG_X86_64
7356 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7357 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7358 u64 divisor, u64 *result)
7360 u64 low = a << shift, high = a >> (64 - shift);
7362 /* To avoid the overflow on divq */
7363 if (high >= divisor)
7366 /* Low hold the result, high hold rem which is discarded */
7367 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7368 "rm" (divisor), "0" (low), "1" (high));
7374 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7377 struct vcpu_vmx *vmx;
7378 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7379 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7383 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7384 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7385 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7386 ktimer->timer_advance_ns);
7388 if (delta_tsc > lapic_timer_advance_cycles)
7389 delta_tsc -= lapic_timer_advance_cycles;
7393 /* Convert to host delta tsc if tsc scaling is enabled */
7394 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7395 delta_tsc && u64_shl_div_u64(delta_tsc,
7396 kvm_tsc_scaling_ratio_frac_bits,
7397 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7401 * If the delta tsc can't fit in the 32 bit after the multi shift,
7402 * we can't use the preemption timer.
7403 * It's possible that it fits on later vmentries, but checking
7404 * on every vmentry is costly so we just use an hrtimer.
7406 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7409 vmx->hv_deadline_tsc = tscl + delta_tsc;
7410 *expired = !delta_tsc;
7414 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7416 to_vmx(vcpu)->hv_deadline_tsc = -1;
7420 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7422 if (!kvm_pause_in_guest(vcpu->kvm))
7423 shrink_ple_window(vcpu);
7426 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7427 struct kvm_memory_slot *slot)
7429 if (!kvm_dirty_log_manual_protect_and_init_set(kvm))
7430 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7431 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7434 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7435 struct kvm_memory_slot *slot)
7437 kvm_mmu_slot_set_dirty(kvm, slot);
7440 static void vmx_flush_log_dirty(struct kvm *kvm)
7442 kvm_flush_pml_buffers(kvm);
7445 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7446 struct kvm_memory_slot *memslot,
7447 gfn_t offset, unsigned long mask)
7449 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7452 static void __pi_post_block(struct kvm_vcpu *vcpu)
7454 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7455 struct pi_desc old, new;
7459 old.control = new.control = pi_desc->control;
7460 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
7461 "Wakeup handler not enabled while the VCPU is blocked\n");
7463 dest = cpu_physical_id(vcpu->cpu);
7465 if (x2apic_enabled())
7468 new.ndst = (dest << 8) & 0xFF00;
7470 /* set 'NV' to 'notification vector' */
7471 new.nv = POSTED_INTR_VECTOR;
7472 } while (cmpxchg64(&pi_desc->control, old.control,
7473 new.control) != old.control);
7475 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
7476 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7477 list_del(&vcpu->blocked_vcpu_list);
7478 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7479 vcpu->pre_pcpu = -1;
7484 * This routine does the following things for vCPU which is going
7485 * to be blocked if VT-d PI is enabled.
7486 * - Store the vCPU to the wakeup list, so when interrupts happen
7487 * we can find the right vCPU to wake up.
7488 * - Change the Posted-interrupt descriptor as below:
7489 * 'NDST' <-- vcpu->pre_pcpu
7490 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
7491 * - If 'ON' is set during this process, which means at least one
7492 * interrupt is posted for this vCPU, we cannot block it, in
7493 * this case, return 1, otherwise, return 0.
7496 static int pi_pre_block(struct kvm_vcpu *vcpu)
7499 struct pi_desc old, new;
7500 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7502 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
7503 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7504 !kvm_vcpu_apicv_active(vcpu))
7507 WARN_ON(irqs_disabled());
7508 local_irq_disable();
7509 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
7510 vcpu->pre_pcpu = vcpu->cpu;
7511 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7512 list_add_tail(&vcpu->blocked_vcpu_list,
7513 &per_cpu(blocked_vcpu_on_cpu,
7515 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7519 old.control = new.control = pi_desc->control;
7521 WARN((pi_desc->sn == 1),
7522 "Warning: SN field of posted-interrupts "
7523 "is set before blocking\n");
7526 * Since vCPU can be preempted during this process,
7527 * vcpu->cpu could be different with pre_pcpu, we
7528 * need to set pre_pcpu as the destination of wakeup
7529 * notification event, then we can find the right vCPU
7530 * to wakeup in wakeup handler if interrupts happen
7531 * when the vCPU is in blocked state.
7533 dest = cpu_physical_id(vcpu->pre_pcpu);
7535 if (x2apic_enabled())
7538 new.ndst = (dest << 8) & 0xFF00;
7540 /* set 'NV' to 'wakeup vector' */
7541 new.nv = POSTED_INTR_WAKEUP_VECTOR;
7542 } while (cmpxchg64(&pi_desc->control, old.control,
7543 new.control) != old.control);
7545 /* We should not block the vCPU if an interrupt is posted for it. */
7546 if (pi_test_on(pi_desc) == 1)
7547 __pi_post_block(vcpu);
7550 return (vcpu->pre_pcpu == -1);
7553 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7555 if (pi_pre_block(vcpu))
7558 if (kvm_lapic_hv_timer_in_use(vcpu))
7559 kvm_lapic_switch_to_sw_timer(vcpu);
7564 static void pi_post_block(struct kvm_vcpu *vcpu)
7566 if (vcpu->pre_pcpu == -1)
7569 WARN_ON(irqs_disabled());
7570 local_irq_disable();
7571 __pi_post_block(vcpu);
7575 static void vmx_post_block(struct kvm_vcpu *vcpu)
7577 if (kvm_x86_ops.set_hv_timer)
7578 kvm_lapic_switch_to_hv_timer(vcpu);
7580 pi_post_block(vcpu);
7584 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
7587 * @host_irq: host irq of the interrupt
7588 * @guest_irq: gsi of the interrupt
7589 * @set: set or unset PI
7590 * returns 0 on success, < 0 on failure
7592 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7593 uint32_t guest_irq, bool set)
7595 struct kvm_kernel_irq_routing_entry *e;
7596 struct kvm_irq_routing_table *irq_rt;
7597 struct kvm_lapic_irq irq;
7598 struct kvm_vcpu *vcpu;
7599 struct vcpu_data vcpu_info;
7602 if (!kvm_arch_has_assigned_device(kvm) ||
7603 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7604 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7607 idx = srcu_read_lock(&kvm->irq_srcu);
7608 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7609 if (guest_irq >= irq_rt->nr_rt_entries ||
7610 hlist_empty(&irq_rt->map[guest_irq])) {
7611 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7612 guest_irq, irq_rt->nr_rt_entries);
7616 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7617 if (e->type != KVM_IRQ_ROUTING_MSI)
7620 * VT-d PI cannot support posting multicast/broadcast
7621 * interrupts to a vCPU, we still use interrupt remapping
7622 * for these kind of interrupts.
7624 * For lowest-priority interrupts, we only support
7625 * those with single CPU as the destination, e.g. user
7626 * configures the interrupts via /proc/irq or uses
7627 * irqbalance to make the interrupts single-CPU.
7629 * We will support full lowest-priority interrupt later.
7631 * In addition, we can only inject generic interrupts using
7632 * the PI mechanism, refuse to route others through it.
7635 kvm_set_msi_irq(kvm, e, &irq);
7636 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
7637 !kvm_irq_is_postable(&irq)) {
7639 * Make sure the IRTE is in remapped mode if
7640 * we don't handle it in posted mode.
7642 ret = irq_set_vcpu_affinity(host_irq, NULL);
7645 "failed to back to remapped mode, irq: %u\n",
7653 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7654 vcpu_info.vector = irq.vector;
7656 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7657 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7660 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7662 ret = irq_set_vcpu_affinity(host_irq, NULL);
7665 printk(KERN_INFO "%s: failed to update PI IRTE\n",
7673 srcu_read_unlock(&kvm->irq_srcu, idx);
7677 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7679 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7680 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7681 FEAT_CTL_LMCE_ENABLED;
7683 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7684 ~FEAT_CTL_LMCE_ENABLED;
7687 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7689 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7690 if (to_vmx(vcpu)->nested.nested_run_pending)
7692 return !is_smm(vcpu);
7695 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7697 struct vcpu_vmx *vmx = to_vmx(vcpu);
7699 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7700 if (vmx->nested.smm.guest_mode)
7701 nested_vmx_vmexit(vcpu, -1, 0, 0);
7703 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7704 vmx->nested.vmxon = false;
7705 vmx_clear_hlt(vcpu);
7709 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7711 struct vcpu_vmx *vmx = to_vmx(vcpu);
7714 if (vmx->nested.smm.vmxon) {
7715 vmx->nested.vmxon = true;
7716 vmx->nested.smm.vmxon = false;
7719 if (vmx->nested.smm.guest_mode) {
7720 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7724 vmx->nested.smm.guest_mode = false;
7729 static void enable_smi_window(struct kvm_vcpu *vcpu)
7731 /* RSM will cause a vmexit anyway. */
7734 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7736 return to_vmx(vcpu)->nested.vmxon;
7739 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7741 if (is_guest_mode(vcpu)) {
7742 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7744 if (hrtimer_try_to_cancel(timer) == 1)
7745 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7749 static void hardware_unsetup(void)
7752 nested_vmx_hardware_unsetup();
7757 static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7759 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7760 BIT(APICV_INHIBIT_REASON_HYPERV);
7762 return supported & BIT(bit);
7765 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7766 .hardware_unsetup = hardware_unsetup,
7768 .hardware_enable = hardware_enable,
7769 .hardware_disable = hardware_disable,
7770 .cpu_has_accelerated_tpr = report_flexpriority,
7771 .has_emulated_msr = vmx_has_emulated_msr,
7773 .vm_size = sizeof(struct kvm_vmx),
7774 .vm_init = vmx_vm_init,
7776 .vcpu_create = vmx_create_vcpu,
7777 .vcpu_free = vmx_free_vcpu,
7778 .vcpu_reset = vmx_vcpu_reset,
7780 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7781 .vcpu_load = vmx_vcpu_load,
7782 .vcpu_put = vmx_vcpu_put,
7784 .update_exception_bitmap = update_exception_bitmap,
7785 .get_msr_feature = vmx_get_msr_feature,
7786 .get_msr = vmx_get_msr,
7787 .set_msr = vmx_set_msr,
7788 .get_segment_base = vmx_get_segment_base,
7789 .get_segment = vmx_get_segment,
7790 .set_segment = vmx_set_segment,
7791 .get_cpl = vmx_get_cpl,
7792 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7793 .set_cr0 = vmx_set_cr0,
7794 .set_cr4 = vmx_set_cr4,
7795 .set_efer = vmx_set_efer,
7796 .get_idt = vmx_get_idt,
7797 .set_idt = vmx_set_idt,
7798 .get_gdt = vmx_get_gdt,
7799 .set_gdt = vmx_set_gdt,
7800 .set_dr7 = vmx_set_dr7,
7801 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7802 .cache_reg = vmx_cache_reg,
7803 .get_rflags = vmx_get_rflags,
7804 .set_rflags = vmx_set_rflags,
7806 .tlb_flush_all = vmx_flush_tlb_all,
7807 .tlb_flush_current = vmx_flush_tlb_current,
7808 .tlb_flush_gva = vmx_flush_tlb_gva,
7809 .tlb_flush_guest = vmx_flush_tlb_guest,
7811 .run = vmx_vcpu_run,
7812 .handle_exit = vmx_handle_exit,
7813 .skip_emulated_instruction = vmx_skip_emulated_instruction,
7814 .update_emulated_instruction = vmx_update_emulated_instruction,
7815 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7816 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7817 .patch_hypercall = vmx_patch_hypercall,
7818 .set_irq = vmx_inject_irq,
7819 .set_nmi = vmx_inject_nmi,
7820 .queue_exception = vmx_queue_exception,
7821 .cancel_injection = vmx_cancel_injection,
7822 .interrupt_allowed = vmx_interrupt_allowed,
7823 .nmi_allowed = vmx_nmi_allowed,
7824 .get_nmi_mask = vmx_get_nmi_mask,
7825 .set_nmi_mask = vmx_set_nmi_mask,
7826 .enable_nmi_window = enable_nmi_window,
7827 .enable_irq_window = enable_irq_window,
7828 .update_cr8_intercept = update_cr8_intercept,
7829 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7830 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7831 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7832 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7833 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7834 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7835 .hwapic_irr_update = vmx_hwapic_irr_update,
7836 .hwapic_isr_update = vmx_hwapic_isr_update,
7837 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7838 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7839 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7840 .dy_apicv_has_pending_interrupt = vmx_dy_apicv_has_pending_interrupt,
7842 .set_tss_addr = vmx_set_tss_addr,
7843 .set_identity_map_addr = vmx_set_identity_map_addr,
7844 .get_mt_mask = vmx_get_mt_mask,
7846 .get_exit_info = vmx_get_exit_info,
7848 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
7850 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7852 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7854 .load_mmu_pgd = vmx_load_mmu_pgd,
7856 .check_intercept = vmx_check_intercept,
7857 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7859 .request_immediate_exit = vmx_request_immediate_exit,
7861 .sched_in = vmx_sched_in,
7863 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7864 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7865 .flush_log_dirty = vmx_flush_log_dirty,
7866 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7868 .pre_block = vmx_pre_block,
7869 .post_block = vmx_post_block,
7871 .pmu_ops = &intel_pmu_ops,
7872 .nested_ops = &vmx_nested_ops,
7874 .update_pi_irte = vmx_update_pi_irte,
7876 #ifdef CONFIG_X86_64
7877 .set_hv_timer = vmx_set_hv_timer,
7878 .cancel_hv_timer = vmx_cancel_hv_timer,
7881 .setup_mce = vmx_setup_mce,
7883 .smi_allowed = vmx_smi_allowed,
7884 .pre_enter_smm = vmx_pre_enter_smm,
7885 .pre_leave_smm = vmx_pre_leave_smm,
7886 .enable_smi_window = enable_smi_window,
7888 .can_emulate_instruction = vmx_can_emulate_instruction,
7889 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7890 .migrate_timers = vmx_migrate_timers,
7893 static __init int hardware_setup(void)
7895 unsigned long host_bndcfgs;
7897 int r, i, ept_lpage_level;
7900 host_idt_base = dt.address;
7902 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7903 kvm_define_shared_msr(i, vmx_msr_index[i]);
7905 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7908 if (boot_cpu_has(X86_FEATURE_NX))
7909 kvm_enable_efer_bits(EFER_NX);
7911 if (boot_cpu_has(X86_FEATURE_MPX)) {
7912 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7913 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7916 if (!cpu_has_vmx_mpx())
7917 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
7918 XFEATURE_MASK_BNDCSR);
7920 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7921 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7924 if (!cpu_has_vmx_ept() ||
7925 !cpu_has_vmx_ept_4levels() ||
7926 !cpu_has_vmx_ept_mt_wb() ||
7927 !cpu_has_vmx_invept_global())
7930 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7931 enable_ept_ad_bits = 0;
7933 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7934 enable_unrestricted_guest = 0;
7936 if (!cpu_has_vmx_flexpriority())
7937 flexpriority_enabled = 0;
7939 if (!cpu_has_virtual_nmis())
7943 * set_apic_access_page_addr() is used to reload apic access
7944 * page upon invalidation. No need to do anything if not
7945 * using the APIC_ACCESS_ADDR VMCS field.
7947 if (!flexpriority_enabled)
7948 vmx_x86_ops.set_apic_access_page_addr = NULL;
7950 if (!cpu_has_vmx_tpr_shadow())
7951 vmx_x86_ops.update_cr8_intercept = NULL;
7953 #if IS_ENABLED(CONFIG_HYPERV)
7954 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7956 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
7957 vmx_x86_ops.tlb_remote_flush_with_range =
7958 hv_remote_flush_tlb_with_range;
7962 if (!cpu_has_vmx_ple()) {
7965 ple_window_grow = 0;
7967 ple_window_shrink = 0;
7970 if (!cpu_has_vmx_apicv()) {
7972 vmx_x86_ops.sync_pir_to_irr = NULL;
7975 if (cpu_has_vmx_tsc_scaling()) {
7976 kvm_has_tsc_control = true;
7977 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7978 kvm_tsc_scaling_ratio_frac_bits = 48;
7981 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7987 ept_lpage_level = 0;
7988 else if (cpu_has_vmx_ept_1g_page())
7989 ept_lpage_level = PG_LEVEL_1G;
7990 else if (cpu_has_vmx_ept_2m_page())
7991 ept_lpage_level = PG_LEVEL_2M;
7993 ept_lpage_level = PG_LEVEL_4K;
7994 kvm_configure_mmu(enable_ept, vmx_get_max_tdp_level(), ept_lpage_level);
7997 * Only enable PML when hardware supports PML feature, and both EPT
7998 * and EPT A/D bit features are enabled -- PML depends on them to work.
8000 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8004 vmx_x86_ops.slot_enable_log_dirty = NULL;
8005 vmx_x86_ops.slot_disable_log_dirty = NULL;
8006 vmx_x86_ops.flush_log_dirty = NULL;
8007 vmx_x86_ops.enable_log_dirty_pt_masked = NULL;
8010 if (!cpu_has_vmx_preemption_timer())
8011 enable_preemption_timer = false;
8013 if (enable_preemption_timer) {
8014 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8017 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
8018 cpu_preemption_timer_multi =
8019 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8022 use_timer_freq = (u64)tsc_khz * 1000;
8023 use_timer_freq >>= cpu_preemption_timer_multi;
8026 * KVM "disables" the preemption timer by setting it to its max
8027 * value. Don't use the timer if it might cause spurious exits
8028 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8030 if (use_timer_freq > 0xffffffffu / 10)
8031 enable_preemption_timer = false;
8034 if (!enable_preemption_timer) {
8035 vmx_x86_ops.set_hv_timer = NULL;
8036 vmx_x86_ops.cancel_hv_timer = NULL;
8037 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8040 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
8042 kvm_mce_cap_supported |= MCG_LMCE_P;
8044 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8046 if (!enable_ept || !cpu_has_vmx_intel_pt())
8047 pt_mode = PT_MODE_SYSTEM;
8050 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
8051 vmx_capability.ept);
8053 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8060 r = alloc_kvm_area();
8062 nested_vmx_hardware_unsetup();
8066 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8067 .cpu_has_kvm_support = cpu_has_kvm_support,
8068 .disabled_by_bios = vmx_disabled_by_bios,
8069 .check_processor_compatibility = vmx_check_processor_compat,
8070 .hardware_setup = hardware_setup,
8072 .runtime_ops = &vmx_x86_ops,
8075 static void vmx_cleanup_l1d_flush(void)
8077 if (vmx_l1d_flush_pages) {
8078 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8079 vmx_l1d_flush_pages = NULL;
8081 /* Restore state so sysfs ignores VMX */
8082 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8085 static void vmx_exit(void)
8087 #ifdef CONFIG_KEXEC_CORE
8088 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8094 #if IS_ENABLED(CONFIG_HYPERV)
8095 if (static_branch_unlikely(&enable_evmcs)) {
8097 struct hv_vp_assist_page *vp_ap;
8099 * Reset everything to support using non-enlightened VMCS
8100 * access later (e.g. when we reload the module with
8101 * enlightened_vmcs=0)
8103 for_each_online_cpu(cpu) {
8104 vp_ap = hv_get_vp_assist_page(cpu);
8109 vp_ap->nested_control.features.directhypercall = 0;
8110 vp_ap->current_nested_vmcs = 0;
8111 vp_ap->enlighten_vmentry = 0;
8114 static_branch_disable(&enable_evmcs);
8117 vmx_cleanup_l1d_flush();
8119 module_exit(vmx_exit);
8121 static int __init vmx_init(void)
8125 #if IS_ENABLED(CONFIG_HYPERV)
8127 * Enlightened VMCS usage should be recommended and the host needs
8128 * to support eVMCS v1 or above. We can also disable eVMCS support
8129 * with module parameter.
8131 if (enlightened_vmcs &&
8132 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8133 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8134 KVM_EVMCS_VERSION) {
8137 /* Check that we have assist pages on all online CPUs */
8138 for_each_online_cpu(cpu) {
8139 if (!hv_get_vp_assist_page(cpu)) {
8140 enlightened_vmcs = false;
8145 if (enlightened_vmcs) {
8146 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8147 static_branch_enable(&enable_evmcs);
8150 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8151 vmx_x86_ops.enable_direct_tlbflush
8152 = hv_enable_direct_tlbflush;
8155 enlightened_vmcs = false;
8159 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8160 __alignof__(struct vcpu_vmx), THIS_MODULE);
8165 * Must be called after kvm_init() so enable_ept is properly set
8166 * up. Hand the parameter mitigation value in which was stored in
8167 * the pre module init parser. If no parameter was given, it will
8168 * contain 'auto' which will be turned into the default 'cond'
8171 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8177 for_each_possible_cpu(cpu) {
8178 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8179 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
8180 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
8183 #ifdef CONFIG_KEXEC_CORE
8184 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8185 crash_vmclear_local_loaded_vmcss);
8187 vmx_check_vmcs12_offsets();
8190 * Intel processors don't have problems with
8191 * GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable
8192 * it for VMX by default
8194 allow_smaller_maxphyaddr = true;
8198 module_init(vmx_init);