2 * Kernel-based Virtual Machine driver for Linux
4 * This module enables machines with Intel VT-x extensions to run virtual
5 * machines without emulation or binary translation.
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11 * Avi Kivity <avi@qumranet.com>
12 * Yaniv Kamay <yaniv@qumranet.com>
14 * This work is licensed under the terms of the GNU GPL, version 2. See
15 * the COPYING file in the top-level directory.
19 #include <linux/frame.h>
20 #include <linux/highmem.h>
21 #include <linux/hrtimer.h>
22 #include <linux/kernel.h>
23 #include <linux/kvm_host.h>
24 #include <linux/module.h>
25 #include <linux/moduleparam.h>
26 #include <linux/mod_devicetable.h>
28 #include <linux/sched.h>
29 #include <linux/slab.h>
30 #include <linux/tboot.h>
31 #include <linux/trace_events.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/spec-ctrl.h>
47 #include <asm/virtext.h>
50 #include "capabilities.h"
54 #include "kvm_cache_regs.h"
66 MODULE_AUTHOR("Qumranet");
67 MODULE_LICENSE("GPL");
69 static const struct x86_cpu_id vmx_cpu_id[] = {
70 X86_FEATURE_MATCH(X86_FEATURE_VMX),
73 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
75 bool __read_mostly enable_vpid = 1;
76 module_param_named(vpid, enable_vpid, bool, 0444);
78 static bool __read_mostly enable_vnmi = 1;
79 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
81 bool __read_mostly flexpriority_enabled = 1;
82 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
84 bool __read_mostly enable_ept = 1;
85 module_param_named(ept, enable_ept, bool, S_IRUGO);
87 bool __read_mostly enable_unrestricted_guest = 1;
88 module_param_named(unrestricted_guest,
89 enable_unrestricted_guest, bool, S_IRUGO);
91 bool __read_mostly enable_ept_ad_bits = 1;
92 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
94 static bool __read_mostly emulate_invalid_guest_state = true;
95 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
97 static bool __read_mostly fasteoi = 1;
98 module_param(fasteoi, bool, S_IRUGO);
100 static bool __read_mostly enable_apicv = 1;
101 module_param(enable_apicv, bool, S_IRUGO);
104 * If nested=1, nested virtualization is supported, i.e., guests may use
105 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
106 * use VMX instructions.
108 static bool __read_mostly nested = 1;
109 module_param(nested, bool, S_IRUGO);
111 static u64 __read_mostly host_xss;
113 bool __read_mostly enable_pml = 1;
114 module_param_named(pml, enable_pml, bool, S_IRUGO);
116 #define MSR_BITMAP_MODE_X2APIC 1
117 #define MSR_BITMAP_MODE_X2APIC_APICV 2
119 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
121 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
122 static int __read_mostly cpu_preemption_timer_multi;
123 static bool __read_mostly enable_preemption_timer = 1;
125 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
128 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
129 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
130 #define KVM_VM_CR0_ALWAYS_ON \
131 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
132 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
133 #define KVM_CR4_GUEST_OWNED_BITS \
134 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
135 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
137 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
138 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
139 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
141 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
144 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
145 * ple_gap: upper bound on the amount of time between two successive
146 * executions of PAUSE in a loop. Also indicate if ple enabled.
147 * According to test, this time is usually smaller than 128 cycles.
148 * ple_window: upper bound on the amount of time a guest is allowed to execute
149 * in a PAUSE loop. Tests indicate that most spinlocks are held for
150 * less than 2^12 cycles
151 * Time is measured based on a counter that runs at the same rate as the TSC,
152 * refer SDM volume 3b section 21.6.13 & 22.1.3.
154 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
155 module_param(ple_gap, uint, 0444);
157 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
158 module_param(ple_window, uint, 0444);
160 /* Default doubles per-vcpu window every exit. */
161 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
162 module_param(ple_window_grow, uint, 0444);
164 /* Default resets per-vcpu window every exit to ple_window. */
165 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
166 module_param(ple_window_shrink, uint, 0444);
168 /* Default is to compute the maximum so we can never overflow. */
169 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
170 module_param(ple_window_max, uint, 0444);
172 /* Default is SYSTEM mode, 1 for host-guest mode */
173 int __read_mostly pt_mode = PT_MODE_SYSTEM;
174 module_param(pt_mode, int, S_IRUGO);
176 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
177 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
178 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
180 /* Storage for pre module init parameter parsing */
181 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
183 static const struct {
186 } vmentry_l1d_param[] = {
187 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
188 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
189 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
190 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
191 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
192 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
195 #define L1D_CACHE_ORDER 4
196 static void *vmx_l1d_flush_pages;
198 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
204 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
208 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
211 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
212 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
213 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
218 /* If set to auto use the default l1tf mitigation method */
219 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
220 switch (l1tf_mitigation) {
221 case L1TF_MITIGATION_OFF:
222 l1tf = VMENTER_L1D_FLUSH_NEVER;
224 case L1TF_MITIGATION_FLUSH_NOWARN:
225 case L1TF_MITIGATION_FLUSH:
226 case L1TF_MITIGATION_FLUSH_NOSMT:
227 l1tf = VMENTER_L1D_FLUSH_COND;
229 case L1TF_MITIGATION_FULL:
230 case L1TF_MITIGATION_FULL_FORCE:
231 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
234 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
235 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
238 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
239 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
240 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
243 vmx_l1d_flush_pages = page_address(page);
246 * Initialize each page with a different pattern in
247 * order to protect against KSM in the nested
248 * virtualization case.
250 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
251 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
256 l1tf_vmx_mitigation = l1tf;
258 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
259 static_branch_enable(&vmx_l1d_should_flush);
261 static_branch_disable(&vmx_l1d_should_flush);
263 if (l1tf == VMENTER_L1D_FLUSH_COND)
264 static_branch_enable(&vmx_l1d_flush_cond);
266 static_branch_disable(&vmx_l1d_flush_cond);
270 static int vmentry_l1d_flush_parse(const char *s)
275 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
276 if (vmentry_l1d_param[i].for_parse &&
277 sysfs_streq(s, vmentry_l1d_param[i].option))
284 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
288 l1tf = vmentry_l1d_flush_parse(s);
292 if (!boot_cpu_has(X86_BUG_L1TF))
296 * Has vmx_init() run already? If not then this is the pre init
297 * parameter parsing. In that case just store the value and let
298 * vmx_init() do the proper setup after enable_ept has been
301 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
302 vmentry_l1d_flush_param = l1tf;
306 mutex_lock(&vmx_l1d_flush_mutex);
307 ret = vmx_setup_l1d_flush(l1tf);
308 mutex_unlock(&vmx_l1d_flush_mutex);
312 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
314 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
315 return sprintf(s, "???\n");
317 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
320 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
321 .set = vmentry_l1d_flush_set,
322 .get = vmentry_l1d_flush_get,
324 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
326 static bool guest_state_valid(struct kvm_vcpu *vcpu);
327 static u32 vmx_segment_access_rights(struct kvm_segment *var);
328 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
331 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
332 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
334 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
335 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
337 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
340 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
341 * can find which vCPU should be waken up.
343 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
344 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
346 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
347 static DEFINE_SPINLOCK(vmx_vpid_lock);
349 struct vmcs_config vmcs_config;
350 struct vmx_capability vmx_capability;
352 #define VMX_SEGMENT_FIELD(seg) \
353 [VCPU_SREG_##seg] = { \
354 .selector = GUEST_##seg##_SELECTOR, \
355 .base = GUEST_##seg##_BASE, \
356 .limit = GUEST_##seg##_LIMIT, \
357 .ar_bytes = GUEST_##seg##_AR_BYTES, \
360 static const struct kvm_vmx_segment_field {
365 } kvm_vmx_segment_fields[] = {
366 VMX_SEGMENT_FIELD(CS),
367 VMX_SEGMENT_FIELD(DS),
368 VMX_SEGMENT_FIELD(ES),
369 VMX_SEGMENT_FIELD(FS),
370 VMX_SEGMENT_FIELD(GS),
371 VMX_SEGMENT_FIELD(SS),
372 VMX_SEGMENT_FIELD(TR),
373 VMX_SEGMENT_FIELD(LDTR),
379 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
380 * will emulate SYSCALL in legacy mode if the vendor string in guest
381 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
382 * support this emulation, IA32_STAR must always be included in
383 * vmx_msr_index[], even in i386 builds.
385 const u32 vmx_msr_index[] = {
387 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
389 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
392 #if IS_ENABLED(CONFIG_HYPERV)
393 static bool __read_mostly enlightened_vmcs = true;
394 module_param(enlightened_vmcs, bool, 0444);
396 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
397 static void check_ept_pointer_match(struct kvm *kvm)
399 struct kvm_vcpu *vcpu;
400 u64 tmp_eptp = INVALID_PAGE;
403 kvm_for_each_vcpu(i, vcpu, kvm) {
404 if (!VALID_PAGE(tmp_eptp)) {
405 tmp_eptp = to_vmx(vcpu)->ept_pointer;
406 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
407 to_kvm_vmx(kvm)->ept_pointers_match
408 = EPT_POINTERS_MISMATCH;
413 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
416 static int vmx_hv_remote_flush_tlb(struct kvm *kvm)
418 struct kvm_vcpu *vcpu;
419 int ret = -ENOTSUPP, i;
421 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
423 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
424 check_ept_pointer_match(kvm);
427 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs the address of the
428 * base of EPT PML4 table, strip off EPT configuration information.
429 * If ept_pointer is invalid pointer, bypass the flush request.
431 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
432 kvm_for_each_vcpu(i, vcpu, kvm) {
433 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
435 if (!VALID_PAGE(ept_pointer))
438 ret |= hyperv_flush_guest_mapping(
439 ept_pointer & PAGE_MASK);
442 ret = hyperv_flush_guest_mapping(
443 to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer & PAGE_MASK);
446 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
449 #endif /* IS_ENABLED(CONFIG_HYPERV) */
452 * Comment's format: document - errata name - stepping - processor name.
454 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
456 static u32 vmx_preemption_cpu_tfms[] = {
457 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
459 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
460 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
461 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
463 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
465 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
466 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
468 * 320767.pdf - AAP86 - B1 -
469 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
472 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
474 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
476 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
478 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
479 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
480 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
482 /* Xeon E3-1220 V2 */
486 static inline bool cpu_has_broken_vmx_preemption_timer(void)
488 u32 eax = cpuid_eax(0x00000001), i;
490 /* Clear the reserved bits */
491 eax &= ~(0x3U << 14 | 0xfU << 28);
492 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
493 if (eax == vmx_preemption_cpu_tfms[i])
499 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
501 return flexpriority_enabled && lapic_in_kernel(vcpu);
504 static inline bool report_flexpriority(void)
506 return flexpriority_enabled;
509 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
513 for (i = 0; i < vmx->nmsrs; ++i)
514 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
519 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
523 i = __find_msr_index(vmx, msr);
525 return &vmx->guest_msrs[i];
529 void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
531 vmcs_clear(loaded_vmcs->vmcs);
532 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
533 vmcs_clear(loaded_vmcs->shadow_vmcs);
534 loaded_vmcs->cpu = -1;
535 loaded_vmcs->launched = 0;
538 #ifdef CONFIG_KEXEC_CORE
540 * This bitmap is used to indicate whether the vmclear
541 * operation is enabled on all cpus. All disabled by
544 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
546 static inline void crash_enable_local_vmclear(int cpu)
548 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
551 static inline void crash_disable_local_vmclear(int cpu)
553 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
556 static inline int crash_local_vmclear_enabled(int cpu)
558 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
561 static void crash_vmclear_local_loaded_vmcss(void)
563 int cpu = raw_smp_processor_id();
564 struct loaded_vmcs *v;
566 if (!crash_local_vmclear_enabled(cpu))
569 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
570 loaded_vmcss_on_cpu_link)
574 static inline void crash_enable_local_vmclear(int cpu) { }
575 static inline void crash_disable_local_vmclear(int cpu) { }
576 #endif /* CONFIG_KEXEC_CORE */
578 static void __loaded_vmcs_clear(void *arg)
580 struct loaded_vmcs *loaded_vmcs = arg;
581 int cpu = raw_smp_processor_id();
583 if (loaded_vmcs->cpu != cpu)
584 return; /* vcpu migration can race with cpu offline */
585 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
586 per_cpu(current_vmcs, cpu) = NULL;
587 crash_disable_local_vmclear(cpu);
588 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
591 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
592 * is before setting loaded_vmcs->vcpu to -1 which is done in
593 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
594 * then adds the vmcs into percpu list before it is deleted.
598 loaded_vmcs_init(loaded_vmcs);
599 crash_enable_local_vmclear(cpu);
602 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
604 int cpu = loaded_vmcs->cpu;
607 smp_call_function_single(cpu,
608 __loaded_vmcs_clear, loaded_vmcs, 1);
611 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
615 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
617 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
618 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
619 vmx->segment_cache.bitmask = 0;
621 ret = vmx->segment_cache.bitmask & mask;
622 vmx->segment_cache.bitmask |= mask;
626 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
628 u16 *p = &vmx->segment_cache.seg[seg].selector;
630 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
631 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
635 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
637 ulong *p = &vmx->segment_cache.seg[seg].base;
639 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
640 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
644 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
646 u32 *p = &vmx->segment_cache.seg[seg].limit;
648 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
649 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
653 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
655 u32 *p = &vmx->segment_cache.seg[seg].ar;
657 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
658 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
662 void update_exception_bitmap(struct kvm_vcpu *vcpu)
666 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
667 (1u << DB_VECTOR) | (1u << AC_VECTOR);
669 * Guest access to VMware backdoor ports could legitimately
670 * trigger #GP because of TSS I/O permission bitmap.
671 * We intercept those #GP and allow access to them anyway
674 if (enable_vmware_backdoor)
675 eb |= (1u << GP_VECTOR);
676 if ((vcpu->guest_debug &
677 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
678 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
679 eb |= 1u << BP_VECTOR;
680 if (to_vmx(vcpu)->rmode.vm86_active)
683 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
685 /* When we are running a nested L2 guest and L1 specified for it a
686 * certain exception bitmap, we must trap the same exceptions and pass
687 * them to L1. When running L2, we will only handle the exceptions
688 * specified above if L1 did not want them.
690 if (is_guest_mode(vcpu))
691 eb |= get_vmcs12(vcpu)->exception_bitmap;
693 vmcs_write32(EXCEPTION_BITMAP, eb);
697 * Check if MSR is intercepted for currently loaded MSR bitmap.
699 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
701 unsigned long *msr_bitmap;
702 int f = sizeof(unsigned long);
704 if (!cpu_has_vmx_msr_bitmap())
707 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
710 return !!test_bit(msr, msr_bitmap + 0x800 / f);
711 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
713 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
719 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
720 unsigned long entry, unsigned long exit)
722 vm_entry_controls_clearbit(vmx, entry);
723 vm_exit_controls_clearbit(vmx, exit);
726 static int find_msr(struct vmx_msrs *m, unsigned int msr)
730 for (i = 0; i < m->nr; ++i) {
731 if (m->val[i].index == msr)
737 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
740 struct msr_autoload *m = &vmx->msr_autoload;
744 if (cpu_has_load_ia32_efer()) {
745 clear_atomic_switch_msr_special(vmx,
746 VM_ENTRY_LOAD_IA32_EFER,
747 VM_EXIT_LOAD_IA32_EFER);
751 case MSR_CORE_PERF_GLOBAL_CTRL:
752 if (cpu_has_load_perf_global_ctrl()) {
753 clear_atomic_switch_msr_special(vmx,
754 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
755 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
760 i = find_msr(&m->guest, msr);
764 m->guest.val[i] = m->guest.val[m->guest.nr];
765 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
768 i = find_msr(&m->host, msr);
773 m->host.val[i] = m->host.val[m->host.nr];
774 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
777 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
778 unsigned long entry, unsigned long exit,
779 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
780 u64 guest_val, u64 host_val)
782 vmcs_write64(guest_val_vmcs, guest_val);
783 if (host_val_vmcs != HOST_IA32_EFER)
784 vmcs_write64(host_val_vmcs, host_val);
785 vm_entry_controls_setbit(vmx, entry);
786 vm_exit_controls_setbit(vmx, exit);
789 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
790 u64 guest_val, u64 host_val, bool entry_only)
793 struct msr_autoload *m = &vmx->msr_autoload;
797 if (cpu_has_load_ia32_efer()) {
798 add_atomic_switch_msr_special(vmx,
799 VM_ENTRY_LOAD_IA32_EFER,
800 VM_EXIT_LOAD_IA32_EFER,
803 guest_val, host_val);
807 case MSR_CORE_PERF_GLOBAL_CTRL:
808 if (cpu_has_load_perf_global_ctrl()) {
809 add_atomic_switch_msr_special(vmx,
810 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
811 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
812 GUEST_IA32_PERF_GLOBAL_CTRL,
813 HOST_IA32_PERF_GLOBAL_CTRL,
814 guest_val, host_val);
818 case MSR_IA32_PEBS_ENABLE:
819 /* PEBS needs a quiescent period after being disabled (to write
820 * a record). Disabling PEBS through VMX MSR swapping doesn't
821 * provide that period, so a CPU could write host's record into
824 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
827 i = find_msr(&m->guest, msr);
829 j = find_msr(&m->host, msr);
831 if (i == NR_AUTOLOAD_MSRS || j == NR_AUTOLOAD_MSRS) {
832 printk_once(KERN_WARNING "Not enough msr switch entries. "
833 "Can't add msr %x\n", msr);
838 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
840 m->guest.val[i].index = msr;
841 m->guest.val[i].value = guest_val;
848 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
850 m->host.val[j].index = msr;
851 m->host.val[j].value = host_val;
854 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
856 u64 guest_efer = vmx->vcpu.arch.efer;
861 * NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
862 * host CPUID is more efficient than testing guest CPUID
863 * or CR4. Host SMEP is anyway a requirement for guest SMEP.
865 if (boot_cpu_has(X86_FEATURE_SMEP))
866 guest_efer |= EFER_NX;
867 else if (!(guest_efer & EFER_NX))
868 ignore_bits |= EFER_NX;
872 * LMA and LME handled by hardware; SCE meaningless outside long mode.
874 ignore_bits |= EFER_SCE;
876 ignore_bits |= EFER_LMA | EFER_LME;
877 /* SCE is meaningful only in long mode on Intel */
878 if (guest_efer & EFER_LMA)
879 ignore_bits &= ~(u64)EFER_SCE;
883 * On EPT, we can't emulate NX, so we must switch EFER atomically.
884 * On CPUs that support "load IA32_EFER", always switch EFER
885 * atomically, since it's faster than switching it manually.
887 if (cpu_has_load_ia32_efer() ||
888 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
889 if (!(guest_efer & EFER_LMA))
890 guest_efer &= ~EFER_LME;
891 if (guest_efer != host_efer)
892 add_atomic_switch_msr(vmx, MSR_EFER,
893 guest_efer, host_efer, false);
895 clear_atomic_switch_msr(vmx, MSR_EFER);
898 clear_atomic_switch_msr(vmx, MSR_EFER);
900 guest_efer &= ~ignore_bits;
901 guest_efer |= host_efer & ignore_bits;
903 vmx->guest_msrs[efer_offset].data = guest_efer;
904 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
912 * On 32-bit kernels, VM exits still load the FS and GS bases from the
913 * VMCS rather than the segment table. KVM uses this helper to figure
914 * out the current bases to poke them into the VMCS before entry.
916 static unsigned long segment_base(u16 selector)
918 struct desc_struct *table;
921 if (!(selector & ~SEGMENT_RPL_MASK))
924 table = get_current_gdt_ro();
926 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
927 u16 ldt_selector = kvm_read_ldt();
929 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
932 table = (struct desc_struct *)segment_base(ldt_selector);
934 v = get_desc_base(&table[selector >> 3]);
939 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
941 struct vcpu_vmx *vmx = to_vmx(vcpu);
942 struct vmcs_host_state *host_state;
944 int cpu = raw_smp_processor_id();
946 unsigned long fs_base, gs_base;
950 vmx->req_immediate_exit = false;
953 * Note that guest MSRs to be saved/restored can also be changed
954 * when guest state is loaded. This happens when guest transitions
955 * to/from long-mode by setting MSR_EFER.LMA.
957 if (!vmx->loaded_cpu_state || vmx->guest_msrs_dirty) {
958 vmx->guest_msrs_dirty = false;
959 for (i = 0; i < vmx->save_nmsrs; ++i)
960 kvm_set_shared_msr(vmx->guest_msrs[i].index,
961 vmx->guest_msrs[i].data,
962 vmx->guest_msrs[i].mask);
966 if (vmx->loaded_cpu_state)
969 vmx->loaded_cpu_state = vmx->loaded_vmcs;
970 host_state = &vmx->loaded_cpu_state->host_state;
973 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
974 * allow segment selectors with cpl > 0 or ti == 1.
976 host_state->ldt_sel = kvm_read_ldt();
979 savesegment(ds, host_state->ds_sel);
980 savesegment(es, host_state->es_sel);
982 gs_base = cpu_kernelmode_gs_base(cpu);
983 if (likely(is_64bit_mm(current->mm))) {
985 fs_sel = current->thread.fsindex;
986 gs_sel = current->thread.gsindex;
987 fs_base = current->thread.fsbase;
988 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
990 savesegment(fs, fs_sel);
991 savesegment(gs, gs_sel);
992 fs_base = read_msr(MSR_FS_BASE);
993 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
996 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
998 savesegment(fs, fs_sel);
999 savesegment(gs, gs_sel);
1000 fs_base = segment_base(fs_sel);
1001 gs_base = segment_base(gs_sel);
1004 if (unlikely(fs_sel != host_state->fs_sel)) {
1006 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1008 vmcs_write16(HOST_FS_SELECTOR, 0);
1009 host_state->fs_sel = fs_sel;
1011 if (unlikely(gs_sel != host_state->gs_sel)) {
1013 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1015 vmcs_write16(HOST_GS_SELECTOR, 0);
1016 host_state->gs_sel = gs_sel;
1018 if (unlikely(fs_base != host_state->fs_base)) {
1019 vmcs_writel(HOST_FS_BASE, fs_base);
1020 host_state->fs_base = fs_base;
1022 if (unlikely(gs_base != host_state->gs_base)) {
1023 vmcs_writel(HOST_GS_BASE, gs_base);
1024 host_state->gs_base = gs_base;
1028 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1030 struct vmcs_host_state *host_state;
1032 if (!vmx->loaded_cpu_state)
1035 WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
1036 host_state = &vmx->loaded_cpu_state->host_state;
1038 ++vmx->vcpu.stat.host_state_reload;
1039 vmx->loaded_cpu_state = NULL;
1041 #ifdef CONFIG_X86_64
1042 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1044 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1045 kvm_load_ldt(host_state->ldt_sel);
1046 #ifdef CONFIG_X86_64
1047 load_gs_index(host_state->gs_sel);
1049 loadsegment(gs, host_state->gs_sel);
1052 if (host_state->fs_sel & 7)
1053 loadsegment(fs, host_state->fs_sel);
1054 #ifdef CONFIG_X86_64
1055 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1056 loadsegment(ds, host_state->ds_sel);
1057 loadsegment(es, host_state->es_sel);
1060 invalidate_tss_limit();
1061 #ifdef CONFIG_X86_64
1062 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1064 load_fixmap_gdt(raw_smp_processor_id());
1067 #ifdef CONFIG_X86_64
1068 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1071 if (vmx->loaded_cpu_state)
1072 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1074 return vmx->msr_guest_kernel_gs_base;
1077 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1080 if (vmx->loaded_cpu_state)
1081 wrmsrl(MSR_KERNEL_GS_BASE, data);
1083 vmx->msr_guest_kernel_gs_base = data;
1087 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1089 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1090 struct pi_desc old, new;
1094 * In case of hot-plug or hot-unplug, we may have to undo
1095 * vmx_vcpu_pi_put even if there is no assigned device. And we
1096 * always keep PI.NDST up to date for simplicity: it makes the
1097 * code easier, and CPU migration is not a fast path.
1099 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1103 * First handle the simple case where no cmpxchg is necessary; just
1104 * allow posting non-urgent interrupts.
1106 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
1107 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
1108 * expects the VCPU to be on the blocked_vcpu_list that matches
1111 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
1113 pi_clear_sn(pi_desc);
1117 /* The full case. */
1119 old.control = new.control = pi_desc->control;
1121 dest = cpu_physical_id(cpu);
1123 if (x2apic_enabled())
1126 new.ndst = (dest << 8) & 0xFF00;
1129 } while (cmpxchg64(&pi_desc->control, old.control,
1130 new.control) != old.control);
1134 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1135 * vcpu mutex is already taken.
1137 void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1139 struct vcpu_vmx *vmx = to_vmx(vcpu);
1140 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1142 if (!already_loaded) {
1143 loaded_vmcs_clear(vmx->loaded_vmcs);
1144 local_irq_disable();
1145 crash_disable_local_vmclear(cpu);
1148 * Read loaded_vmcs->cpu should be before fetching
1149 * loaded_vmcs->loaded_vmcss_on_cpu_link.
1150 * See the comments in __loaded_vmcs_clear().
1154 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1155 &per_cpu(loaded_vmcss_on_cpu, cpu));
1156 crash_enable_local_vmclear(cpu);
1160 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1161 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1162 vmcs_load(vmx->loaded_vmcs->vmcs);
1163 indirect_branch_prediction_barrier();
1166 if (!already_loaded) {
1167 void *gdt = get_current_gdt_ro();
1168 unsigned long sysenter_esp;
1170 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1173 * Linux uses per-cpu TSS and GDT, so set these when switching
1174 * processors. See 22.2.4.
1176 vmcs_writel(HOST_TR_BASE,
1177 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1178 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1181 * VM exits change the host TR limit to 0x67 after a VM
1182 * exit. This is okay, since 0x67 covers everything except
1183 * the IO bitmap and have have code to handle the IO bitmap
1184 * being lost after a VM exit.
1186 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
1188 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1189 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1191 vmx->loaded_vmcs->cpu = cpu;
1194 /* Setup TSC multiplier */
1195 if (kvm_has_tsc_control &&
1196 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1197 decache_tsc_multiplier(vmx);
1199 vmx_vcpu_pi_load(vcpu, cpu);
1200 vmx->host_pkru = read_pkru();
1201 vmx->host_debugctlmsr = get_debugctlmsr();
1204 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1206 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1208 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1209 !irq_remapping_cap(IRQ_POSTING_CAP) ||
1210 !kvm_vcpu_apicv_active(vcpu))
1213 /* Set SN when the vCPU is preempted */
1214 if (vcpu->preempted)
1218 void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1220 vmx_vcpu_pi_put(vcpu);
1222 vmx_prepare_switch_to_host(to_vmx(vcpu));
1225 static bool emulation_required(struct kvm_vcpu *vcpu)
1227 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1230 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1232 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1234 unsigned long rflags, save_rflags;
1236 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1237 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1238 rflags = vmcs_readl(GUEST_RFLAGS);
1239 if (to_vmx(vcpu)->rmode.vm86_active) {
1240 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1241 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1242 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1244 to_vmx(vcpu)->rflags = rflags;
1246 return to_vmx(vcpu)->rflags;
1249 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1251 unsigned long old_rflags = vmx_get_rflags(vcpu);
1253 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1254 to_vmx(vcpu)->rflags = rflags;
1255 if (to_vmx(vcpu)->rmode.vm86_active) {
1256 to_vmx(vcpu)->rmode.save_rflags = rflags;
1257 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1259 vmcs_writel(GUEST_RFLAGS, rflags);
1261 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
1262 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
1265 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1267 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1270 if (interruptibility & GUEST_INTR_STATE_STI)
1271 ret |= KVM_X86_SHADOW_INT_STI;
1272 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1273 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1278 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1280 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1281 u32 interruptibility = interruptibility_old;
1283 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1285 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1286 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1287 else if (mask & KVM_X86_SHADOW_INT_STI)
1288 interruptibility |= GUEST_INTR_STATE_STI;
1290 if ((interruptibility != interruptibility_old))
1291 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1294 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1298 rip = kvm_rip_read(vcpu);
1299 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1300 kvm_rip_write(vcpu, rip);
1302 /* skipping an emulated instruction also counts */
1303 vmx_set_interrupt_shadow(vcpu, 0);
1306 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1309 * Ensure that we clear the HLT state in the VMCS. We don't need to
1310 * explicitly skip the instruction because if the HLT state is set,
1311 * then the instruction is already executing and RIP has already been
1314 if (kvm_hlt_in_guest(vcpu->kvm) &&
1315 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1316 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1319 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1321 struct vcpu_vmx *vmx = to_vmx(vcpu);
1322 unsigned nr = vcpu->arch.exception.nr;
1323 bool has_error_code = vcpu->arch.exception.has_error_code;
1324 u32 error_code = vcpu->arch.exception.error_code;
1325 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1327 kvm_deliver_exception_payload(vcpu);
1329 if (has_error_code) {
1330 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1331 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1334 if (vmx->rmode.vm86_active) {
1336 if (kvm_exception_is_soft(nr))
1337 inc_eip = vcpu->arch.event_exit_inst_len;
1338 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1339 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1343 WARN_ON_ONCE(vmx->emulation_required);
1345 if (kvm_exception_is_soft(nr)) {
1346 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1347 vmx->vcpu.arch.event_exit_inst_len);
1348 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1350 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1352 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1354 vmx_clear_hlt(vcpu);
1357 static bool vmx_rdtscp_supported(void)
1359 return cpu_has_vmx_rdtscp();
1362 static bool vmx_invpcid_supported(void)
1364 return cpu_has_vmx_invpcid();
1368 * Swap MSR entry in host/guest MSR entry array.
1370 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1372 struct shared_msr_entry tmp;
1374 tmp = vmx->guest_msrs[to];
1375 vmx->guest_msrs[to] = vmx->guest_msrs[from];
1376 vmx->guest_msrs[from] = tmp;
1380 * Set up the vmcs to automatically save and restore system
1381 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1382 * mode, as fiddling with msrs is very expensive.
1384 static void setup_msrs(struct vcpu_vmx *vmx)
1386 int save_nmsrs, index;
1389 #ifdef CONFIG_X86_64
1391 * The SYSCALL MSRs are only needed on long mode guests, and only
1392 * when EFER.SCE is set.
1394 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1395 index = __find_msr_index(vmx, MSR_STAR);
1397 move_msr_up(vmx, index, save_nmsrs++);
1398 index = __find_msr_index(vmx, MSR_LSTAR);
1400 move_msr_up(vmx, index, save_nmsrs++);
1401 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1403 move_msr_up(vmx, index, save_nmsrs++);
1406 index = __find_msr_index(vmx, MSR_EFER);
1407 if (index >= 0 && update_transition_efer(vmx, index))
1408 move_msr_up(vmx, index, save_nmsrs++);
1409 index = __find_msr_index(vmx, MSR_TSC_AUX);
1410 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1411 move_msr_up(vmx, index, save_nmsrs++);
1413 vmx->save_nmsrs = save_nmsrs;
1414 vmx->guest_msrs_dirty = true;
1416 if (cpu_has_vmx_msr_bitmap())
1417 vmx_update_msr_bitmap(&vmx->vcpu);
1420 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1422 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1424 if (is_guest_mode(vcpu) &&
1425 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1426 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
1428 return vcpu->arch.tsc_offset;
1431 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1433 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1434 u64 g_tsc_offset = 0;
1437 * We're here if L1 chose not to trap WRMSR to TSC. According
1438 * to the spec, this should set L1's TSC; The offset that L1
1439 * set for L2 remains unchanged, and still needs to be added
1440 * to the newly set TSC to get L2's TSC.
1442 if (is_guest_mode(vcpu) &&
1443 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1444 g_tsc_offset = vmcs12->tsc_offset;
1446 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1447 vcpu->arch.tsc_offset - g_tsc_offset,
1449 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1450 return offset + g_tsc_offset;
1454 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1455 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1456 * all guests if the "nested" module option is off, and can also be disabled
1457 * for a single guest by disabling its VMX cpuid bit.
1459 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1461 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1464 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1467 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1469 return !(val & ~valid_bits);
1472 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1474 switch (msr->index) {
1475 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1478 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1487 * Reads an msr value (of 'msr_index') into 'pdata'.
1488 * Returns 0 on success, non-0 otherwise.
1489 * Assumes vcpu_load() was already called.
1491 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1493 struct vcpu_vmx *vmx = to_vmx(vcpu);
1494 struct shared_msr_entry *msr;
1496 switch (msr_info->index) {
1497 #ifdef CONFIG_X86_64
1499 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1502 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1504 case MSR_KERNEL_GS_BASE:
1505 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1509 return kvm_get_msr_common(vcpu, msr_info);
1510 case MSR_IA32_SPEC_CTRL:
1511 if (!msr_info->host_initiated &&
1512 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1515 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1517 case MSR_IA32_ARCH_CAPABILITIES:
1518 if (!msr_info->host_initiated &&
1519 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
1521 msr_info->data = to_vmx(vcpu)->arch_capabilities;
1523 case MSR_IA32_SYSENTER_CS:
1524 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1526 case MSR_IA32_SYSENTER_EIP:
1527 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1529 case MSR_IA32_SYSENTER_ESP:
1530 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1532 case MSR_IA32_BNDCFGS:
1533 if (!kvm_mpx_supported() ||
1534 (!msr_info->host_initiated &&
1535 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1537 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1539 case MSR_IA32_MCG_EXT_CTL:
1540 if (!msr_info->host_initiated &&
1541 !(vmx->msr_ia32_feature_control &
1542 FEATURE_CONTROL_LMCE))
1544 msr_info->data = vcpu->arch.mcg_ext_ctl;
1546 case MSR_IA32_FEATURE_CONTROL:
1547 msr_info->data = vmx->msr_ia32_feature_control;
1549 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1550 if (!nested_vmx_allowed(vcpu))
1552 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1555 if (!vmx_xsaves_supported())
1557 msr_info->data = vcpu->arch.ia32_xss;
1560 if (!msr_info->host_initiated &&
1561 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1563 /* Otherwise falls through */
1565 msr = find_msr_entry(vmx, msr_info->index);
1567 msr_info->data = msr->data;
1570 return kvm_get_msr_common(vcpu, msr_info);
1577 * Writes msr value into into the appropriate "register".
1578 * Returns 0 on success, non-0 otherwise.
1579 * Assumes vcpu_load() was already called.
1581 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1583 struct vcpu_vmx *vmx = to_vmx(vcpu);
1584 struct shared_msr_entry *msr;
1586 u32 msr_index = msr_info->index;
1587 u64 data = msr_info->data;
1589 switch (msr_index) {
1591 ret = kvm_set_msr_common(vcpu, msr_info);
1593 #ifdef CONFIG_X86_64
1595 vmx_segment_cache_clear(vmx);
1596 vmcs_writel(GUEST_FS_BASE, data);
1599 vmx_segment_cache_clear(vmx);
1600 vmcs_writel(GUEST_GS_BASE, data);
1602 case MSR_KERNEL_GS_BASE:
1603 vmx_write_guest_kernel_gs_base(vmx, data);
1606 case MSR_IA32_SYSENTER_CS:
1607 vmcs_write32(GUEST_SYSENTER_CS, data);
1609 case MSR_IA32_SYSENTER_EIP:
1610 vmcs_writel(GUEST_SYSENTER_EIP, data);
1612 case MSR_IA32_SYSENTER_ESP:
1613 vmcs_writel(GUEST_SYSENTER_ESP, data);
1615 case MSR_IA32_BNDCFGS:
1616 if (!kvm_mpx_supported() ||
1617 (!msr_info->host_initiated &&
1618 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1620 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
1621 (data & MSR_IA32_BNDCFGS_RSVD))
1623 vmcs_write64(GUEST_BNDCFGS, data);
1625 case MSR_IA32_SPEC_CTRL:
1626 if (!msr_info->host_initiated &&
1627 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1630 /* The STIBP bit doesn't fault even if it's not advertised */
1631 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
1634 vmx->spec_ctrl = data;
1641 * When it's written (to non-zero) for the first time, pass
1645 * The handling of the MSR bitmap for L2 guests is done in
1646 * nested_vmx_merge_msr_bitmap. We should not touch the
1647 * vmcs02.msr_bitmap here since it gets completely overwritten
1648 * in the merging. We update the vmcs01 here for L1 as well
1649 * since it will end up touching the MSR anyway now.
1651 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
1655 case MSR_IA32_PRED_CMD:
1656 if (!msr_info->host_initiated &&
1657 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1660 if (data & ~PRED_CMD_IBPB)
1666 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
1670 * When it's written (to non-zero) for the first time, pass
1674 * The handling of the MSR bitmap for L2 guests is done in
1675 * nested_vmx_merge_msr_bitmap. We should not touch the
1676 * vmcs02.msr_bitmap here since it gets completely overwritten
1679 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
1682 case MSR_IA32_ARCH_CAPABILITIES:
1683 if (!msr_info->host_initiated)
1685 vmx->arch_capabilities = data;
1687 case MSR_IA32_CR_PAT:
1688 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
1689 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
1691 vmcs_write64(GUEST_IA32_PAT, data);
1692 vcpu->arch.pat = data;
1695 ret = kvm_set_msr_common(vcpu, msr_info);
1697 case MSR_IA32_TSC_ADJUST:
1698 ret = kvm_set_msr_common(vcpu, msr_info);
1700 case MSR_IA32_MCG_EXT_CTL:
1701 if ((!msr_info->host_initiated &&
1702 !(to_vmx(vcpu)->msr_ia32_feature_control &
1703 FEATURE_CONTROL_LMCE)) ||
1704 (data & ~MCG_EXT_CTL_LMCE_EN))
1706 vcpu->arch.mcg_ext_ctl = data;
1708 case MSR_IA32_FEATURE_CONTROL:
1709 if (!vmx_feature_control_msr_valid(vcpu, data) ||
1710 (to_vmx(vcpu)->msr_ia32_feature_control &
1711 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
1713 vmx->msr_ia32_feature_control = data;
1714 if (msr_info->host_initiated && data == 0)
1715 vmx_leave_nested(vcpu);
1717 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1718 if (!msr_info->host_initiated)
1719 return 1; /* they are read-only */
1720 if (!nested_vmx_allowed(vcpu))
1722 return vmx_set_vmx_msr(vcpu, msr_index, data);
1724 if (!vmx_xsaves_supported())
1727 * The only supported bit as of Skylake is bit 8, but
1728 * it is not supported on KVM.
1732 vcpu->arch.ia32_xss = data;
1733 if (vcpu->arch.ia32_xss != host_xss)
1734 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
1735 vcpu->arch.ia32_xss, host_xss, false);
1737 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
1740 if (!msr_info->host_initiated &&
1741 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1743 /* Check reserved bit, higher 32 bits should be zero */
1744 if ((data >> 32) != 0)
1746 /* Otherwise falls through */
1748 msr = find_msr_entry(vmx, msr_index);
1750 u64 old_msr_data = msr->data;
1752 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
1754 ret = kvm_set_shared_msr(msr->index, msr->data,
1758 msr->data = old_msr_data;
1762 ret = kvm_set_msr_common(vcpu, msr_info);
1768 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1770 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
1773 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
1776 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
1778 case VCPU_EXREG_PDPTR:
1780 ept_save_pdptrs(vcpu);
1787 static __init int cpu_has_kvm_support(void)
1789 return cpu_has_vmx();
1792 static __init int vmx_disabled_by_bios(void)
1796 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
1797 if (msr & FEATURE_CONTROL_LOCKED) {
1798 /* launched w/ TXT and VMX disabled */
1799 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
1802 /* launched w/o TXT and VMX only enabled w/ TXT */
1803 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
1804 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
1805 && !tboot_enabled()) {
1806 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
1807 "activate TXT before enabling KVM\n");
1810 /* launched w/o TXT and VMX disabled */
1811 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
1812 && !tboot_enabled())
1819 static void kvm_cpu_vmxon(u64 addr)
1821 cr4_set_bits(X86_CR4_VMXE);
1822 intel_pt_handle_vmx(1);
1824 asm volatile ("vmxon %0" : : "m"(addr));
1827 static int hardware_enable(void)
1829 int cpu = raw_smp_processor_id();
1830 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1833 if (cr4_read_shadow() & X86_CR4_VMXE)
1837 * This can happen if we hot-added a CPU but failed to allocate
1838 * VP assist page for it.
1840 if (static_branch_unlikely(&enable_evmcs) &&
1841 !hv_get_vp_assist_page(cpu))
1844 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
1845 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
1846 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
1849 * Now we can enable the vmclear operation in kdump
1850 * since the loaded_vmcss_on_cpu list on this cpu
1851 * has been initialized.
1853 * Though the cpu is not in VMX operation now, there
1854 * is no problem to enable the vmclear operation
1855 * for the loaded_vmcss_on_cpu list is empty!
1857 crash_enable_local_vmclear(cpu);
1859 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
1861 test_bits = FEATURE_CONTROL_LOCKED;
1862 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
1863 if (tboot_enabled())
1864 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
1866 if ((old & test_bits) != test_bits) {
1867 /* enable and lock */
1868 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
1870 kvm_cpu_vmxon(phys_addr);
1877 static void vmclear_local_loaded_vmcss(void)
1879 int cpu = raw_smp_processor_id();
1880 struct loaded_vmcs *v, *n;
1882 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
1883 loaded_vmcss_on_cpu_link)
1884 __loaded_vmcs_clear(v);
1888 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
1891 static void kvm_cpu_vmxoff(void)
1893 asm volatile (__ex("vmxoff"));
1895 intel_pt_handle_vmx(0);
1896 cr4_clear_bits(X86_CR4_VMXE);
1899 static void hardware_disable(void)
1901 vmclear_local_loaded_vmcss();
1905 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
1906 u32 msr, u32 *result)
1908 u32 vmx_msr_low, vmx_msr_high;
1909 u32 ctl = ctl_min | ctl_opt;
1911 rdmsr(msr, vmx_msr_low, vmx_msr_high);
1913 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
1914 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
1916 /* Ensure minimum (required) set of control bits are supported. */
1924 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
1925 struct vmx_capability *vmx_cap)
1927 u32 vmx_msr_low, vmx_msr_high;
1928 u32 min, opt, min2, opt2;
1929 u32 _pin_based_exec_control = 0;
1930 u32 _cpu_based_exec_control = 0;
1931 u32 _cpu_based_2nd_exec_control = 0;
1932 u32 _vmexit_control = 0;
1933 u32 _vmentry_control = 0;
1935 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
1936 min = CPU_BASED_HLT_EXITING |
1937 #ifdef CONFIG_X86_64
1938 CPU_BASED_CR8_LOAD_EXITING |
1939 CPU_BASED_CR8_STORE_EXITING |
1941 CPU_BASED_CR3_LOAD_EXITING |
1942 CPU_BASED_CR3_STORE_EXITING |
1943 CPU_BASED_UNCOND_IO_EXITING |
1944 CPU_BASED_MOV_DR_EXITING |
1945 CPU_BASED_USE_TSC_OFFSETING |
1946 CPU_BASED_MWAIT_EXITING |
1947 CPU_BASED_MONITOR_EXITING |
1948 CPU_BASED_INVLPG_EXITING |
1949 CPU_BASED_RDPMC_EXITING;
1951 opt = CPU_BASED_TPR_SHADOW |
1952 CPU_BASED_USE_MSR_BITMAPS |
1953 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1954 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
1955 &_cpu_based_exec_control) < 0)
1957 #ifdef CONFIG_X86_64
1958 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
1959 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
1960 ~CPU_BASED_CR8_STORE_EXITING;
1962 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
1964 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
1965 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
1966 SECONDARY_EXEC_WBINVD_EXITING |
1967 SECONDARY_EXEC_ENABLE_VPID |
1968 SECONDARY_EXEC_ENABLE_EPT |
1969 SECONDARY_EXEC_UNRESTRICTED_GUEST |
1970 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
1971 SECONDARY_EXEC_DESC |
1972 SECONDARY_EXEC_RDTSCP |
1973 SECONDARY_EXEC_ENABLE_INVPCID |
1974 SECONDARY_EXEC_APIC_REGISTER_VIRT |
1975 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
1976 SECONDARY_EXEC_SHADOW_VMCS |
1977 SECONDARY_EXEC_XSAVES |
1978 SECONDARY_EXEC_RDSEED_EXITING |
1979 SECONDARY_EXEC_RDRAND_EXITING |
1980 SECONDARY_EXEC_ENABLE_PML |
1981 SECONDARY_EXEC_TSC_SCALING |
1982 SECONDARY_EXEC_PT_USE_GPA |
1983 SECONDARY_EXEC_PT_CONCEAL_VMX |
1984 SECONDARY_EXEC_ENABLE_VMFUNC |
1985 SECONDARY_EXEC_ENCLS_EXITING;
1986 if (adjust_vmx_controls(min2, opt2,
1987 MSR_IA32_VMX_PROCBASED_CTLS2,
1988 &_cpu_based_2nd_exec_control) < 0)
1991 #ifndef CONFIG_X86_64
1992 if (!(_cpu_based_2nd_exec_control &
1993 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
1994 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
1997 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
1998 _cpu_based_2nd_exec_control &= ~(
1999 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2000 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2001 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2003 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2004 &vmx_cap->ept, &vmx_cap->vpid);
2006 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2007 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2009 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2010 CPU_BASED_CR3_STORE_EXITING |
2011 CPU_BASED_INVLPG_EXITING);
2012 } else if (vmx_cap->ept) {
2014 pr_warn_once("EPT CAP should not exist if not support "
2015 "1-setting enable EPT VM-execution control\n");
2017 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2020 pr_warn_once("VPID CAP should not exist if not support "
2021 "1-setting enable VPID VM-execution control\n");
2024 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2025 #ifdef CONFIG_X86_64
2026 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2028 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2029 VM_EXIT_SAVE_IA32_PAT |
2030 VM_EXIT_LOAD_IA32_PAT |
2031 VM_EXIT_LOAD_IA32_EFER |
2032 VM_EXIT_CLEAR_BNDCFGS |
2033 VM_EXIT_PT_CONCEAL_PIP |
2034 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2035 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2036 &_vmexit_control) < 0)
2039 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2040 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2041 PIN_BASED_VMX_PREEMPTION_TIMER;
2042 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2043 &_pin_based_exec_control) < 0)
2046 if (cpu_has_broken_vmx_preemption_timer())
2047 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2048 if (!(_cpu_based_2nd_exec_control &
2049 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2050 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2052 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2053 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2054 VM_ENTRY_LOAD_IA32_PAT |
2055 VM_ENTRY_LOAD_IA32_EFER |
2056 VM_ENTRY_LOAD_BNDCFGS |
2057 VM_ENTRY_PT_CONCEAL_PIP |
2058 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2059 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2060 &_vmentry_control) < 0)
2064 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2065 * can't be used due to an errata where VM Exit may incorrectly clear
2066 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2067 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2069 if (boot_cpu_data.x86 == 0x6) {
2070 switch (boot_cpu_data.x86_model) {
2071 case 26: /* AAK155 */
2072 case 30: /* AAP115 */
2073 case 37: /* AAT100 */
2074 case 44: /* BC86,AAY89,BD102 */
2076 _vmexit_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2077 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2078 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2079 "does not work properly. Using workaround\n");
2087 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2089 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2090 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2093 #ifdef CONFIG_X86_64
2094 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2095 if (vmx_msr_high & (1u<<16))
2099 /* Require Write-Back (WB) memory type for VMCS accesses. */
2100 if (((vmx_msr_high >> 18) & 15) != 6)
2103 vmcs_conf->size = vmx_msr_high & 0x1fff;
2104 vmcs_conf->order = get_order(vmcs_conf->size);
2105 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2107 vmcs_conf->revision_id = vmx_msr_low;
2109 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2110 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2111 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2112 vmcs_conf->vmexit_ctrl = _vmexit_control;
2113 vmcs_conf->vmentry_ctrl = _vmentry_control;
2115 if (static_branch_unlikely(&enable_evmcs))
2116 evmcs_sanitize_exec_ctrls(vmcs_conf);
2121 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
2123 int node = cpu_to_node(cpu);
2127 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
2130 vmcs = page_address(pages);
2131 memset(vmcs, 0, vmcs_config.size);
2133 /* KVM supports Enlightened VMCS v1 only */
2134 if (static_branch_unlikely(&enable_evmcs))
2135 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2137 vmcs->hdr.revision_id = vmcs_config.revision_id;
2140 vmcs->hdr.shadow_vmcs = 1;
2144 void free_vmcs(struct vmcs *vmcs)
2146 free_pages((unsigned long)vmcs, vmcs_config.order);
2150 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2152 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2154 if (!loaded_vmcs->vmcs)
2156 loaded_vmcs_clear(loaded_vmcs);
2157 free_vmcs(loaded_vmcs->vmcs);
2158 loaded_vmcs->vmcs = NULL;
2159 if (loaded_vmcs->msr_bitmap)
2160 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2161 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2164 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2166 loaded_vmcs->vmcs = alloc_vmcs(false);
2167 if (!loaded_vmcs->vmcs)
2170 loaded_vmcs->shadow_vmcs = NULL;
2171 loaded_vmcs_init(loaded_vmcs);
2173 if (cpu_has_vmx_msr_bitmap()) {
2174 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
2175 if (!loaded_vmcs->msr_bitmap)
2177 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2179 if (IS_ENABLED(CONFIG_HYPERV) &&
2180 static_branch_unlikely(&enable_evmcs) &&
2181 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2182 struct hv_enlightened_vmcs *evmcs =
2183 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2185 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2189 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2194 free_loaded_vmcs(loaded_vmcs);
2198 static void free_kvm_area(void)
2202 for_each_possible_cpu(cpu) {
2203 free_vmcs(per_cpu(vmxarea, cpu));
2204 per_cpu(vmxarea, cpu) = NULL;
2208 static __init int alloc_kvm_area(void)
2212 for_each_possible_cpu(cpu) {
2215 vmcs = alloc_vmcs_cpu(false, cpu);
2222 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2223 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2224 * revision_id reported by MSR_IA32_VMX_BASIC.
2226 * However, even though not explictly documented by
2227 * TLFS, VMXArea passed as VMXON argument should
2228 * still be marked with revision_id reported by
2231 if (static_branch_unlikely(&enable_evmcs))
2232 vmcs->hdr.revision_id = vmcs_config.revision_id;
2234 per_cpu(vmxarea, cpu) = vmcs;
2239 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2240 struct kvm_segment *save)
2242 if (!emulate_invalid_guest_state) {
2244 * CS and SS RPL should be equal during guest entry according
2245 * to VMX spec, but in reality it is not always so. Since vcpu
2246 * is in the middle of the transition from real mode to
2247 * protected mode it is safe to assume that RPL 0 is a good
2250 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2251 save->selector &= ~SEGMENT_RPL_MASK;
2252 save->dpl = save->selector & SEGMENT_RPL_MASK;
2255 vmx_set_segment(vcpu, save, seg);
2258 static void enter_pmode(struct kvm_vcpu *vcpu)
2260 unsigned long flags;
2261 struct vcpu_vmx *vmx = to_vmx(vcpu);
2264 * Update real mode segment cache. It may be not up-to-date if sement
2265 * register was written while vcpu was in a guest mode.
2267 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2268 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2269 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2270 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2271 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2272 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2274 vmx->rmode.vm86_active = 0;
2276 vmx_segment_cache_clear(vmx);
2278 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2280 flags = vmcs_readl(GUEST_RFLAGS);
2281 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2282 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2283 vmcs_writel(GUEST_RFLAGS, flags);
2285 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2286 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2288 update_exception_bitmap(vcpu);
2290 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2291 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2292 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2293 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2294 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2295 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2298 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2300 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2301 struct kvm_segment var = *save;
2304 if (seg == VCPU_SREG_CS)
2307 if (!emulate_invalid_guest_state) {
2308 var.selector = var.base >> 4;
2309 var.base = var.base & 0xffff0;
2319 if (save->base & 0xf)
2320 printk_once(KERN_WARNING "kvm: segment base is not "
2321 "paragraph aligned when entering "
2322 "protected mode (seg=%d)", seg);
2325 vmcs_write16(sf->selector, var.selector);
2326 vmcs_writel(sf->base, var.base);
2327 vmcs_write32(sf->limit, var.limit);
2328 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2331 static void enter_rmode(struct kvm_vcpu *vcpu)
2333 unsigned long flags;
2334 struct vcpu_vmx *vmx = to_vmx(vcpu);
2335 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2337 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2338 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2339 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2340 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2341 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2342 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2343 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2345 vmx->rmode.vm86_active = 1;
2348 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2349 * vcpu. Warn the user that an update is overdue.
2351 if (!kvm_vmx->tss_addr)
2352 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2353 "called before entering vcpu\n");
2355 vmx_segment_cache_clear(vmx);
2357 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2358 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2359 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2361 flags = vmcs_readl(GUEST_RFLAGS);
2362 vmx->rmode.save_rflags = flags;
2364 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2366 vmcs_writel(GUEST_RFLAGS, flags);
2367 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2368 update_exception_bitmap(vcpu);
2370 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2371 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2372 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2373 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2374 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2375 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2377 kvm_mmu_reset_context(vcpu);
2380 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2382 struct vcpu_vmx *vmx = to_vmx(vcpu);
2383 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2388 vcpu->arch.efer = efer;
2389 if (efer & EFER_LMA) {
2390 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2393 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2395 msr->data = efer & ~EFER_LME;
2400 #ifdef CONFIG_X86_64
2402 static void enter_lmode(struct kvm_vcpu *vcpu)
2406 vmx_segment_cache_clear(to_vmx(vcpu));
2408 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2409 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2410 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2412 vmcs_write32(GUEST_TR_AR_BYTES,
2413 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2414 | VMX_AR_TYPE_BUSY_64_TSS);
2416 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2419 static void exit_lmode(struct kvm_vcpu *vcpu)
2421 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2422 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2427 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2429 int vpid = to_vmx(vcpu)->vpid;
2431 if (!vpid_sync_vcpu_addr(vpid, addr))
2432 vpid_sync_context(vpid);
2435 * If VPIDs are not supported or enabled, then the above is a no-op.
2436 * But we don't really need a TLB flush in that case anyway, because
2437 * each VM entry/exit includes an implicit flush when VPID is 0.
2441 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2443 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2445 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
2446 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
2449 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2451 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
2452 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2453 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2456 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2458 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2460 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2461 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2464 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2466 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2468 if (!test_bit(VCPU_EXREG_PDPTR,
2469 (unsigned long *)&vcpu->arch.regs_dirty))
2472 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2473 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2474 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2475 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2476 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2480 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2482 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2484 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2485 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2486 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2487 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2488 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2491 __set_bit(VCPU_EXREG_PDPTR,
2492 (unsigned long *)&vcpu->arch.regs_avail);
2493 __set_bit(VCPU_EXREG_PDPTR,
2494 (unsigned long *)&vcpu->arch.regs_dirty);
2497 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2499 struct kvm_vcpu *vcpu)
2501 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2502 vmx_decache_cr3(vcpu);
2503 if (!(cr0 & X86_CR0_PG)) {
2504 /* From paging/starting to nonpaging */
2505 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2506 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
2507 (CPU_BASED_CR3_LOAD_EXITING |
2508 CPU_BASED_CR3_STORE_EXITING));
2509 vcpu->arch.cr0 = cr0;
2510 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2511 } else if (!is_paging(vcpu)) {
2512 /* From nonpaging to paging */
2513 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2514 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
2515 ~(CPU_BASED_CR3_LOAD_EXITING |
2516 CPU_BASED_CR3_STORE_EXITING));
2517 vcpu->arch.cr0 = cr0;
2518 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2521 if (!(cr0 & X86_CR0_WP))
2522 *hw_cr0 &= ~X86_CR0_WP;
2525 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2527 struct vcpu_vmx *vmx = to_vmx(vcpu);
2528 unsigned long hw_cr0;
2530 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
2531 if (enable_unrestricted_guest)
2532 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
2534 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
2536 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
2539 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
2543 #ifdef CONFIG_X86_64
2544 if (vcpu->arch.efer & EFER_LME) {
2545 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
2547 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
2552 if (enable_ept && !enable_unrestricted_guest)
2553 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
2555 vmcs_writel(CR0_READ_SHADOW, cr0);
2556 vmcs_writel(GUEST_CR0, hw_cr0);
2557 vcpu->arch.cr0 = cr0;
2559 /* depends on vcpu->arch.cr0 to be set to a new value */
2560 vmx->emulation_required = emulation_required(vcpu);
2563 static int get_ept_level(struct kvm_vcpu *vcpu)
2565 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
2570 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
2572 u64 eptp = VMX_EPTP_MT_WB;
2574 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
2576 if (enable_ept_ad_bits &&
2577 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
2578 eptp |= VMX_EPTP_AD_ENABLE_BIT;
2579 eptp |= (root_hpa & PAGE_MASK);
2584 void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
2586 struct kvm *kvm = vcpu->kvm;
2587 unsigned long guest_cr3;
2592 eptp = construct_eptp(vcpu, cr3);
2593 vmcs_write64(EPT_POINTER, eptp);
2595 if (kvm_x86_ops->tlb_remote_flush) {
2596 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2597 to_vmx(vcpu)->ept_pointer = eptp;
2598 to_kvm_vmx(kvm)->ept_pointers_match
2599 = EPT_POINTERS_CHECK;
2600 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2603 if (enable_unrestricted_guest || is_paging(vcpu) ||
2604 is_guest_mode(vcpu))
2605 guest_cr3 = kvm_read_cr3(vcpu);
2607 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
2608 ept_load_pdptrs(vcpu);
2611 vmcs_writel(GUEST_CR3, guest_cr3);
2614 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2617 * Pass through host's Machine Check Enable value to hw_cr4, which
2618 * is in force while we are in guest mode. Do not let guests control
2619 * this bit, even if host CR4.MCE == 0.
2621 unsigned long hw_cr4;
2623 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
2624 if (enable_unrestricted_guest)
2625 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
2626 else if (to_vmx(vcpu)->rmode.vm86_active)
2627 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
2629 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
2631 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
2632 if (cr4 & X86_CR4_UMIP) {
2633 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
2634 SECONDARY_EXEC_DESC);
2635 hw_cr4 &= ~X86_CR4_UMIP;
2636 } else if (!is_guest_mode(vcpu) ||
2637 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
2638 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
2639 SECONDARY_EXEC_DESC);
2642 if (cr4 & X86_CR4_VMXE) {
2644 * To use VMXON (and later other VMX instructions), a guest
2645 * must first be able to turn on cr4.VMXE (see handle_vmon()).
2646 * So basically the check on whether to allow nested VMX
2647 * is here. We operate under the default treatment of SMM,
2648 * so VMX cannot be enabled under SMM.
2650 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
2654 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
2657 vcpu->arch.cr4 = cr4;
2659 if (!enable_unrestricted_guest) {
2661 if (!is_paging(vcpu)) {
2662 hw_cr4 &= ~X86_CR4_PAE;
2663 hw_cr4 |= X86_CR4_PSE;
2664 } else if (!(cr4 & X86_CR4_PAE)) {
2665 hw_cr4 &= ~X86_CR4_PAE;
2670 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
2671 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
2672 * to be manually disabled when guest switches to non-paging
2675 * If !enable_unrestricted_guest, the CPU is always running
2676 * with CR0.PG=1 and CR4 needs to be modified.
2677 * If enable_unrestricted_guest, the CPU automatically
2678 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
2680 if (!is_paging(vcpu))
2681 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
2684 vmcs_writel(CR4_READ_SHADOW, cr4);
2685 vmcs_writel(GUEST_CR4, hw_cr4);
2689 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
2691 struct vcpu_vmx *vmx = to_vmx(vcpu);
2694 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
2695 *var = vmx->rmode.segs[seg];
2696 if (seg == VCPU_SREG_TR
2697 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
2699 var->base = vmx_read_guest_seg_base(vmx, seg);
2700 var->selector = vmx_read_guest_seg_selector(vmx, seg);
2703 var->base = vmx_read_guest_seg_base(vmx, seg);
2704 var->limit = vmx_read_guest_seg_limit(vmx, seg);
2705 var->selector = vmx_read_guest_seg_selector(vmx, seg);
2706 ar = vmx_read_guest_seg_ar(vmx, seg);
2707 var->unusable = (ar >> 16) & 1;
2708 var->type = ar & 15;
2709 var->s = (ar >> 4) & 1;
2710 var->dpl = (ar >> 5) & 3;
2712 * Some userspaces do not preserve unusable property. Since usable
2713 * segment has to be present according to VMX spec we can use present
2714 * property to amend userspace bug by making unusable segment always
2715 * nonpresent. vmx_segment_access_rights() already marks nonpresent
2716 * segment as unusable.
2718 var->present = !var->unusable;
2719 var->avl = (ar >> 12) & 1;
2720 var->l = (ar >> 13) & 1;
2721 var->db = (ar >> 14) & 1;
2722 var->g = (ar >> 15) & 1;
2725 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2727 struct kvm_segment s;
2729 if (to_vmx(vcpu)->rmode.vm86_active) {
2730 vmx_get_segment(vcpu, &s, seg);
2733 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
2736 int vmx_get_cpl(struct kvm_vcpu *vcpu)
2738 struct vcpu_vmx *vmx = to_vmx(vcpu);
2740 if (unlikely(vmx->rmode.vm86_active))
2743 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
2744 return VMX_AR_DPL(ar);
2748 static u32 vmx_segment_access_rights(struct kvm_segment *var)
2752 if (var->unusable || !var->present)
2755 ar = var->type & 15;
2756 ar |= (var->s & 1) << 4;
2757 ar |= (var->dpl & 3) << 5;
2758 ar |= (var->present & 1) << 7;
2759 ar |= (var->avl & 1) << 12;
2760 ar |= (var->l & 1) << 13;
2761 ar |= (var->db & 1) << 14;
2762 ar |= (var->g & 1) << 15;
2768 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
2770 struct vcpu_vmx *vmx = to_vmx(vcpu);
2771 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2773 vmx_segment_cache_clear(vmx);
2775 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
2776 vmx->rmode.segs[seg] = *var;
2777 if (seg == VCPU_SREG_TR)
2778 vmcs_write16(sf->selector, var->selector);
2780 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
2784 vmcs_writel(sf->base, var->base);
2785 vmcs_write32(sf->limit, var->limit);
2786 vmcs_write16(sf->selector, var->selector);
2789 * Fix the "Accessed" bit in AR field of segment registers for older
2791 * IA32 arch specifies that at the time of processor reset the
2792 * "Accessed" bit in the AR field of segment registers is 1. And qemu
2793 * is setting it to 0 in the userland code. This causes invalid guest
2794 * state vmexit when "unrestricted guest" mode is turned on.
2795 * Fix for this setup issue in cpu_reset is being pushed in the qemu
2796 * tree. Newer qemu binaries with that qemu fix would not need this
2799 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
2800 var->type |= 0x1; /* Accessed */
2802 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
2805 vmx->emulation_required = emulation_required(vcpu);
2808 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
2810 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
2812 *db = (ar >> 14) & 1;
2813 *l = (ar >> 13) & 1;
2816 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2818 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
2819 dt->address = vmcs_readl(GUEST_IDTR_BASE);
2822 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2824 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
2825 vmcs_writel(GUEST_IDTR_BASE, dt->address);
2828 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2830 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
2831 dt->address = vmcs_readl(GUEST_GDTR_BASE);
2834 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2836 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
2837 vmcs_writel(GUEST_GDTR_BASE, dt->address);
2840 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
2842 struct kvm_segment var;
2845 vmx_get_segment(vcpu, &var, seg);
2847 if (seg == VCPU_SREG_CS)
2849 ar = vmx_segment_access_rights(&var);
2851 if (var.base != (var.selector << 4))
2853 if (var.limit != 0xffff)
2861 static bool code_segment_valid(struct kvm_vcpu *vcpu)
2863 struct kvm_segment cs;
2864 unsigned int cs_rpl;
2866 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
2867 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
2871 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
2875 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
2876 if (cs.dpl > cs_rpl)
2879 if (cs.dpl != cs_rpl)
2885 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
2889 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
2891 struct kvm_segment ss;
2892 unsigned int ss_rpl;
2894 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
2895 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
2899 if (ss.type != 3 && ss.type != 7)
2903 if (ss.dpl != ss_rpl) /* DPL != RPL */
2911 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
2913 struct kvm_segment var;
2916 vmx_get_segment(vcpu, &var, seg);
2917 rpl = var.selector & SEGMENT_RPL_MASK;
2925 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
2926 if (var.dpl < rpl) /* DPL < RPL */
2930 /* TODO: Add other members to kvm_segment_field to allow checking for other access
2936 static bool tr_valid(struct kvm_vcpu *vcpu)
2938 struct kvm_segment tr;
2940 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
2944 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
2946 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
2954 static bool ldtr_valid(struct kvm_vcpu *vcpu)
2956 struct kvm_segment ldtr;
2958 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
2962 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
2972 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
2974 struct kvm_segment cs, ss;
2976 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
2977 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
2979 return ((cs.selector & SEGMENT_RPL_MASK) ==
2980 (ss.selector & SEGMENT_RPL_MASK));
2984 * Check if guest state is valid. Returns true if valid, false if
2986 * We assume that registers are always usable
2988 static bool guest_state_valid(struct kvm_vcpu *vcpu)
2990 if (enable_unrestricted_guest)
2993 /* real mode guest state checks */
2994 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
2995 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
2997 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
2999 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3001 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3003 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3005 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3008 /* protected mode guest state checks */
3009 if (!cs_ss_rpl_check(vcpu))
3011 if (!code_segment_valid(vcpu))
3013 if (!stack_segment_valid(vcpu))
3015 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3017 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3019 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3021 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3023 if (!tr_valid(vcpu))
3025 if (!ldtr_valid(vcpu))
3029 * - Add checks on RIP
3030 * - Add checks on RFLAGS
3036 static int init_rmode_tss(struct kvm *kvm)
3042 idx = srcu_read_lock(&kvm->srcu);
3043 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3044 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3047 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3048 r = kvm_write_guest_page(kvm, fn++, &data,
3049 TSS_IOPB_BASE_OFFSET, sizeof(u16));
3052 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3055 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3059 r = kvm_write_guest_page(kvm, fn, &data,
3060 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3063 srcu_read_unlock(&kvm->srcu, idx);
3067 static int init_rmode_identity_map(struct kvm *kvm)
3069 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3071 kvm_pfn_t identity_map_pfn;
3074 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3075 mutex_lock(&kvm->slots_lock);
3077 if (likely(kvm_vmx->ept_identity_pagetable_done))
3080 if (!kvm_vmx->ept_identity_map_addr)
3081 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3082 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3084 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3085 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3089 idx = srcu_read_lock(&kvm->srcu);
3090 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3093 /* Set up identity-mapping pagetable for EPT in real mode */
3094 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3095 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3096 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3097 r = kvm_write_guest_page(kvm, identity_map_pfn,
3098 &tmp, i * sizeof(tmp), sizeof(tmp));
3102 kvm_vmx->ept_identity_pagetable_done = true;
3105 srcu_read_unlock(&kvm->srcu, idx);
3108 mutex_unlock(&kvm->slots_lock);
3112 static void seg_setup(int seg)
3114 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3117 vmcs_write16(sf->selector, 0);
3118 vmcs_writel(sf->base, 0);
3119 vmcs_write32(sf->limit, 0xffff);
3121 if (seg == VCPU_SREG_CS)
3122 ar |= 0x08; /* code segment */
3124 vmcs_write32(sf->ar_bytes, ar);
3127 static int alloc_apic_access_page(struct kvm *kvm)
3132 mutex_lock(&kvm->slots_lock);
3133 if (kvm->arch.apic_access_page_done)
3135 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3136 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3140 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3141 if (is_error_page(page)) {
3147 * Do not pin the page in memory, so that memory hot-unplug
3148 * is able to migrate it.
3151 kvm->arch.apic_access_page_done = true;
3153 mutex_unlock(&kvm->slots_lock);
3157 int allocate_vpid(void)
3163 spin_lock(&vmx_vpid_lock);
3164 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3165 if (vpid < VMX_NR_VPIDS)
3166 __set_bit(vpid, vmx_vpid_bitmap);
3169 spin_unlock(&vmx_vpid_lock);
3173 void free_vpid(int vpid)
3175 if (!enable_vpid || vpid == 0)
3177 spin_lock(&vmx_vpid_lock);
3178 __clear_bit(vpid, vmx_vpid_bitmap);
3179 spin_unlock(&vmx_vpid_lock);
3182 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3185 int f = sizeof(unsigned long);
3187 if (!cpu_has_vmx_msr_bitmap())
3190 if (static_branch_unlikely(&enable_evmcs))
3191 evmcs_touch_msr_bitmap();
3194 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3195 * have the write-low and read-high bitmap offsets the wrong way round.
3196 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3198 if (msr <= 0x1fff) {
3199 if (type & MSR_TYPE_R)
3201 __clear_bit(msr, msr_bitmap + 0x000 / f);
3203 if (type & MSR_TYPE_W)
3205 __clear_bit(msr, msr_bitmap + 0x800 / f);
3207 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3209 if (type & MSR_TYPE_R)
3211 __clear_bit(msr, msr_bitmap + 0x400 / f);
3213 if (type & MSR_TYPE_W)
3215 __clear_bit(msr, msr_bitmap + 0xc00 / f);
3220 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3223 int f = sizeof(unsigned long);
3225 if (!cpu_has_vmx_msr_bitmap())
3228 if (static_branch_unlikely(&enable_evmcs))
3229 evmcs_touch_msr_bitmap();
3232 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3233 * have the write-low and read-high bitmap offsets the wrong way round.
3234 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3236 if (msr <= 0x1fff) {
3237 if (type & MSR_TYPE_R)
3239 __set_bit(msr, msr_bitmap + 0x000 / f);
3241 if (type & MSR_TYPE_W)
3243 __set_bit(msr, msr_bitmap + 0x800 / f);
3245 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3247 if (type & MSR_TYPE_R)
3249 __set_bit(msr, msr_bitmap + 0x400 / f);
3251 if (type & MSR_TYPE_W)
3253 __set_bit(msr, msr_bitmap + 0xc00 / f);
3258 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3259 u32 msr, int type, bool value)
3262 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3264 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3267 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3271 if (cpu_has_secondary_exec_ctrls() &&
3272 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
3273 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3274 mode |= MSR_BITMAP_MODE_X2APIC;
3275 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3276 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3282 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3287 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3288 unsigned word = msr / BITS_PER_LONG;
3289 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3290 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3293 if (mode & MSR_BITMAP_MODE_X2APIC) {
3295 * TPR reads and writes can be virtualized even if virtual interrupt
3296 * delivery is not in use.
3298 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3299 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3300 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3301 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3302 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3307 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3309 struct vcpu_vmx *vmx = to_vmx(vcpu);
3310 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3311 u8 mode = vmx_msr_bitmap_mode(vcpu);
3312 u8 changed = mode ^ vmx->msr_bitmap_mode;
3317 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3318 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3320 vmx->msr_bitmap_mode = mode;
3323 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
3325 return enable_apicv;
3328 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3330 struct vcpu_vmx *vmx = to_vmx(vcpu);
3335 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3336 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3337 WARN_ON_ONCE(!vmx->nested.virtual_apic_page))
3340 rvi = vmx_get_rvi();
3342 vapic_page = kmap(vmx->nested.virtual_apic_page);
3343 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3344 kunmap(vmx->nested.virtual_apic_page);
3346 return ((rvi & 0xf0) > (vppr & 0xf0));
3349 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3353 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3355 if (vcpu->mode == IN_GUEST_MODE) {
3357 * The vector of interrupt to be delivered to vcpu had
3358 * been set in PIR before this function.
3360 * Following cases will be reached in this block, and
3361 * we always send a notification event in all cases as
3364 * Case 1: vcpu keeps in non-root mode. Sending a
3365 * notification event posts the interrupt to vcpu.
3367 * Case 2: vcpu exits to root mode and is still
3368 * runnable. PIR will be synced to vIRR before the
3369 * next vcpu entry. Sending a notification event in
3370 * this case has no effect, as vcpu is not in root
3373 * Case 3: vcpu exits to root mode and is blocked.
3374 * vcpu_block() has already synced PIR to vIRR and
3375 * never blocks vcpu if vIRR is not cleared. Therefore,
3376 * a blocked vcpu here does not wait for any requested
3377 * interrupts in PIR, and sending a notification event
3378 * which has no effect is safe here.
3381 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3388 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3391 struct vcpu_vmx *vmx = to_vmx(vcpu);
3393 if (is_guest_mode(vcpu) &&
3394 vector == vmx->nested.posted_intr_nv) {
3396 * If a posted intr is not recognized by hardware,
3397 * we will accomplish it in the next vmentry.
3399 vmx->nested.pi_pending = true;
3400 kvm_make_request(KVM_REQ_EVENT, vcpu);
3401 /* the PIR and ON have been set by L1. */
3402 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3403 kvm_vcpu_kick(vcpu);
3409 * Send interrupt to vcpu via posted interrupt way.
3410 * 1. If target vcpu is running(non-root mode), send posted interrupt
3411 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3412 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3413 * interrupt from PIR in next vmentry.
3415 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3417 struct vcpu_vmx *vmx = to_vmx(vcpu);
3420 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3424 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3427 /* If a previous notification has sent the IPI, nothing to do. */
3428 if (pi_test_and_set_on(&vmx->pi_desc))
3431 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3432 kvm_vcpu_kick(vcpu);
3436 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3437 * will not change in the lifetime of the guest.
3438 * Note that host-state that does change is set elsewhere. E.g., host-state
3439 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3441 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3446 unsigned long cr0, cr3, cr4;
3449 WARN_ON(cr0 & X86_CR0_TS);
3450 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
3453 * Save the most likely value for this task's CR3 in the VMCS.
3454 * We can't use __get_current_cr3_fast() because we're not atomic.
3457 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
3458 vmx->loaded_vmcs->host_state.cr3 = cr3;
3460 /* Save the most likely value for this task's CR4 in the VMCS. */
3461 cr4 = cr4_read_shadow();
3462 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
3463 vmx->loaded_vmcs->host_state.cr4 = cr4;
3465 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
3466 #ifdef CONFIG_X86_64
3468 * Load null selectors, so we can avoid reloading them in
3469 * vmx_prepare_switch_to_host(), in case userspace uses
3470 * the null selectors too (the expected case).
3472 vmcs_write16(HOST_DS_SELECTOR, 0);
3473 vmcs_write16(HOST_ES_SELECTOR, 0);
3475 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3476 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3478 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3479 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
3482 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
3483 vmx->host_idt_base = dt.address;
3485 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
3487 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3488 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3489 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
3490 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
3492 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
3493 rdmsr(MSR_IA32_CR_PAT, low32, high32);
3494 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
3497 if (cpu_has_load_ia32_efer())
3498 vmcs_write64(HOST_IA32_EFER, host_efer);
3501 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
3503 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
3505 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
3506 if (is_guest_mode(&vmx->vcpu))
3507 vmx->vcpu.arch.cr4_guest_owned_bits &=
3508 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
3509 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
3512 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
3514 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
3516 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
3517 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
3520 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
3522 /* Enable the preemption timer dynamically */
3523 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3524 return pin_based_exec_ctrl;
3527 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
3529 struct vcpu_vmx *vmx = to_vmx(vcpu);
3531 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
3532 if (cpu_has_secondary_exec_ctrls()) {
3533 if (kvm_vcpu_apicv_active(vcpu))
3534 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
3535 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3536 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3538 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
3539 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3540 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3543 if (cpu_has_vmx_msr_bitmap())
3544 vmx_update_msr_bitmap(vcpu);
3547 u32 vmx_exec_control(struct vcpu_vmx *vmx)
3549 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
3551 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
3552 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
3554 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
3555 exec_control &= ~CPU_BASED_TPR_SHADOW;
3556 #ifdef CONFIG_X86_64
3557 exec_control |= CPU_BASED_CR8_STORE_EXITING |
3558 CPU_BASED_CR8_LOAD_EXITING;
3562 exec_control |= CPU_BASED_CR3_STORE_EXITING |
3563 CPU_BASED_CR3_LOAD_EXITING |
3564 CPU_BASED_INVLPG_EXITING;
3565 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
3566 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
3567 CPU_BASED_MONITOR_EXITING);
3568 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
3569 exec_control &= ~CPU_BASED_HLT_EXITING;
3570 return exec_control;
3574 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
3576 struct kvm_vcpu *vcpu = &vmx->vcpu;
3578 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
3580 if (pt_mode == PT_MODE_SYSTEM)
3581 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
3582 if (!cpu_need_virtualize_apic_accesses(vcpu))
3583 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3585 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
3587 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
3588 enable_unrestricted_guest = 0;
3590 if (!enable_unrestricted_guest)
3591 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
3592 if (kvm_pause_in_guest(vmx->vcpu.kvm))
3593 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
3594 if (!kvm_vcpu_apicv_active(vcpu))
3595 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
3596 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3597 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
3599 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
3600 * in vmx_set_cr4. */
3601 exec_control &= ~SECONDARY_EXEC_DESC;
3603 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
3605 We can NOT enable shadow_vmcs here because we don't have yet
3608 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
3611 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
3613 if (vmx_xsaves_supported()) {
3614 /* Exposing XSAVES only when XSAVE is exposed */
3615 bool xsaves_enabled =
3616 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
3617 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
3619 if (!xsaves_enabled)
3620 exec_control &= ~SECONDARY_EXEC_XSAVES;
3624 vmx->nested.msrs.secondary_ctls_high |=
3625 SECONDARY_EXEC_XSAVES;
3627 vmx->nested.msrs.secondary_ctls_high &=
3628 ~SECONDARY_EXEC_XSAVES;
3632 if (vmx_rdtscp_supported()) {
3633 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
3634 if (!rdtscp_enabled)
3635 exec_control &= ~SECONDARY_EXEC_RDTSCP;
3639 vmx->nested.msrs.secondary_ctls_high |=
3640 SECONDARY_EXEC_RDTSCP;
3642 vmx->nested.msrs.secondary_ctls_high &=
3643 ~SECONDARY_EXEC_RDTSCP;
3647 if (vmx_invpcid_supported()) {
3648 /* Exposing INVPCID only when PCID is exposed */
3649 bool invpcid_enabled =
3650 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
3651 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
3653 if (!invpcid_enabled) {
3654 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
3655 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
3659 if (invpcid_enabled)
3660 vmx->nested.msrs.secondary_ctls_high |=
3661 SECONDARY_EXEC_ENABLE_INVPCID;
3663 vmx->nested.msrs.secondary_ctls_high &=
3664 ~SECONDARY_EXEC_ENABLE_INVPCID;
3668 if (vmx_rdrand_supported()) {
3669 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
3671 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
3675 vmx->nested.msrs.secondary_ctls_high |=
3676 SECONDARY_EXEC_RDRAND_EXITING;
3678 vmx->nested.msrs.secondary_ctls_high &=
3679 ~SECONDARY_EXEC_RDRAND_EXITING;
3683 if (vmx_rdseed_supported()) {
3684 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
3686 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
3690 vmx->nested.msrs.secondary_ctls_high |=
3691 SECONDARY_EXEC_RDSEED_EXITING;
3693 vmx->nested.msrs.secondary_ctls_high &=
3694 ~SECONDARY_EXEC_RDSEED_EXITING;
3698 vmx->secondary_exec_control = exec_control;
3701 static void ept_set_mmio_spte_mask(void)
3704 * EPT Misconfigurations can be generated if the value of bits 2:0
3705 * of an EPT paging-structure entry is 110b (write/execute).
3707 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
3708 VMX_EPT_MISCONFIG_WX_VALUE);
3711 #define VMX_XSS_EXIT_BITMAP 0
3714 * Sets up the vmcs for emulated real mode.
3716 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
3721 nested_vmx_vcpu_setup();
3723 if (cpu_has_vmx_msr_bitmap())
3724 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
3726 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
3729 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
3730 vmx->hv_deadline_tsc = -1;
3732 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
3734 if (cpu_has_secondary_exec_ctrls()) {
3735 vmx_compute_secondary_exec_control(vmx);
3736 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
3737 vmx->secondary_exec_control);
3740 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
3741 vmcs_write64(EOI_EXIT_BITMAP0, 0);
3742 vmcs_write64(EOI_EXIT_BITMAP1, 0);
3743 vmcs_write64(EOI_EXIT_BITMAP2, 0);
3744 vmcs_write64(EOI_EXIT_BITMAP3, 0);
3746 vmcs_write16(GUEST_INTR_STATUS, 0);
3748 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
3749 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
3752 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
3753 vmcs_write32(PLE_GAP, ple_gap);
3754 vmx->ple_window = ple_window;
3755 vmx->ple_window_dirty = true;
3758 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
3759 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
3760 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
3762 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
3763 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
3764 vmx_set_constant_host_state(vmx);
3765 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
3766 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
3768 if (cpu_has_vmx_vmfunc())
3769 vmcs_write64(VM_FUNCTION_CONTROL, 0);
3771 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
3772 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
3773 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
3774 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
3775 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
3777 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
3778 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
3780 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
3781 u32 index = vmx_msr_index[i];
3782 u32 data_low, data_high;
3785 if (rdmsr_safe(index, &data_low, &data_high) < 0)
3787 if (wrmsr_safe(index, data_low, data_high) < 0)
3789 vmx->guest_msrs[j].index = i;
3790 vmx->guest_msrs[j].data = 0;
3791 vmx->guest_msrs[j].mask = -1ull;
3795 vmx->arch_capabilities = kvm_get_arch_capabilities();
3797 vm_exit_controls_init(vmx, vmx_vmexit_ctrl());
3799 /* 22.2.1, 20.8.1 */
3800 vm_entry_controls_init(vmx, vmx_vmentry_ctrl());
3802 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
3803 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
3805 set_cr4_guest_host_mask(vmx);
3807 if (vmx_xsaves_supported())
3808 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
3811 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
3812 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
3815 if (cpu_has_vmx_encls_vmexit())
3816 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
3819 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
3821 struct vcpu_vmx *vmx = to_vmx(vcpu);
3822 struct msr_data apic_base_msr;
3825 vmx->rmode.vm86_active = 0;
3828 vcpu->arch.microcode_version = 0x100000000ULL;
3829 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
3830 kvm_set_cr8(vcpu, 0);
3833 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
3834 MSR_IA32_APICBASE_ENABLE;
3835 if (kvm_vcpu_is_reset_bsp(vcpu))
3836 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
3837 apic_base_msr.host_initiated = true;
3838 kvm_set_apic_base(vcpu, &apic_base_msr);
3841 vmx_segment_cache_clear(vmx);
3843 seg_setup(VCPU_SREG_CS);
3844 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
3845 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
3847 seg_setup(VCPU_SREG_DS);
3848 seg_setup(VCPU_SREG_ES);
3849 seg_setup(VCPU_SREG_FS);
3850 seg_setup(VCPU_SREG_GS);
3851 seg_setup(VCPU_SREG_SS);
3853 vmcs_write16(GUEST_TR_SELECTOR, 0);
3854 vmcs_writel(GUEST_TR_BASE, 0);
3855 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
3856 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3858 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
3859 vmcs_writel(GUEST_LDTR_BASE, 0);
3860 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
3861 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
3864 vmcs_write32(GUEST_SYSENTER_CS, 0);
3865 vmcs_writel(GUEST_SYSENTER_ESP, 0);
3866 vmcs_writel(GUEST_SYSENTER_EIP, 0);
3867 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
3870 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
3871 kvm_rip_write(vcpu, 0xfff0);
3873 vmcs_writel(GUEST_GDTR_BASE, 0);
3874 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
3876 vmcs_writel(GUEST_IDTR_BASE, 0);
3877 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
3879 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3880 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
3881 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
3882 if (kvm_mpx_supported())
3883 vmcs_write64(GUEST_BNDCFGS, 0);
3887 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
3889 if (cpu_has_vmx_tpr_shadow() && !init_event) {
3890 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
3891 if (cpu_need_tpr_shadow(vcpu))
3892 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
3893 __pa(vcpu->arch.apic->regs));
3894 vmcs_write32(TPR_THRESHOLD, 0);
3897 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
3900 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
3902 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
3903 vmx->vcpu.arch.cr0 = cr0;
3904 vmx_set_cr0(vcpu, cr0); /* enter rmode */
3905 vmx_set_cr4(vcpu, 0);
3906 vmx_set_efer(vcpu, 0);
3908 update_exception_bitmap(vcpu);
3910 vpid_sync_context(vmx->vpid);
3912 vmx_clear_hlt(vcpu);
3915 static void enable_irq_window(struct kvm_vcpu *vcpu)
3917 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
3918 CPU_BASED_VIRTUAL_INTR_PENDING);
3921 static void enable_nmi_window(struct kvm_vcpu *vcpu)
3924 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
3925 enable_irq_window(vcpu);
3929 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
3930 CPU_BASED_VIRTUAL_NMI_PENDING);
3933 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
3935 struct vcpu_vmx *vmx = to_vmx(vcpu);
3937 int irq = vcpu->arch.interrupt.nr;
3939 trace_kvm_inj_virq(irq);
3941 ++vcpu->stat.irq_injections;
3942 if (vmx->rmode.vm86_active) {
3944 if (vcpu->arch.interrupt.soft)
3945 inc_eip = vcpu->arch.event_exit_inst_len;
3946 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
3947 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3950 intr = irq | INTR_INFO_VALID_MASK;
3951 if (vcpu->arch.interrupt.soft) {
3952 intr |= INTR_TYPE_SOFT_INTR;
3953 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
3954 vmx->vcpu.arch.event_exit_inst_len);
3956 intr |= INTR_TYPE_EXT_INTR;
3957 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
3959 vmx_clear_hlt(vcpu);
3962 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
3964 struct vcpu_vmx *vmx = to_vmx(vcpu);
3968 * Tracking the NMI-blocked state in software is built upon
3969 * finding the next open IRQ window. This, in turn, depends on
3970 * well-behaving guests: They have to keep IRQs disabled at
3971 * least as long as the NMI handler runs. Otherwise we may
3972 * cause NMI nesting, maybe breaking the guest. But as this is
3973 * highly unlikely, we can live with the residual risk.
3975 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
3976 vmx->loaded_vmcs->vnmi_blocked_time = 0;
3979 ++vcpu->stat.nmi_injections;
3980 vmx->loaded_vmcs->nmi_known_unmasked = false;
3982 if (vmx->rmode.vm86_active) {
3983 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
3984 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3988 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
3989 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
3991 vmx_clear_hlt(vcpu);
3994 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
3996 struct vcpu_vmx *vmx = to_vmx(vcpu);
4000 return vmx->loaded_vmcs->soft_vnmi_blocked;
4001 if (vmx->loaded_vmcs->nmi_known_unmasked)
4003 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4004 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4008 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4010 struct vcpu_vmx *vmx = to_vmx(vcpu);
4013 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4014 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4015 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4018 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4020 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4021 GUEST_INTR_STATE_NMI);
4023 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4024 GUEST_INTR_STATE_NMI);
4028 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4030 if (to_vmx(vcpu)->nested.nested_run_pending)
4034 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4037 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4038 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4039 | GUEST_INTR_STATE_NMI));
4042 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4044 return (!to_vmx(vcpu)->nested.nested_run_pending &&
4045 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4046 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4047 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4050 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4054 if (enable_unrestricted_guest)
4057 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4061 to_kvm_vmx(kvm)->tss_addr = addr;
4062 return init_rmode_tss(kvm);
4065 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4067 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4071 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4076 * Update instruction length as we may reinject the exception
4077 * from user space while in guest debugging mode.
4079 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4080 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4081 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4085 if (vcpu->guest_debug &
4086 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4103 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4104 int vec, u32 err_code)
4107 * Instruction with address size override prefix opcode 0x67
4108 * Cause the #SS fault with 0 error code in VM86 mode.
4110 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4111 if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
4112 if (vcpu->arch.halt_request) {
4113 vcpu->arch.halt_request = 0;
4114 return kvm_vcpu_halt(vcpu);
4122 * Forward all other exceptions that are valid in real mode.
4123 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4124 * the required debugging infrastructure rework.
4126 kvm_queue_exception(vcpu, vec);
4131 * Trigger machine check on the host. We assume all the MSRs are already set up
4132 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4133 * We pass a fake environment to the machine check handler because we want
4134 * the guest to be always treated like user space, no matter what context
4135 * it used internally.
4137 static void kvm_machine_check(void)
4139 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4140 struct pt_regs regs = {
4141 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4142 .flags = X86_EFLAGS_IF,
4145 do_machine_check(®s, 0);
4149 static int handle_machine_check(struct kvm_vcpu *vcpu)
4151 /* already handled by vcpu_run */
4155 static int handle_exception(struct kvm_vcpu *vcpu)
4157 struct vcpu_vmx *vmx = to_vmx(vcpu);
4158 struct kvm_run *kvm_run = vcpu->run;
4159 u32 intr_info, ex_no, error_code;
4160 unsigned long cr2, rip, dr6;
4162 enum emulation_result er;
4164 vect_info = vmx->idt_vectoring_info;
4165 intr_info = vmx->exit_intr_info;
4167 if (is_machine_check(intr_info))
4168 return handle_machine_check(vcpu);
4170 if (is_nmi(intr_info))
4171 return 1; /* already handled by vmx_vcpu_run() */
4173 if (is_invalid_opcode(intr_info))
4174 return handle_ud(vcpu);
4177 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4178 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4180 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4181 WARN_ON_ONCE(!enable_vmware_backdoor);
4182 er = kvm_emulate_instruction(vcpu,
4183 EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
4184 if (er == EMULATE_USER_EXIT)
4186 else if (er != EMULATE_DONE)
4187 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4192 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4193 * MMIO, it is better to report an internal error.
4194 * See the comments in vmx_handle_exit.
4196 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4197 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4198 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4199 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4200 vcpu->run->internal.ndata = 3;
4201 vcpu->run->internal.data[0] = vect_info;
4202 vcpu->run->internal.data[1] = intr_info;
4203 vcpu->run->internal.data[2] = error_code;
4207 if (is_page_fault(intr_info)) {
4208 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4209 /* EPT won't cause page fault directly */
4210 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
4211 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4214 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4216 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4217 return handle_rmode_exception(vcpu, ex_no, error_code);
4221 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4224 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4225 if (!(vcpu->guest_debug &
4226 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4227 vcpu->arch.dr6 &= ~15;
4228 vcpu->arch.dr6 |= dr6 | DR6_RTM;
4229 if (is_icebp(intr_info))
4230 skip_emulated_instruction(vcpu);
4232 kvm_queue_exception(vcpu, DB_VECTOR);
4235 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4236 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4240 * Update instruction length as we may reinject #BP from
4241 * user space while in guest debugging mode. Reading it for
4242 * #DB as well causes no harm, it is not used in that case.
4244 vmx->vcpu.arch.event_exit_inst_len =
4245 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4246 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4247 rip = kvm_rip_read(vcpu);
4248 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4249 kvm_run->debug.arch.exception = ex_no;
4252 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4253 kvm_run->ex.exception = ex_no;
4254 kvm_run->ex.error_code = error_code;
4260 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4262 ++vcpu->stat.irq_exits;
4266 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4268 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4269 vcpu->mmio_needed = 0;
4273 static int handle_io(struct kvm_vcpu *vcpu)
4275 unsigned long exit_qualification;
4276 int size, in, string;
4279 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4280 string = (exit_qualification & 16) != 0;
4282 ++vcpu->stat.io_exits;
4285 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4287 port = exit_qualification >> 16;
4288 size = (exit_qualification & 7) + 1;
4289 in = (exit_qualification & 8) != 0;
4291 return kvm_fast_pio(vcpu, size, port, in);
4295 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4298 * Patch in the VMCALL instruction:
4300 hypercall[0] = 0x0f;
4301 hypercall[1] = 0x01;
4302 hypercall[2] = 0xc1;
4305 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4306 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4308 if (is_guest_mode(vcpu)) {
4309 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4310 unsigned long orig_val = val;
4313 * We get here when L2 changed cr0 in a way that did not change
4314 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4315 * but did change L0 shadowed bits. So we first calculate the
4316 * effective cr0 value that L1 would like to write into the
4317 * hardware. It consists of the L2-owned bits from the new
4318 * value combined with the L1-owned bits from L1's guest_cr0.
4320 val = (val & ~vmcs12->cr0_guest_host_mask) |
4321 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4323 if (!nested_guest_cr0_valid(vcpu, val))
4326 if (kvm_set_cr0(vcpu, val))
4328 vmcs_writel(CR0_READ_SHADOW, orig_val);
4331 if (to_vmx(vcpu)->nested.vmxon &&
4332 !nested_host_cr0_valid(vcpu, val))
4335 return kvm_set_cr0(vcpu, val);
4339 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4341 if (is_guest_mode(vcpu)) {
4342 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4343 unsigned long orig_val = val;
4345 /* analogously to handle_set_cr0 */
4346 val = (val & ~vmcs12->cr4_guest_host_mask) |
4347 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4348 if (kvm_set_cr4(vcpu, val))
4350 vmcs_writel(CR4_READ_SHADOW, orig_val);
4353 return kvm_set_cr4(vcpu, val);
4356 static int handle_desc(struct kvm_vcpu *vcpu)
4358 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4359 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4362 static int handle_cr(struct kvm_vcpu *vcpu)
4364 unsigned long exit_qualification, val;
4370 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4371 cr = exit_qualification & 15;
4372 reg = (exit_qualification >> 8) & 15;
4373 switch ((exit_qualification >> 4) & 3) {
4374 case 0: /* mov to cr */
4375 val = kvm_register_readl(vcpu, reg);
4376 trace_kvm_cr_write(cr, val);
4379 err = handle_set_cr0(vcpu, val);
4380 return kvm_complete_insn_gp(vcpu, err);
4382 WARN_ON_ONCE(enable_unrestricted_guest);
4383 err = kvm_set_cr3(vcpu, val);
4384 return kvm_complete_insn_gp(vcpu, err);
4386 err = handle_set_cr4(vcpu, val);
4387 return kvm_complete_insn_gp(vcpu, err);
4389 u8 cr8_prev = kvm_get_cr8(vcpu);
4391 err = kvm_set_cr8(vcpu, cr8);
4392 ret = kvm_complete_insn_gp(vcpu, err);
4393 if (lapic_in_kernel(vcpu))
4395 if (cr8_prev <= cr8)
4398 * TODO: we might be squashing a
4399 * KVM_GUESTDBG_SINGLESTEP-triggered
4400 * KVM_EXIT_DEBUG here.
4402 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4408 WARN_ONCE(1, "Guest should always own CR0.TS");
4409 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4410 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4411 return kvm_skip_emulated_instruction(vcpu);
4412 case 1: /*mov from cr*/
4415 WARN_ON_ONCE(enable_unrestricted_guest);
4416 val = kvm_read_cr3(vcpu);
4417 kvm_register_write(vcpu, reg, val);
4418 trace_kvm_cr_read(cr, val);
4419 return kvm_skip_emulated_instruction(vcpu);
4421 val = kvm_get_cr8(vcpu);
4422 kvm_register_write(vcpu, reg, val);
4423 trace_kvm_cr_read(cr, val);
4424 return kvm_skip_emulated_instruction(vcpu);
4428 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4429 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4430 kvm_lmsw(vcpu, val);
4432 return kvm_skip_emulated_instruction(vcpu);
4436 vcpu->run->exit_reason = 0;
4437 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4438 (int)(exit_qualification >> 4) & 3, cr);
4442 static int handle_dr(struct kvm_vcpu *vcpu)
4444 unsigned long exit_qualification;
4447 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4448 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
4450 /* First, if DR does not exist, trigger UD */
4451 if (!kvm_require_dr(vcpu, dr))
4454 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
4455 if (!kvm_require_cpl(vcpu, 0))
4457 dr7 = vmcs_readl(GUEST_DR7);
4460 * As the vm-exit takes precedence over the debug trap, we
4461 * need to emulate the latter, either for the host or the
4462 * guest debugging itself.
4464 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
4465 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
4466 vcpu->run->debug.arch.dr7 = dr7;
4467 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
4468 vcpu->run->debug.arch.exception = DB_VECTOR;
4469 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
4472 vcpu->arch.dr6 &= ~15;
4473 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
4474 kvm_queue_exception(vcpu, DB_VECTOR);
4479 if (vcpu->guest_debug == 0) {
4480 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4481 CPU_BASED_MOV_DR_EXITING);
4484 * No more DR vmexits; force a reload of the debug registers
4485 * and reenter on this instruction. The next vmexit will
4486 * retrieve the full state of the debug registers.
4488 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4492 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
4493 if (exit_qualification & TYPE_MOV_FROM_DR) {
4496 if (kvm_get_dr(vcpu, dr, &val))
4498 kvm_register_write(vcpu, reg, val);
4500 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
4503 return kvm_skip_emulated_instruction(vcpu);
4506 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
4508 return vcpu->arch.dr6;
4511 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
4515 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
4517 get_debugreg(vcpu->arch.db[0], 0);
4518 get_debugreg(vcpu->arch.db[1], 1);
4519 get_debugreg(vcpu->arch.db[2], 2);
4520 get_debugreg(vcpu->arch.db[3], 3);
4521 get_debugreg(vcpu->arch.dr6, 6);
4522 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
4524 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
4525 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
4528 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
4530 vmcs_writel(GUEST_DR7, val);
4533 static int handle_cpuid(struct kvm_vcpu *vcpu)
4535 return kvm_emulate_cpuid(vcpu);
4538 static int handle_rdmsr(struct kvm_vcpu *vcpu)
4540 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4541 struct msr_data msr_info;
4543 msr_info.index = ecx;
4544 msr_info.host_initiated = false;
4545 if (vmx_get_msr(vcpu, &msr_info)) {
4546 trace_kvm_msr_read_ex(ecx);
4547 kvm_inject_gp(vcpu, 0);
4551 trace_kvm_msr_read(ecx, msr_info.data);
4553 /* FIXME: handling of bits 32:63 of rax, rdx */
4554 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
4555 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
4556 return kvm_skip_emulated_instruction(vcpu);
4559 static int handle_wrmsr(struct kvm_vcpu *vcpu)
4561 struct msr_data msr;
4562 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4563 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
4564 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
4568 msr.host_initiated = false;
4569 if (kvm_set_msr(vcpu, &msr) != 0) {
4570 trace_kvm_msr_write_ex(ecx, data);
4571 kvm_inject_gp(vcpu, 0);
4575 trace_kvm_msr_write(ecx, data);
4576 return kvm_skip_emulated_instruction(vcpu);
4579 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
4581 kvm_apic_update_ppr(vcpu);
4585 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
4587 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4588 CPU_BASED_VIRTUAL_INTR_PENDING);
4590 kvm_make_request(KVM_REQ_EVENT, vcpu);
4592 ++vcpu->stat.irq_window_exits;
4596 static int handle_halt(struct kvm_vcpu *vcpu)
4598 return kvm_emulate_halt(vcpu);
4601 static int handle_vmcall(struct kvm_vcpu *vcpu)
4603 return kvm_emulate_hypercall(vcpu);
4606 static int handle_invd(struct kvm_vcpu *vcpu)
4608 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4611 static int handle_invlpg(struct kvm_vcpu *vcpu)
4613 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4615 kvm_mmu_invlpg(vcpu, exit_qualification);
4616 return kvm_skip_emulated_instruction(vcpu);
4619 static int handle_rdpmc(struct kvm_vcpu *vcpu)
4623 err = kvm_rdpmc(vcpu);
4624 return kvm_complete_insn_gp(vcpu, err);
4627 static int handle_wbinvd(struct kvm_vcpu *vcpu)
4629 return kvm_emulate_wbinvd(vcpu);
4632 static int handle_xsetbv(struct kvm_vcpu *vcpu)
4634 u64 new_bv = kvm_read_edx_eax(vcpu);
4635 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
4637 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
4638 return kvm_skip_emulated_instruction(vcpu);
4642 static int handle_xsaves(struct kvm_vcpu *vcpu)
4644 kvm_skip_emulated_instruction(vcpu);
4645 WARN(1, "this should never happen\n");
4649 static int handle_xrstors(struct kvm_vcpu *vcpu)
4651 kvm_skip_emulated_instruction(vcpu);
4652 WARN(1, "this should never happen\n");
4656 static int handle_apic_access(struct kvm_vcpu *vcpu)
4658 if (likely(fasteoi)) {
4659 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4660 int access_type, offset;
4662 access_type = exit_qualification & APIC_ACCESS_TYPE;
4663 offset = exit_qualification & APIC_ACCESS_OFFSET;
4665 * Sane guest uses MOV to write EOI, with written value
4666 * not cared. So make a short-circuit here by avoiding
4667 * heavy instruction emulation.
4669 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
4670 (offset == APIC_EOI)) {
4671 kvm_lapic_set_eoi(vcpu);
4672 return kvm_skip_emulated_instruction(vcpu);
4675 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4678 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
4680 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4681 int vector = exit_qualification & 0xff;
4683 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
4684 kvm_apic_set_eoi_accelerated(vcpu, vector);
4688 static int handle_apic_write(struct kvm_vcpu *vcpu)
4690 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4691 u32 offset = exit_qualification & 0xfff;
4693 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
4694 kvm_apic_write_nodecode(vcpu, offset);
4698 static int handle_task_switch(struct kvm_vcpu *vcpu)
4700 struct vcpu_vmx *vmx = to_vmx(vcpu);
4701 unsigned long exit_qualification;
4702 bool has_error_code = false;
4705 int reason, type, idt_v, idt_index;
4707 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
4708 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
4709 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
4711 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4713 reason = (u32)exit_qualification >> 30;
4714 if (reason == TASK_SWITCH_GATE && idt_v) {
4716 case INTR_TYPE_NMI_INTR:
4717 vcpu->arch.nmi_injected = false;
4718 vmx_set_nmi_mask(vcpu, true);
4720 case INTR_TYPE_EXT_INTR:
4721 case INTR_TYPE_SOFT_INTR:
4722 kvm_clear_interrupt_queue(vcpu);
4724 case INTR_TYPE_HARD_EXCEPTION:
4725 if (vmx->idt_vectoring_info &
4726 VECTORING_INFO_DELIVER_CODE_MASK) {
4727 has_error_code = true;
4729 vmcs_read32(IDT_VECTORING_ERROR_CODE);
4732 case INTR_TYPE_SOFT_EXCEPTION:
4733 kvm_clear_exception_queue(vcpu);
4739 tss_selector = exit_qualification;
4741 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
4742 type != INTR_TYPE_EXT_INTR &&
4743 type != INTR_TYPE_NMI_INTR))
4744 skip_emulated_instruction(vcpu);
4746 if (kvm_task_switch(vcpu, tss_selector,
4747 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
4748 has_error_code, error_code) == EMULATE_FAIL) {
4749 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4750 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4751 vcpu->run->internal.ndata = 0;
4756 * TODO: What about debug traps on tss switch?
4757 * Are we supposed to inject them and update dr6?
4763 static int handle_ept_violation(struct kvm_vcpu *vcpu)
4765 unsigned long exit_qualification;
4769 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4772 * EPT violation happened while executing iret from NMI,
4773 * "blocked by NMI" bit has to be set before next VM entry.
4774 * There are errata that may cause this bit to not be set:
4777 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
4779 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
4780 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
4782 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
4783 trace_kvm_page_fault(gpa, exit_qualification);
4785 /* Is it a read fault? */
4786 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
4787 ? PFERR_USER_MASK : 0;
4788 /* Is it a write fault? */
4789 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
4790 ? PFERR_WRITE_MASK : 0;
4791 /* Is it a fetch fault? */
4792 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
4793 ? PFERR_FETCH_MASK : 0;
4794 /* ept page table entry is present? */
4795 error_code |= (exit_qualification &
4796 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
4797 EPT_VIOLATION_EXECUTABLE))
4798 ? PFERR_PRESENT_MASK : 0;
4800 error_code |= (exit_qualification & 0x100) != 0 ?
4801 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
4803 vcpu->arch.exit_qualification = exit_qualification;
4804 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
4807 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
4812 * A nested guest cannot optimize MMIO vmexits, because we have an
4813 * nGPA here instead of the required GPA.
4815 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
4816 if (!is_guest_mode(vcpu) &&
4817 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
4818 trace_kvm_fast_mmio(gpa);
4820 * Doing kvm_skip_emulated_instruction() depends on undefined
4821 * behavior: Intel's manual doesn't mandate
4822 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
4823 * occurs and while on real hardware it was observed to be set,
4824 * other hypervisors (namely Hyper-V) don't set it, we end up
4825 * advancing IP with some random value. Disable fast mmio when
4826 * running nested and keep it for real hardware in hope that
4827 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
4829 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
4830 return kvm_skip_emulated_instruction(vcpu);
4832 return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
4836 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
4839 static int handle_nmi_window(struct kvm_vcpu *vcpu)
4841 WARN_ON_ONCE(!enable_vnmi);
4842 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4843 CPU_BASED_VIRTUAL_NMI_PENDING);
4844 ++vcpu->stat.nmi_window_exits;
4845 kvm_make_request(KVM_REQ_EVENT, vcpu);
4850 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
4852 struct vcpu_vmx *vmx = to_vmx(vcpu);
4853 enum emulation_result err = EMULATE_DONE;
4856 bool intr_window_requested;
4857 unsigned count = 130;
4860 * We should never reach the point where we are emulating L2
4861 * due to invalid guest state as that means we incorrectly
4862 * allowed a nested VMEntry with an invalid vmcs12.
4864 WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
4866 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4867 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
4869 while (vmx->emulation_required && count-- != 0) {
4870 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
4871 return handle_interrupt_window(&vmx->vcpu);
4873 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
4876 err = kvm_emulate_instruction(vcpu, 0);
4878 if (err == EMULATE_USER_EXIT) {
4879 ++vcpu->stat.mmio_exits;
4884 if (err != EMULATE_DONE)
4885 goto emulation_error;
4887 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
4888 vcpu->arch.exception.pending)
4889 goto emulation_error;
4891 if (vcpu->arch.halt_request) {
4892 vcpu->arch.halt_request = 0;
4893 ret = kvm_vcpu_halt(vcpu);
4897 if (signal_pending(current))
4907 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4908 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4909 vcpu->run->internal.ndata = 0;
4913 static void grow_ple_window(struct kvm_vcpu *vcpu)
4915 struct vcpu_vmx *vmx = to_vmx(vcpu);
4916 int old = vmx->ple_window;
4918 vmx->ple_window = __grow_ple_window(old, ple_window,
4922 if (vmx->ple_window != old)
4923 vmx->ple_window_dirty = true;
4925 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
4928 static void shrink_ple_window(struct kvm_vcpu *vcpu)
4930 struct vcpu_vmx *vmx = to_vmx(vcpu);
4931 int old = vmx->ple_window;
4933 vmx->ple_window = __shrink_ple_window(old, ple_window,
4937 if (vmx->ple_window != old)
4938 vmx->ple_window_dirty = true;
4940 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
4944 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
4946 static void wakeup_handler(void)
4948 struct kvm_vcpu *vcpu;
4949 int cpu = smp_processor_id();
4951 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4952 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
4953 blocked_vcpu_list) {
4954 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
4956 if (pi_test_on(pi_desc) == 1)
4957 kvm_vcpu_kick(vcpu);
4959 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4962 static void vmx_enable_tdp(void)
4964 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
4965 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
4966 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
4967 0ull, VMX_EPT_EXECUTABLE_MASK,
4968 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
4969 VMX_EPT_RWX_MASK, 0ull);
4971 ept_set_mmio_spte_mask();
4976 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
4977 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
4979 static int handle_pause(struct kvm_vcpu *vcpu)
4981 if (!kvm_pause_in_guest(vcpu->kvm))
4982 grow_ple_window(vcpu);
4985 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
4986 * VM-execution control is ignored if CPL > 0. OTOH, KVM
4987 * never set PAUSE_EXITING and just set PLE if supported,
4988 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
4990 kvm_vcpu_on_spin(vcpu, true);
4991 return kvm_skip_emulated_instruction(vcpu);
4994 static int handle_nop(struct kvm_vcpu *vcpu)
4996 return kvm_skip_emulated_instruction(vcpu);
4999 static int handle_mwait(struct kvm_vcpu *vcpu)
5001 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5002 return handle_nop(vcpu);
5005 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5007 kvm_queue_exception(vcpu, UD_VECTOR);
5011 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5016 static int handle_monitor(struct kvm_vcpu *vcpu)
5018 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5019 return handle_nop(vcpu);
5022 static int handle_invpcid(struct kvm_vcpu *vcpu)
5024 u32 vmx_instruction_info;
5028 struct x86_exception e;
5030 unsigned long roots_to_free = 0;
5036 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5037 kvm_queue_exception(vcpu, UD_VECTOR);
5041 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5042 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5045 kvm_inject_gp(vcpu, 0);
5049 /* According to the Intel instruction reference, the memory operand
5050 * is read even if it isn't needed (e.g., for type==all)
5052 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5053 vmx_instruction_info, false, &gva))
5056 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5057 kvm_inject_page_fault(vcpu, &e);
5061 if (operand.pcid >> 12 != 0) {
5062 kvm_inject_gp(vcpu, 0);
5066 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5069 case INVPCID_TYPE_INDIV_ADDR:
5070 if ((!pcid_enabled && (operand.pcid != 0)) ||
5071 is_noncanonical_address(operand.gla, vcpu)) {
5072 kvm_inject_gp(vcpu, 0);
5075 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5076 return kvm_skip_emulated_instruction(vcpu);
5078 case INVPCID_TYPE_SINGLE_CTXT:
5079 if (!pcid_enabled && (operand.pcid != 0)) {
5080 kvm_inject_gp(vcpu, 0);
5084 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5085 kvm_mmu_sync_roots(vcpu);
5086 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5089 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5090 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
5092 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5094 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5096 * If neither the current cr3 nor any of the prev_roots use the
5097 * given PCID, then nothing needs to be done here because a
5098 * resync will happen anyway before switching to any other CR3.
5101 return kvm_skip_emulated_instruction(vcpu);
5103 case INVPCID_TYPE_ALL_NON_GLOBAL:
5105 * Currently, KVM doesn't mark global entries in the shadow
5106 * page tables, so a non-global flush just degenerates to a
5107 * global flush. If needed, we could optimize this later by
5108 * keeping track of global entries in shadow page tables.
5112 case INVPCID_TYPE_ALL_INCL_GLOBAL:
5113 kvm_mmu_unload(vcpu);
5114 return kvm_skip_emulated_instruction(vcpu);
5117 BUG(); /* We have already checked above that type <= 3 */
5121 static int handle_pml_full(struct kvm_vcpu *vcpu)
5123 unsigned long exit_qualification;
5125 trace_kvm_pml_full(vcpu->vcpu_id);
5127 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5130 * PML buffer FULL happened while executing iret from NMI,
5131 * "blocked by NMI" bit has to be set before next VM entry.
5133 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5135 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5136 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5137 GUEST_INTR_STATE_NMI);
5140 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5141 * here.., and there's no userspace involvement needed for PML.
5146 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5148 if (!to_vmx(vcpu)->req_immediate_exit)
5149 kvm_lapic_expired_hv_timer(vcpu);
5154 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5155 * are overwritten by nested_vmx_setup() when nested=1.
5157 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5159 kvm_queue_exception(vcpu, UD_VECTOR);
5163 static int handle_encls(struct kvm_vcpu *vcpu)
5166 * SGX virtualization is not yet supported. There is no software
5167 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5168 * to prevent the guest from executing ENCLS.
5170 kvm_queue_exception(vcpu, UD_VECTOR);
5175 * The exit handlers return 1 if the exit was handled fully and guest execution
5176 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5177 * to be done to userspace and return 0.
5179 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5180 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
5181 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5182 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5183 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5184 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5185 [EXIT_REASON_CR_ACCESS] = handle_cr,
5186 [EXIT_REASON_DR_ACCESS] = handle_dr,
5187 [EXIT_REASON_CPUID] = handle_cpuid,
5188 [EXIT_REASON_MSR_READ] = handle_rdmsr,
5189 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
5190 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
5191 [EXIT_REASON_HLT] = handle_halt,
5192 [EXIT_REASON_INVD] = handle_invd,
5193 [EXIT_REASON_INVLPG] = handle_invlpg,
5194 [EXIT_REASON_RDPMC] = handle_rdpmc,
5195 [EXIT_REASON_VMCALL] = handle_vmcall,
5196 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5197 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5198 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5199 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5200 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5201 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5202 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5203 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5204 [EXIT_REASON_VMON] = handle_vmx_instruction,
5205 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5206 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5207 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5208 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5209 [EXIT_REASON_WBINVD] = handle_wbinvd,
5210 [EXIT_REASON_XSETBV] = handle_xsetbv,
5211 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5212 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5213 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5214 [EXIT_REASON_LDTR_TR] = handle_desc,
5215 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5216 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5217 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5218 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5219 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5220 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5221 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5222 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5223 [EXIT_REASON_RDRAND] = handle_invalid_op,
5224 [EXIT_REASON_RDSEED] = handle_invalid_op,
5225 [EXIT_REASON_XSAVES] = handle_xsaves,
5226 [EXIT_REASON_XRSTORS] = handle_xrstors,
5227 [EXIT_REASON_PML_FULL] = handle_pml_full,
5228 [EXIT_REASON_INVPCID] = handle_invpcid,
5229 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5230 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5231 [EXIT_REASON_ENCLS] = handle_encls,
5234 static const int kvm_vmx_max_exit_handlers =
5235 ARRAY_SIZE(kvm_vmx_exit_handlers);
5237 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5239 *info1 = vmcs_readl(EXIT_QUALIFICATION);
5240 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
5243 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5246 __free_page(vmx->pml_pg);
5251 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5253 struct vcpu_vmx *vmx = to_vmx(vcpu);
5257 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5259 /* Do nothing if PML buffer is empty */
5260 if (pml_idx == (PML_ENTITY_NUM - 1))
5263 /* PML index always points to next available PML buffer entity */
5264 if (pml_idx >= PML_ENTITY_NUM)
5269 pml_buf = page_address(vmx->pml_pg);
5270 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5273 gpa = pml_buf[pml_idx];
5274 WARN_ON(gpa & (PAGE_SIZE - 1));
5275 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5278 /* reset PML index */
5279 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5283 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5284 * Called before reporting dirty_bitmap to userspace.
5286 static void kvm_flush_pml_buffers(struct kvm *kvm)
5289 struct kvm_vcpu *vcpu;
5291 * We only need to kick vcpu out of guest mode here, as PML buffer
5292 * is flushed at beginning of all VMEXITs, and it's obvious that only
5293 * vcpus running in guest are possible to have unflushed GPAs in PML
5296 kvm_for_each_vcpu(i, vcpu, kvm)
5297 kvm_vcpu_kick(vcpu);
5300 static void vmx_dump_sel(char *name, uint32_t sel)
5302 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5303 name, vmcs_read16(sel),
5304 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5305 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5306 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5309 static void vmx_dump_dtsel(char *name, uint32_t limit)
5311 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5312 name, vmcs_read32(limit),
5313 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5316 static void dump_vmcs(void)
5318 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5319 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5320 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5321 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5322 u32 secondary_exec_control = 0;
5323 unsigned long cr4 = vmcs_readl(GUEST_CR4);
5324 u64 efer = vmcs_read64(GUEST_IA32_EFER);
5327 if (cpu_has_secondary_exec_ctrls())
5328 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5330 pr_err("*** Guest State ***\n");
5331 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5332 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5333 vmcs_readl(CR0_GUEST_HOST_MASK));
5334 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5335 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5336 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5337 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5338 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5340 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5341 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5342 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5343 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5345 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5346 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5347 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5348 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5349 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5350 vmcs_readl(GUEST_SYSENTER_ESP),
5351 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5352 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5353 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5354 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5355 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5356 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5357 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5358 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5359 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5360 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5361 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5362 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5363 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5364 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5365 efer, vmcs_read64(GUEST_IA32_PAT));
5366 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5367 vmcs_read64(GUEST_IA32_DEBUGCTL),
5368 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5369 if (cpu_has_load_perf_global_ctrl() &&
5370 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5371 pr_err("PerfGlobCtl = 0x%016llx\n",
5372 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5373 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5374 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5375 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5376 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5377 vmcs_read32(GUEST_ACTIVITY_STATE));
5378 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5379 pr_err("InterruptStatus = %04x\n",
5380 vmcs_read16(GUEST_INTR_STATUS));
5382 pr_err("*** Host State ***\n");
5383 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5384 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5385 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5386 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5387 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5388 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5389 vmcs_read16(HOST_TR_SELECTOR));
5390 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5391 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5392 vmcs_readl(HOST_TR_BASE));
5393 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5394 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5395 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5396 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5397 vmcs_readl(HOST_CR4));
5398 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5399 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5400 vmcs_read32(HOST_IA32_SYSENTER_CS),
5401 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5402 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5403 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5404 vmcs_read64(HOST_IA32_EFER),
5405 vmcs_read64(HOST_IA32_PAT));
5406 if (cpu_has_load_perf_global_ctrl() &&
5407 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5408 pr_err("PerfGlobCtl = 0x%016llx\n",
5409 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5411 pr_err("*** Control State ***\n");
5412 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5413 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5414 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5415 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5416 vmcs_read32(EXCEPTION_BITMAP),
5417 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5418 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5419 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5420 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5421 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5422 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5423 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5424 vmcs_read32(VM_EXIT_INTR_INFO),
5425 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5426 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5427 pr_err(" reason=%08x qualification=%016lx\n",
5428 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5429 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5430 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5431 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5432 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5433 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5434 pr_err("TSC Multiplier = 0x%016llx\n",
5435 vmcs_read64(TSC_MULTIPLIER));
5436 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
5437 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5438 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5439 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5440 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5441 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5442 n = vmcs_read32(CR3_TARGET_COUNT);
5443 for (i = 0; i + 1 < n; i += 4)
5444 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
5445 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
5446 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
5448 pr_err("CR3 target%u=%016lx\n",
5449 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
5450 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5451 pr_err("PLE Gap=%08x Window=%08x\n",
5452 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5453 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5454 pr_err("Virtual processor ID = 0x%04x\n",
5455 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5459 * The guest has exited. See if we can fix it or if we need userspace
5462 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
5464 struct vcpu_vmx *vmx = to_vmx(vcpu);
5465 u32 exit_reason = vmx->exit_reason;
5466 u32 vectoring_info = vmx->idt_vectoring_info;
5468 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
5471 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5472 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5473 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5474 * mode as if vcpus is in root mode, the PML buffer must has been
5478 vmx_flush_pml_buffer(vcpu);
5480 /* If guest state is invalid, start emulating */
5481 if (vmx->emulation_required)
5482 return handle_invalid_guest_state(vcpu);
5484 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
5485 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
5487 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5489 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5490 vcpu->run->fail_entry.hardware_entry_failure_reason
5495 if (unlikely(vmx->fail)) {
5496 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5497 vcpu->run->fail_entry.hardware_entry_failure_reason
5498 = vmcs_read32(VM_INSTRUCTION_ERROR);
5504 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5505 * delivery event since it indicates guest is accessing MMIO.
5506 * The vm-exit can be triggered again after return to guest that
5507 * will cause infinite loop.
5509 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5510 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5511 exit_reason != EXIT_REASON_EPT_VIOLATION &&
5512 exit_reason != EXIT_REASON_PML_FULL &&
5513 exit_reason != EXIT_REASON_TASK_SWITCH)) {
5514 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5515 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
5516 vcpu->run->internal.ndata = 3;
5517 vcpu->run->internal.data[0] = vectoring_info;
5518 vcpu->run->internal.data[1] = exit_reason;
5519 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
5520 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
5521 vcpu->run->internal.ndata++;
5522 vcpu->run->internal.data[3] =
5523 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5528 if (unlikely(!enable_vnmi &&
5529 vmx->loaded_vmcs->soft_vnmi_blocked)) {
5530 if (vmx_interrupt_allowed(vcpu)) {
5531 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5532 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
5533 vcpu->arch.nmi_pending) {
5535 * This CPU don't support us in finding the end of an
5536 * NMI-blocked window if the guest runs with IRQs
5537 * disabled. So we pull the trigger after 1 s of
5538 * futile waiting, but inform the user about this.
5540 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
5541 "state on VCPU %d after 1 s timeout\n",
5542 __func__, vcpu->vcpu_id);
5543 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5547 if (exit_reason < kvm_vmx_max_exit_handlers
5548 && kvm_vmx_exit_handlers[exit_reason])
5549 return kvm_vmx_exit_handlers[exit_reason](vcpu);
5551 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
5553 kvm_queue_exception(vcpu, UD_VECTOR);
5559 * Software based L1D cache flush which is used when microcode providing
5560 * the cache control MSR is not loaded.
5562 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
5563 * flush it is required to read in 64 KiB because the replacement algorithm
5564 * is not exactly LRU. This could be sized at runtime via topology
5565 * information but as all relevant affected CPUs have 32KiB L1D cache size
5566 * there is no point in doing so.
5568 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
5570 int size = PAGE_SIZE << L1D_CACHE_ORDER;
5573 * This code is only executed when the the flush mode is 'cond' or
5576 if (static_branch_likely(&vmx_l1d_flush_cond)) {
5580 * Clear the per-vcpu flush bit, it gets set again
5581 * either from vcpu_run() or from one of the unsafe
5584 flush_l1d = vcpu->arch.l1tf_flush_l1d;
5585 vcpu->arch.l1tf_flush_l1d = false;
5588 * Clear the per-cpu flush bit, it gets set again from
5589 * the interrupt handlers.
5591 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
5592 kvm_clear_cpu_l1tf_flush_l1d();
5598 vcpu->stat.l1d_flush++;
5600 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
5601 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
5606 /* First ensure the pages are in the TLB */
5607 "xorl %%eax, %%eax\n"
5608 ".Lpopulate_tlb:\n\t"
5609 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5610 "addl $4096, %%eax\n\t"
5611 "cmpl %%eax, %[size]\n\t"
5612 "jne .Lpopulate_tlb\n\t"
5613 "xorl %%eax, %%eax\n\t"
5615 /* Now fill the cache */
5616 "xorl %%eax, %%eax\n"
5618 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5619 "addl $64, %%eax\n\t"
5620 "cmpl %%eax, %[size]\n\t"
5621 "jne .Lfill_cache\n\t"
5623 :: [flush_pages] "r" (vmx_l1d_flush_pages),
5625 : "eax", "ebx", "ecx", "edx");
5628 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5630 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5632 if (is_guest_mode(vcpu) &&
5633 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
5636 if (irr == -1 || tpr < irr) {
5637 vmcs_write32(TPR_THRESHOLD, 0);
5641 vmcs_write32(TPR_THRESHOLD, irr);
5644 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5646 u32 sec_exec_control;
5648 if (!lapic_in_kernel(vcpu))
5651 if (!flexpriority_enabled &&
5652 !cpu_has_vmx_virtualize_x2apic_mode())
5655 /* Postpone execution until vmcs01 is the current VMCS. */
5656 if (is_guest_mode(vcpu)) {
5657 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
5661 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5662 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
5663 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
5665 switch (kvm_get_apic_mode(vcpu)) {
5666 case LAPIC_MODE_INVALID:
5667 WARN_ONCE(true, "Invalid local APIC state");
5668 case LAPIC_MODE_DISABLED:
5670 case LAPIC_MODE_XAPIC:
5671 if (flexpriority_enabled) {
5673 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5674 vmx_flush_tlb(vcpu, true);
5677 case LAPIC_MODE_X2APIC:
5678 if (cpu_has_vmx_virtualize_x2apic_mode())
5680 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5683 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
5685 vmx_update_msr_bitmap(vcpu);
5688 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
5690 if (!is_guest_mode(vcpu)) {
5691 vmcs_write64(APIC_ACCESS_ADDR, hpa);
5692 vmx_flush_tlb(vcpu, true);
5696 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
5704 status = vmcs_read16(GUEST_INTR_STATUS);
5706 if (max_isr != old) {
5708 status |= max_isr << 8;
5709 vmcs_write16(GUEST_INTR_STATUS, status);
5713 static void vmx_set_rvi(int vector)
5721 status = vmcs_read16(GUEST_INTR_STATUS);
5722 old = (u8)status & 0xff;
5723 if ((u8)vector != old) {
5725 status |= (u8)vector;
5726 vmcs_write16(GUEST_INTR_STATUS, status);
5730 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
5733 * When running L2, updating RVI is only relevant when
5734 * vmcs12 virtual-interrupt-delivery enabled.
5735 * However, it can be enabled only when L1 also
5736 * intercepts external-interrupts and in that case
5737 * we should not update vmcs02 RVI but instead intercept
5738 * interrupt. Therefore, do nothing when running L2.
5740 if (!is_guest_mode(vcpu))
5741 vmx_set_rvi(max_irr);
5744 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
5746 struct vcpu_vmx *vmx = to_vmx(vcpu);
5748 bool max_irr_updated;
5750 WARN_ON(!vcpu->arch.apicv_active);
5751 if (pi_test_on(&vmx->pi_desc)) {
5752 pi_clear_on(&vmx->pi_desc);
5754 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
5755 * But on x86 this is just a compiler barrier anyway.
5757 smp_mb__after_atomic();
5759 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
5762 * If we are running L2 and L1 has a new pending interrupt
5763 * which can be injected, we should re-evaluate
5764 * what should be done with this new L1 interrupt.
5765 * If L1 intercepts external-interrupts, we should
5766 * exit from L2 to L1. Otherwise, interrupt should be
5767 * delivered directly to L2.
5769 if (is_guest_mode(vcpu) && max_irr_updated) {
5770 if (nested_exit_on_intr(vcpu))
5771 kvm_vcpu_exiting_guest_mode(vcpu);
5773 kvm_make_request(KVM_REQ_EVENT, vcpu);
5776 max_irr = kvm_lapic_find_highest_irr(vcpu);
5778 vmx_hwapic_irr_update(vcpu, max_irr);
5782 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
5784 if (!kvm_vcpu_apicv_active(vcpu))
5787 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
5788 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
5789 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
5790 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
5793 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
5795 struct vcpu_vmx *vmx = to_vmx(vcpu);
5797 pi_clear_on(&vmx->pi_desc);
5798 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
5801 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
5803 u32 exit_intr_info = 0;
5804 u16 basic_exit_reason = (u16)vmx->exit_reason;
5806 if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
5807 || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
5810 if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
5811 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5812 vmx->exit_intr_info = exit_intr_info;
5814 /* if exit due to PF check for async PF */
5815 if (is_page_fault(exit_intr_info))
5816 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5818 /* Handle machine checks before interrupts are enabled */
5819 if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
5820 is_machine_check(exit_intr_info))
5821 kvm_machine_check();
5823 /* We need to handle NMIs before interrupts are enabled */
5824 if (is_nmi(exit_intr_info)) {
5825 kvm_before_interrupt(&vmx->vcpu);
5827 kvm_after_interrupt(&vmx->vcpu);
5831 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
5833 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5835 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
5836 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
5837 unsigned int vector;
5838 unsigned long entry;
5840 struct vcpu_vmx *vmx = to_vmx(vcpu);
5841 #ifdef CONFIG_X86_64
5845 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
5846 desc = (gate_desc *)vmx->host_idt_base + vector;
5847 entry = gate_offset(desc);
5849 #ifdef CONFIG_X86_64
5850 "mov %%" _ASM_SP ", %[sp]\n\t"
5851 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
5856 __ASM_SIZE(push) " $%c[cs]\n\t"
5859 #ifdef CONFIG_X86_64
5864 THUNK_TARGET(entry),
5865 [ss]"i"(__KERNEL_DS),
5866 [cs]"i"(__KERNEL_CS)
5870 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
5872 static bool vmx_has_emulated_msr(int index)
5875 case MSR_IA32_SMBASE:
5877 * We cannot do SMM unless we can run the guest in big
5880 return enable_unrestricted_guest || emulate_invalid_guest_state;
5881 case MSR_AMD64_VIRT_SPEC_CTRL:
5882 /* This is AMD only. */
5889 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
5894 bool idtv_info_valid;
5896 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
5899 if (vmx->loaded_vmcs->nmi_known_unmasked)
5902 * Can't use vmx->exit_intr_info since we're not sure what
5903 * the exit reason is.
5905 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5906 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
5907 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
5909 * SDM 3: 27.7.1.2 (September 2008)
5910 * Re-set bit "block by NMI" before VM entry if vmexit caused by
5911 * a guest IRET fault.
5912 * SDM 3: 23.2.2 (September 2008)
5913 * Bit 12 is undefined in any of the following cases:
5914 * If the VM exit sets the valid bit in the IDT-vectoring
5915 * information field.
5916 * If the VM exit is due to a double fault.
5918 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
5919 vector != DF_VECTOR && !idtv_info_valid)
5920 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5921 GUEST_INTR_STATE_NMI);
5923 vmx->loaded_vmcs->nmi_known_unmasked =
5924 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
5925 & GUEST_INTR_STATE_NMI);
5926 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
5927 vmx->loaded_vmcs->vnmi_blocked_time +=
5928 ktime_to_ns(ktime_sub(ktime_get(),
5929 vmx->loaded_vmcs->entry_time));
5932 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
5933 u32 idt_vectoring_info,
5934 int instr_len_field,
5935 int error_code_field)
5939 bool idtv_info_valid;
5941 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
5943 vcpu->arch.nmi_injected = false;
5944 kvm_clear_exception_queue(vcpu);
5945 kvm_clear_interrupt_queue(vcpu);
5947 if (!idtv_info_valid)
5950 kvm_make_request(KVM_REQ_EVENT, vcpu);
5952 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
5953 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
5956 case INTR_TYPE_NMI_INTR:
5957 vcpu->arch.nmi_injected = true;
5959 * SDM 3: 27.7.1.2 (September 2008)
5960 * Clear bit "block by NMI" before VM entry if a NMI
5963 vmx_set_nmi_mask(vcpu, false);
5965 case INTR_TYPE_SOFT_EXCEPTION:
5966 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
5968 case INTR_TYPE_HARD_EXCEPTION:
5969 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
5970 u32 err = vmcs_read32(error_code_field);
5971 kvm_requeue_exception_e(vcpu, vector, err);
5973 kvm_requeue_exception(vcpu, vector);
5975 case INTR_TYPE_SOFT_INTR:
5976 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
5978 case INTR_TYPE_EXT_INTR:
5979 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
5986 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
5988 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
5989 VM_EXIT_INSTRUCTION_LEN,
5990 IDT_VECTORING_ERROR_CODE);
5993 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
5995 __vmx_complete_interrupts(vcpu,
5996 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5997 VM_ENTRY_INSTRUCTION_LEN,
5998 VM_ENTRY_EXCEPTION_ERROR_CODE);
6000 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6003 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6006 struct perf_guest_switch_msr *msrs;
6008 msrs = perf_guest_get_msrs(&nr_msrs);
6013 for (i = 0; i < nr_msrs; i++)
6014 if (msrs[i].host == msrs[i].guest)
6015 clear_atomic_switch_msr(vmx, msrs[i].msr);
6017 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6018 msrs[i].host, false);
6021 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
6023 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
6024 if (!vmx->loaded_vmcs->hv_timer_armed)
6025 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
6026 PIN_BASED_VMX_PREEMPTION_TIMER);
6027 vmx->loaded_vmcs->hv_timer_armed = true;
6030 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6032 struct vcpu_vmx *vmx = to_vmx(vcpu);
6036 if (vmx->req_immediate_exit) {
6037 vmx_arm_hv_timer(vmx, 0);
6041 if (vmx->hv_deadline_tsc != -1) {
6043 if (vmx->hv_deadline_tsc > tscl)
6044 /* set_hv_timer ensures the delta fits in 32-bits */
6045 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6046 cpu_preemption_timer_multi);
6050 vmx_arm_hv_timer(vmx, delta_tsc);
6054 if (vmx->loaded_vmcs->hv_timer_armed)
6055 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
6056 PIN_BASED_VMX_PREEMPTION_TIMER);
6057 vmx->loaded_vmcs->hv_timer_armed = false;
6060 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
6062 struct vcpu_vmx *vmx = to_vmx(vcpu);
6063 unsigned long cr3, cr4, evmcs_rsp;
6065 /* Record the guest's net vcpu time for enforced NMI injections. */
6066 if (unlikely(!enable_vnmi &&
6067 vmx->loaded_vmcs->soft_vnmi_blocked))
6068 vmx->loaded_vmcs->entry_time = ktime_get();
6070 /* Don't enter VMX if guest state is invalid, let the exit handler
6071 start emulation until we arrive back to a valid state */
6072 if (vmx->emulation_required)
6075 if (vmx->ple_window_dirty) {
6076 vmx->ple_window_dirty = false;
6077 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6080 if (vmx->nested.need_vmcs12_sync)
6081 nested_sync_from_vmcs12(vcpu);
6083 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
6084 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6085 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
6086 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6088 cr3 = __get_current_cr3_fast();
6089 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6090 vmcs_writel(HOST_CR3, cr3);
6091 vmx->loaded_vmcs->host_state.cr3 = cr3;
6094 cr4 = cr4_read_shadow();
6095 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6096 vmcs_writel(HOST_CR4, cr4);
6097 vmx->loaded_vmcs->host_state.cr4 = cr4;
6100 /* When single-stepping over STI and MOV SS, we must clear the
6101 * corresponding interruptibility bits in the guest state. Otherwise
6102 * vmentry fails as it then expects bit 14 (BS) in pending debug
6103 * exceptions being set, but that's not correct for the guest debugging
6105 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6106 vmx_set_interrupt_shadow(vcpu, 0);
6108 if (static_cpu_has(X86_FEATURE_PKU) &&
6109 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
6110 vcpu->arch.pkru != vmx->host_pkru)
6111 __write_pkru(vcpu->arch.pkru);
6113 atomic_switch_perf_msrs(vmx);
6115 vmx_update_hv_timer(vcpu);
6118 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6119 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6120 * is no need to worry about the conditional branch over the wrmsr
6121 * being speculatively taken.
6123 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6125 vmx->__launched = vmx->loaded_vmcs->launched;
6127 evmcs_rsp = static_branch_unlikely(&enable_evmcs) ?
6128 (unsigned long)¤t_evmcs->host_rsp : 0;
6130 if (static_branch_unlikely(&vmx_l1d_should_flush))
6131 vmx_l1d_flush(vcpu);
6134 /* Store host registers */
6135 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
6136 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
6137 "push %%" _ASM_CX " \n\t"
6138 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
6140 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
6141 /* Avoid VMWRITE when Enlightened VMCS is in use */
6142 "test %%" _ASM_SI ", %%" _ASM_SI " \n\t"
6144 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
6147 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
6149 /* Reload cr2 if changed */
6150 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
6151 "mov %%cr2, %%" _ASM_DX " \n\t"
6152 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
6154 "mov %%" _ASM_AX", %%cr2 \n\t"
6156 /* Check if vmlaunch or vmresume is needed */
6157 "cmpl $0, %c[launched](%0) \n\t"
6158 /* Load guest registers. Don't clobber flags. */
6159 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
6160 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
6161 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
6162 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
6163 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
6164 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
6165 #ifdef CONFIG_X86_64
6166 "mov %c[r8](%0), %%r8 \n\t"
6167 "mov %c[r9](%0), %%r9 \n\t"
6168 "mov %c[r10](%0), %%r10 \n\t"
6169 "mov %c[r11](%0), %%r11 \n\t"
6170 "mov %c[r12](%0), %%r12 \n\t"
6171 "mov %c[r13](%0), %%r13 \n\t"
6172 "mov %c[r14](%0), %%r14 \n\t"
6173 "mov %c[r15](%0), %%r15 \n\t"
6175 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
6177 /* Enter guest mode */
6179 __ex("vmlaunch") "\n\t"
6181 "1: " __ex("vmresume") "\n\t"
6183 /* Save guest registers, load host registers, keep flags */
6184 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
6186 "setbe %c[fail](%0)\n\t"
6187 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
6188 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
6189 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
6190 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
6191 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
6192 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
6193 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
6194 #ifdef CONFIG_X86_64
6195 "mov %%r8, %c[r8](%0) \n\t"
6196 "mov %%r9, %c[r9](%0) \n\t"
6197 "mov %%r10, %c[r10](%0) \n\t"
6198 "mov %%r11, %c[r11](%0) \n\t"
6199 "mov %%r12, %c[r12](%0) \n\t"
6200 "mov %%r13, %c[r13](%0) \n\t"
6201 "mov %%r14, %c[r14](%0) \n\t"
6202 "mov %%r15, %c[r15](%0) \n\t"
6204 * Clear host registers marked as clobbered to prevent
6207 "xor %%r8d, %%r8d \n\t"
6208 "xor %%r9d, %%r9d \n\t"
6209 "xor %%r10d, %%r10d \n\t"
6210 "xor %%r11d, %%r11d \n\t"
6211 "xor %%r12d, %%r12d \n\t"
6212 "xor %%r13d, %%r13d \n\t"
6213 "xor %%r14d, %%r14d \n\t"
6214 "xor %%r15d, %%r15d \n\t"
6216 "mov %%cr2, %%" _ASM_AX " \n\t"
6217 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
6219 "xor %%eax, %%eax \n\t"
6220 "xor %%ebx, %%ebx \n\t"
6221 "xor %%esi, %%esi \n\t"
6222 "xor %%edi, %%edi \n\t"
6223 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
6224 ".pushsection .rodata \n\t"
6225 ".global vmx_return \n\t"
6226 "vmx_return: " _ASM_PTR " 2b \n\t"
6228 : : "c"(vmx), "d"((unsigned long)HOST_RSP), "S"(evmcs_rsp),
6229 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
6230 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
6231 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
6232 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
6233 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
6234 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
6235 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
6236 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
6237 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
6238 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
6239 #ifdef CONFIG_X86_64
6240 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
6241 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
6242 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
6243 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
6244 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
6245 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
6246 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
6247 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
6249 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
6250 [wordsize]"i"(sizeof(ulong))
6252 #ifdef CONFIG_X86_64
6253 , "rax", "rbx", "rdi"
6254 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
6256 , "eax", "ebx", "edi"
6261 * We do not use IBRS in the kernel. If this vCPU has used the
6262 * SPEC_CTRL MSR it may have left it on; save the value and
6263 * turn it off. This is much more efficient than blindly adding
6264 * it to the atomic save/restore list. Especially as the former
6265 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6267 * For non-nested case:
6268 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6272 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6275 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6276 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6278 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6280 /* Eliminate branch target predictions from guest mode */
6283 /* All fields are clean at this point */
6284 if (static_branch_unlikely(&enable_evmcs))
6285 current_evmcs->hv_clean_fields |=
6286 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6288 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6289 if (vmx->host_debugctlmsr)
6290 update_debugctlmsr(vmx->host_debugctlmsr);
6292 #ifndef CONFIG_X86_64
6294 * The sysexit path does not restore ds/es, so we must set them to
6295 * a reasonable value ourselves.
6297 * We can't defer this to vmx_prepare_switch_to_host() since that
6298 * function may be executed in interrupt context, which saves and
6299 * restore segments around it, nullifying its effect.
6301 loadsegment(ds, __USER_DS);
6302 loadsegment(es, __USER_DS);
6305 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
6306 | (1 << VCPU_EXREG_RFLAGS)
6307 | (1 << VCPU_EXREG_PDPTR)
6308 | (1 << VCPU_EXREG_SEGMENTS)
6309 | (1 << VCPU_EXREG_CR3));
6310 vcpu->arch.regs_dirty = 0;
6313 * eager fpu is enabled if PKEY is supported and CR4 is switched
6314 * back on host, so it is safe to read guest PKRU from current
6317 if (static_cpu_has(X86_FEATURE_PKU) &&
6318 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
6319 vcpu->arch.pkru = __read_pkru();
6320 if (vcpu->arch.pkru != vmx->host_pkru)
6321 __write_pkru(vmx->host_pkru);
6324 vmx->nested.nested_run_pending = 0;
6325 vmx->idt_vectoring_info = 0;
6327 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
6328 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6331 vmx->loaded_vmcs->launched = 1;
6332 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6334 vmx_complete_atomic_exit(vmx);
6335 vmx_recover_nmi_blocking(vmx);
6336 vmx_complete_interrupts(vmx);
6338 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
6340 static struct kvm *vmx_vm_alloc(void)
6342 struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
6343 return &kvm_vmx->kvm;
6346 static void vmx_vm_free(struct kvm *kvm)
6348 vfree(to_kvm_vmx(kvm));
6351 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6353 struct vcpu_vmx *vmx = to_vmx(vcpu);
6356 vmx_destroy_pml_buffer(vmx);
6357 free_vpid(vmx->vpid);
6358 leave_guest_mode(vcpu);
6359 nested_vmx_free_vcpu(vcpu);
6360 free_loaded_vmcs(vmx->loaded_vmcs);
6361 kfree(vmx->guest_msrs);
6362 kvm_vcpu_uninit(vcpu);
6363 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6364 kmem_cache_free(kvm_vcpu_cache, vmx);
6367 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
6370 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
6371 unsigned long *msr_bitmap;
6375 return ERR_PTR(-ENOMEM);
6377 vmx->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache, GFP_KERNEL);
6378 if (!vmx->vcpu.arch.guest_fpu) {
6379 printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
6381 goto free_partial_vcpu;
6384 vmx->vpid = allocate_vpid();
6386 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
6393 * If PML is turned on, failure on enabling PML just results in failure
6394 * of creating the vcpu, therefore we can simplify PML logic (by
6395 * avoiding dealing with cases, such as enabling PML partially on vcpus
6396 * for the guest, etc.
6399 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
6404 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
6405 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
6408 if (!vmx->guest_msrs)
6411 err = alloc_loaded_vmcs(&vmx->vmcs01);
6415 msr_bitmap = vmx->vmcs01.msr_bitmap;
6416 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6417 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6418 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6419 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6420 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6421 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6422 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6423 vmx->msr_bitmap_mode = 0;
6425 vmx->loaded_vmcs = &vmx->vmcs01;
6427 vmx_vcpu_load(&vmx->vcpu, cpu);
6428 vmx->vcpu.cpu = cpu;
6429 vmx_vcpu_setup(vmx);
6430 vmx_vcpu_put(&vmx->vcpu);
6432 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
6433 err = alloc_apic_access_page(kvm);
6438 if (enable_ept && !enable_unrestricted_guest) {
6439 err = init_rmode_identity_map(kvm);
6445 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
6447 kvm_vcpu_apicv_active(&vmx->vcpu));
6449 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6451 vmx->nested.posted_intr_nv = -1;
6452 vmx->nested.current_vmptr = -1ull;
6454 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
6457 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6458 * or POSTED_INTR_WAKEUP_VECTOR.
6460 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6461 vmx->pi_desc.sn = 1;
6463 vmx->ept_pointer = INVALID_PAGE;
6468 free_loaded_vmcs(vmx->loaded_vmcs);
6470 kfree(vmx->guest_msrs);
6472 vmx_destroy_pml_buffer(vmx);
6474 kvm_vcpu_uninit(&vmx->vcpu);
6476 free_vpid(vmx->vpid);
6477 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6479 kmem_cache_free(kvm_vcpu_cache, vmx);
6480 return ERR_PTR(err);
6483 #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/l1tf.html for details.\n"
6484 #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/l1tf.html for details.\n"
6486 static int vmx_vm_init(struct kvm *kvm)
6488 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
6491 kvm->arch.pause_in_guest = true;
6493 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6494 switch (l1tf_mitigation) {
6495 case L1TF_MITIGATION_OFF:
6496 case L1TF_MITIGATION_FLUSH_NOWARN:
6497 /* 'I explicitly don't care' is set */
6499 case L1TF_MITIGATION_FLUSH:
6500 case L1TF_MITIGATION_FLUSH_NOSMT:
6501 case L1TF_MITIGATION_FULL:
6503 * Warn upon starting the first VM in a potentially
6504 * insecure environment.
6506 if (cpu_smt_control == CPU_SMT_ENABLED)
6507 pr_warn_once(L1TF_MSG_SMT);
6508 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6509 pr_warn_once(L1TF_MSG_L1D);
6511 case L1TF_MITIGATION_FULL_FORCE:
6512 /* Flush is enforced */
6519 static void __init vmx_check_processor_compat(void *rtn)
6521 struct vmcs_config vmcs_conf;
6522 struct vmx_capability vmx_cap;
6525 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
6528 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept,
6530 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6531 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6532 smp_processor_id());
6537 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6542 /* For VT-d and EPT combination
6543 * 1. MMIO: always map as UC
6545 * a. VT-d without snooping control feature: can't guarantee the
6546 * result, try to trust guest.
6547 * b. VT-d with snooping control feature: snooping control feature of
6548 * VT-d engine can guarantee the cache correctness. Just set it
6549 * to WB to keep consistent with host. So the same as item 3.
6550 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
6551 * consistent with host MTRR
6554 cache = MTRR_TYPE_UNCACHABLE;
6558 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
6559 ipat = VMX_EPT_IPAT_BIT;
6560 cache = MTRR_TYPE_WRBACK;
6564 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
6565 ipat = VMX_EPT_IPAT_BIT;
6566 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
6567 cache = MTRR_TYPE_WRBACK;
6569 cache = MTRR_TYPE_UNCACHABLE;
6573 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
6576 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
6579 static int vmx_get_lpage_level(void)
6581 if (enable_ept && !cpu_has_vmx_ept_1g_page())
6582 return PT_DIRECTORY_LEVEL;
6584 /* For shadow and EPT supported 1GB page */
6585 return PT_PDPE_LEVEL;
6588 static void vmcs_set_secondary_exec_control(u32 new_ctl)
6591 * These bits in the secondary execution controls field
6592 * are dynamic, the others are mostly based on the hypervisor
6593 * architecture and the guest's CPUID. Do not touch the
6597 SECONDARY_EXEC_SHADOW_VMCS |
6598 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
6599 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6600 SECONDARY_EXEC_DESC;
6602 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6604 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6605 (new_ctl & ~mask) | (cur_ctl & mask));
6609 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
6610 * (indicating "allowed-1") if they are supported in the guest's CPUID.
6612 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
6614 struct vcpu_vmx *vmx = to_vmx(vcpu);
6615 struct kvm_cpuid_entry2 *entry;
6617 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
6618 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
6620 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
6621 if (entry && (entry->_reg & (_cpuid_mask))) \
6622 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
6625 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
6626 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
6627 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
6628 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
6629 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
6630 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
6631 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
6632 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
6633 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
6634 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
6635 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
6636 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
6637 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
6638 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
6639 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
6641 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
6642 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
6643 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
6644 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
6645 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
6646 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
6648 #undef cr4_fixed1_update
6651 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
6653 struct vcpu_vmx *vmx = to_vmx(vcpu);
6655 if (kvm_mpx_supported()) {
6656 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
6659 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
6660 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
6662 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
6663 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
6668 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
6670 struct vcpu_vmx *vmx = to_vmx(vcpu);
6672 if (cpu_has_secondary_exec_ctrls()) {
6673 vmx_compute_secondary_exec_control(vmx);
6674 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
6677 if (nested_vmx_allowed(vcpu))
6678 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
6679 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
6681 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
6682 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
6684 if (nested_vmx_allowed(vcpu)) {
6685 nested_vmx_cr_fixed1_bits_update(vcpu);
6686 nested_vmx_entry_exit_ctls_update(vcpu);
6690 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
6692 if (func == 1 && nested)
6693 entry->ecx |= bit(X86_FEATURE_VMX);
6696 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
6698 to_vmx(vcpu)->req_immediate_exit = true;
6701 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
6702 struct x86_instruction_info *info,
6703 enum x86_intercept_stage stage)
6705 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6706 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6709 * RDPID causes #UD if disabled through secondary execution controls.
6710 * Because it is marked as EmulateOnUD, we need to intercept it here.
6712 if (info->intercept == x86_intercept_rdtscp &&
6713 !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
6714 ctxt->exception.vector = UD_VECTOR;
6715 ctxt->exception.error_code_valid = false;
6716 return X86EMUL_PROPAGATE_FAULT;
6719 /* TODO: check more intercepts... */
6720 return X86EMUL_CONTINUE;
6723 #ifdef CONFIG_X86_64
6724 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
6725 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
6726 u64 divisor, u64 *result)
6728 u64 low = a << shift, high = a >> (64 - shift);
6730 /* To avoid the overflow on divq */
6731 if (high >= divisor)
6734 /* Low hold the result, high hold rem which is discarded */
6735 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
6736 "rm" (divisor), "0" (low), "1" (high));
6742 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
6744 struct vcpu_vmx *vmx;
6745 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
6747 if (kvm_mwait_in_guest(vcpu->kvm))
6752 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
6753 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
6754 lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
6756 if (delta_tsc > lapic_timer_advance_cycles)
6757 delta_tsc -= lapic_timer_advance_cycles;
6761 /* Convert to host delta tsc if tsc scaling is enabled */
6762 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
6763 u64_shl_div_u64(delta_tsc,
6764 kvm_tsc_scaling_ratio_frac_bits,
6765 vcpu->arch.tsc_scaling_ratio,
6770 * If the delta tsc can't fit in the 32 bit after the multi shift,
6771 * we can't use the preemption timer.
6772 * It's possible that it fits on later vmentries, but checking
6773 * on every vmentry is costly so we just use an hrtimer.
6775 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
6778 vmx->hv_deadline_tsc = tscl + delta_tsc;
6779 return delta_tsc == 0;
6782 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
6784 to_vmx(vcpu)->hv_deadline_tsc = -1;
6788 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
6790 if (!kvm_pause_in_guest(vcpu->kvm))
6791 shrink_ple_window(vcpu);
6794 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
6795 struct kvm_memory_slot *slot)
6797 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
6798 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
6801 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
6802 struct kvm_memory_slot *slot)
6804 kvm_mmu_slot_set_dirty(kvm, slot);
6807 static void vmx_flush_log_dirty(struct kvm *kvm)
6809 kvm_flush_pml_buffers(kvm);
6812 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
6814 struct vmcs12 *vmcs12;
6815 struct vcpu_vmx *vmx = to_vmx(vcpu);
6817 struct page *page = NULL;
6820 if (is_guest_mode(vcpu)) {
6821 WARN_ON_ONCE(vmx->nested.pml_full);
6824 * Check if PML is enabled for the nested guest.
6825 * Whether eptp bit 6 is set is already checked
6826 * as part of A/D emulation.
6828 vmcs12 = get_vmcs12(vcpu);
6829 if (!nested_cpu_has_pml(vmcs12))
6832 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
6833 vmx->nested.pml_full = true;
6837 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
6839 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
6840 if (is_error_page(page))
6843 pml_address = kmap(page);
6844 pml_address[vmcs12->guest_pml_index--] = gpa;
6846 kvm_release_page_clean(page);
6852 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
6853 struct kvm_memory_slot *memslot,
6854 gfn_t offset, unsigned long mask)
6856 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
6859 static void __pi_post_block(struct kvm_vcpu *vcpu)
6861 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6862 struct pi_desc old, new;
6866 old.control = new.control = pi_desc->control;
6867 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
6868 "Wakeup handler not enabled while the VCPU is blocked\n");
6870 dest = cpu_physical_id(vcpu->cpu);
6872 if (x2apic_enabled())
6875 new.ndst = (dest << 8) & 0xFF00;
6877 /* set 'NV' to 'notification vector' */
6878 new.nv = POSTED_INTR_VECTOR;
6879 } while (cmpxchg64(&pi_desc->control, old.control,
6880 new.control) != old.control);
6882 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
6883 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
6884 list_del(&vcpu->blocked_vcpu_list);
6885 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
6886 vcpu->pre_pcpu = -1;
6891 * This routine does the following things for vCPU which is going
6892 * to be blocked if VT-d PI is enabled.
6893 * - Store the vCPU to the wakeup list, so when interrupts happen
6894 * we can find the right vCPU to wake up.
6895 * - Change the Posted-interrupt descriptor as below:
6896 * 'NDST' <-- vcpu->pre_pcpu
6897 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
6898 * - If 'ON' is set during this process, which means at least one
6899 * interrupt is posted for this vCPU, we cannot block it, in
6900 * this case, return 1, otherwise, return 0.
6903 static int pi_pre_block(struct kvm_vcpu *vcpu)
6906 struct pi_desc old, new;
6907 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6909 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
6910 !irq_remapping_cap(IRQ_POSTING_CAP) ||
6911 !kvm_vcpu_apicv_active(vcpu))
6914 WARN_ON(irqs_disabled());
6915 local_irq_disable();
6916 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
6917 vcpu->pre_pcpu = vcpu->cpu;
6918 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
6919 list_add_tail(&vcpu->blocked_vcpu_list,
6920 &per_cpu(blocked_vcpu_on_cpu,
6922 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
6926 old.control = new.control = pi_desc->control;
6928 WARN((pi_desc->sn == 1),
6929 "Warning: SN field of posted-interrupts "
6930 "is set before blocking\n");
6933 * Since vCPU can be preempted during this process,
6934 * vcpu->cpu could be different with pre_pcpu, we
6935 * need to set pre_pcpu as the destination of wakeup
6936 * notification event, then we can find the right vCPU
6937 * to wakeup in wakeup handler if interrupts happen
6938 * when the vCPU is in blocked state.
6940 dest = cpu_physical_id(vcpu->pre_pcpu);
6942 if (x2apic_enabled())
6945 new.ndst = (dest << 8) & 0xFF00;
6947 /* set 'NV' to 'wakeup vector' */
6948 new.nv = POSTED_INTR_WAKEUP_VECTOR;
6949 } while (cmpxchg64(&pi_desc->control, old.control,
6950 new.control) != old.control);
6952 /* We should not block the vCPU if an interrupt is posted for it. */
6953 if (pi_test_on(pi_desc) == 1)
6954 __pi_post_block(vcpu);
6957 return (vcpu->pre_pcpu == -1);
6960 static int vmx_pre_block(struct kvm_vcpu *vcpu)
6962 if (pi_pre_block(vcpu))
6965 if (kvm_lapic_hv_timer_in_use(vcpu))
6966 kvm_lapic_switch_to_sw_timer(vcpu);
6971 static void pi_post_block(struct kvm_vcpu *vcpu)
6973 if (vcpu->pre_pcpu == -1)
6976 WARN_ON(irqs_disabled());
6977 local_irq_disable();
6978 __pi_post_block(vcpu);
6982 static void vmx_post_block(struct kvm_vcpu *vcpu)
6984 if (kvm_x86_ops->set_hv_timer)
6985 kvm_lapic_switch_to_hv_timer(vcpu);
6987 pi_post_block(vcpu);
6991 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
6994 * @host_irq: host irq of the interrupt
6995 * @guest_irq: gsi of the interrupt
6996 * @set: set or unset PI
6997 * returns 0 on success, < 0 on failure
6999 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7000 uint32_t guest_irq, bool set)
7002 struct kvm_kernel_irq_routing_entry *e;
7003 struct kvm_irq_routing_table *irq_rt;
7004 struct kvm_lapic_irq irq;
7005 struct kvm_vcpu *vcpu;
7006 struct vcpu_data vcpu_info;
7009 if (!kvm_arch_has_assigned_device(kvm) ||
7010 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7011 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7014 idx = srcu_read_lock(&kvm->irq_srcu);
7015 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7016 if (guest_irq >= irq_rt->nr_rt_entries ||
7017 hlist_empty(&irq_rt->map[guest_irq])) {
7018 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7019 guest_irq, irq_rt->nr_rt_entries);
7023 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7024 if (e->type != KVM_IRQ_ROUTING_MSI)
7027 * VT-d PI cannot support posting multicast/broadcast
7028 * interrupts to a vCPU, we still use interrupt remapping
7029 * for these kind of interrupts.
7031 * For lowest-priority interrupts, we only support
7032 * those with single CPU as the destination, e.g. user
7033 * configures the interrupts via /proc/irq or uses
7034 * irqbalance to make the interrupts single-CPU.
7036 * We will support full lowest-priority interrupt later.
7039 kvm_set_msi_irq(kvm, e, &irq);
7040 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
7042 * Make sure the IRTE is in remapped mode if
7043 * we don't handle it in posted mode.
7045 ret = irq_set_vcpu_affinity(host_irq, NULL);
7048 "failed to back to remapped mode, irq: %u\n",
7056 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7057 vcpu_info.vector = irq.vector;
7059 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7060 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7063 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7065 ret = irq_set_vcpu_affinity(host_irq, NULL);
7068 printk(KERN_INFO "%s: failed to update PI IRTE\n",
7076 srcu_read_unlock(&kvm->irq_srcu, idx);
7080 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7082 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7083 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7084 FEATURE_CONTROL_LMCE;
7086 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7087 ~FEATURE_CONTROL_LMCE;
7090 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
7092 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7093 if (to_vmx(vcpu)->nested.nested_run_pending)
7098 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7100 struct vcpu_vmx *vmx = to_vmx(vcpu);
7102 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7103 if (vmx->nested.smm.guest_mode)
7104 nested_vmx_vmexit(vcpu, -1, 0, 0);
7106 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7107 vmx->nested.vmxon = false;
7108 vmx_clear_hlt(vcpu);
7112 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
7114 struct vcpu_vmx *vmx = to_vmx(vcpu);
7117 if (vmx->nested.smm.vmxon) {
7118 vmx->nested.vmxon = true;
7119 vmx->nested.smm.vmxon = false;
7122 if (vmx->nested.smm.guest_mode) {
7123 vcpu->arch.hflags &= ~HF_SMM_MASK;
7124 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7125 vcpu->arch.hflags |= HF_SMM_MASK;
7129 vmx->nested.smm.guest_mode = false;
7134 static int enable_smi_window(struct kvm_vcpu *vcpu)
7139 static __init int hardware_setup(void)
7141 unsigned long host_bndcfgs;
7144 rdmsrl_safe(MSR_EFER, &host_efer);
7146 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7147 kvm_define_shared_msr(i, vmx_msr_index[i]);
7149 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7152 if (boot_cpu_has(X86_FEATURE_NX))
7153 kvm_enable_efer_bits(EFER_NX);
7155 if (boot_cpu_has(X86_FEATURE_MPX)) {
7156 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7157 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7160 if (boot_cpu_has(X86_FEATURE_XSAVES))
7161 rdmsrl(MSR_IA32_XSS, host_xss);
7163 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7164 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7167 if (!cpu_has_vmx_ept() ||
7168 !cpu_has_vmx_ept_4levels() ||
7169 !cpu_has_vmx_ept_mt_wb() ||
7170 !cpu_has_vmx_invept_global())
7173 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7174 enable_ept_ad_bits = 0;
7176 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7177 enable_unrestricted_guest = 0;
7179 if (!cpu_has_vmx_flexpriority())
7180 flexpriority_enabled = 0;
7182 if (!cpu_has_virtual_nmis())
7186 * set_apic_access_page_addr() is used to reload apic access
7187 * page upon invalidation. No need to do anything if not
7188 * using the APIC_ACCESS_ADDR VMCS field.
7190 if (!flexpriority_enabled)
7191 kvm_x86_ops->set_apic_access_page_addr = NULL;
7193 if (!cpu_has_vmx_tpr_shadow())
7194 kvm_x86_ops->update_cr8_intercept = NULL;
7196 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7197 kvm_disable_largepages();
7199 #if IS_ENABLED(CONFIG_HYPERV)
7200 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7202 kvm_x86_ops->tlb_remote_flush = vmx_hv_remote_flush_tlb;
7205 if (!cpu_has_vmx_ple()) {
7208 ple_window_grow = 0;
7210 ple_window_shrink = 0;
7213 if (!cpu_has_vmx_apicv()) {
7215 kvm_x86_ops->sync_pir_to_irr = NULL;
7218 if (cpu_has_vmx_tsc_scaling()) {
7219 kvm_has_tsc_control = true;
7220 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7221 kvm_tsc_scaling_ratio_frac_bits = 48;
7224 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7232 * Only enable PML when hardware supports PML feature, and both EPT
7233 * and EPT A/D bit features are enabled -- PML depends on them to work.
7235 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7239 kvm_x86_ops->slot_enable_log_dirty = NULL;
7240 kvm_x86_ops->slot_disable_log_dirty = NULL;
7241 kvm_x86_ops->flush_log_dirty = NULL;
7242 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7245 if (!cpu_has_vmx_preemption_timer())
7246 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7248 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7251 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7252 cpu_preemption_timer_multi =
7253 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7255 kvm_x86_ops->set_hv_timer = NULL;
7256 kvm_x86_ops->cancel_hv_timer = NULL;
7259 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7261 kvm_mce_cap_supported |= MCG_LMCE_P;
7263 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7265 if (!enable_ept || !cpu_has_vmx_intel_pt())
7266 pt_mode = PT_MODE_SYSTEM;
7269 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7270 vmx_capability.ept, enable_apicv);
7272 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7277 r = alloc_kvm_area();
7279 nested_vmx_hardware_unsetup();
7283 static __exit void hardware_unsetup(void)
7286 nested_vmx_hardware_unsetup();
7291 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
7292 .cpu_has_kvm_support = cpu_has_kvm_support,
7293 .disabled_by_bios = vmx_disabled_by_bios,
7294 .hardware_setup = hardware_setup,
7295 .hardware_unsetup = hardware_unsetup,
7296 .check_processor_compatibility = vmx_check_processor_compat,
7297 .hardware_enable = hardware_enable,
7298 .hardware_disable = hardware_disable,
7299 .cpu_has_accelerated_tpr = report_flexpriority,
7300 .has_emulated_msr = vmx_has_emulated_msr,
7302 .vm_init = vmx_vm_init,
7303 .vm_alloc = vmx_vm_alloc,
7304 .vm_free = vmx_vm_free,
7306 .vcpu_create = vmx_create_vcpu,
7307 .vcpu_free = vmx_free_vcpu,
7308 .vcpu_reset = vmx_vcpu_reset,
7310 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7311 .vcpu_load = vmx_vcpu_load,
7312 .vcpu_put = vmx_vcpu_put,
7314 .update_bp_intercept = update_exception_bitmap,
7315 .get_msr_feature = vmx_get_msr_feature,
7316 .get_msr = vmx_get_msr,
7317 .set_msr = vmx_set_msr,
7318 .get_segment_base = vmx_get_segment_base,
7319 .get_segment = vmx_get_segment,
7320 .set_segment = vmx_set_segment,
7321 .get_cpl = vmx_get_cpl,
7322 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7323 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
7324 .decache_cr3 = vmx_decache_cr3,
7325 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
7326 .set_cr0 = vmx_set_cr0,
7327 .set_cr3 = vmx_set_cr3,
7328 .set_cr4 = vmx_set_cr4,
7329 .set_efer = vmx_set_efer,
7330 .get_idt = vmx_get_idt,
7331 .set_idt = vmx_set_idt,
7332 .get_gdt = vmx_get_gdt,
7333 .set_gdt = vmx_set_gdt,
7334 .get_dr6 = vmx_get_dr6,
7335 .set_dr6 = vmx_set_dr6,
7336 .set_dr7 = vmx_set_dr7,
7337 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7338 .cache_reg = vmx_cache_reg,
7339 .get_rflags = vmx_get_rflags,
7340 .set_rflags = vmx_set_rflags,
7342 .tlb_flush = vmx_flush_tlb,
7343 .tlb_flush_gva = vmx_flush_tlb_gva,
7345 .run = vmx_vcpu_run,
7346 .handle_exit = vmx_handle_exit,
7347 .skip_emulated_instruction = skip_emulated_instruction,
7348 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7349 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7350 .patch_hypercall = vmx_patch_hypercall,
7351 .set_irq = vmx_inject_irq,
7352 .set_nmi = vmx_inject_nmi,
7353 .queue_exception = vmx_queue_exception,
7354 .cancel_injection = vmx_cancel_injection,
7355 .interrupt_allowed = vmx_interrupt_allowed,
7356 .nmi_allowed = vmx_nmi_allowed,
7357 .get_nmi_mask = vmx_get_nmi_mask,
7358 .set_nmi_mask = vmx_set_nmi_mask,
7359 .enable_nmi_window = enable_nmi_window,
7360 .enable_irq_window = enable_irq_window,
7361 .update_cr8_intercept = update_cr8_intercept,
7362 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7363 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7364 .get_enable_apicv = vmx_get_enable_apicv,
7365 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7366 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7367 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7368 .hwapic_irr_update = vmx_hwapic_irr_update,
7369 .hwapic_isr_update = vmx_hwapic_isr_update,
7370 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7371 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7372 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7374 .set_tss_addr = vmx_set_tss_addr,
7375 .set_identity_map_addr = vmx_set_identity_map_addr,
7376 .get_tdp_level = get_ept_level,
7377 .get_mt_mask = vmx_get_mt_mask,
7379 .get_exit_info = vmx_get_exit_info,
7381 .get_lpage_level = vmx_get_lpage_level,
7383 .cpuid_update = vmx_cpuid_update,
7385 .rdtscp_supported = vmx_rdtscp_supported,
7386 .invpcid_supported = vmx_invpcid_supported,
7388 .set_supported_cpuid = vmx_set_supported_cpuid,
7390 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7392 .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
7393 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7395 .set_tdp_cr3 = vmx_set_cr3,
7397 .check_intercept = vmx_check_intercept,
7398 .handle_external_intr = vmx_handle_external_intr,
7399 .mpx_supported = vmx_mpx_supported,
7400 .xsaves_supported = vmx_xsaves_supported,
7401 .umip_emulated = vmx_umip_emulated,
7403 .request_immediate_exit = vmx_request_immediate_exit,
7405 .sched_in = vmx_sched_in,
7407 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7408 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7409 .flush_log_dirty = vmx_flush_log_dirty,
7410 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7411 .write_log_dirty = vmx_write_pml_buffer,
7413 .pre_block = vmx_pre_block,
7414 .post_block = vmx_post_block,
7416 .pmu_ops = &intel_pmu_ops,
7418 .update_pi_irte = vmx_update_pi_irte,
7420 #ifdef CONFIG_X86_64
7421 .set_hv_timer = vmx_set_hv_timer,
7422 .cancel_hv_timer = vmx_cancel_hv_timer,
7425 .setup_mce = vmx_setup_mce,
7427 .smi_allowed = vmx_smi_allowed,
7428 .pre_enter_smm = vmx_pre_enter_smm,
7429 .pre_leave_smm = vmx_pre_leave_smm,
7430 .enable_smi_window = enable_smi_window,
7432 .check_nested_events = NULL,
7433 .get_nested_state = NULL,
7434 .set_nested_state = NULL,
7435 .get_vmcs12_pages = NULL,
7436 .nested_enable_evmcs = NULL,
7439 static void vmx_cleanup_l1d_flush(void)
7441 if (vmx_l1d_flush_pages) {
7442 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7443 vmx_l1d_flush_pages = NULL;
7445 /* Restore state so sysfs ignores VMX */
7446 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
7449 static void vmx_exit(void)
7451 #ifdef CONFIG_KEXEC_CORE
7452 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
7458 #if IS_ENABLED(CONFIG_HYPERV)
7459 if (static_branch_unlikely(&enable_evmcs)) {
7461 struct hv_vp_assist_page *vp_ap;
7463 * Reset everything to support using non-enlightened VMCS
7464 * access later (e.g. when we reload the module with
7465 * enlightened_vmcs=0)
7467 for_each_online_cpu(cpu) {
7468 vp_ap = hv_get_vp_assist_page(cpu);
7473 vp_ap->current_nested_vmcs = 0;
7474 vp_ap->enlighten_vmentry = 0;
7477 static_branch_disable(&enable_evmcs);
7480 vmx_cleanup_l1d_flush();
7482 module_exit(vmx_exit);
7484 static int __init vmx_init(void)
7488 #if IS_ENABLED(CONFIG_HYPERV)
7490 * Enlightened VMCS usage should be recommended and the host needs
7491 * to support eVMCS v1 or above. We can also disable eVMCS support
7492 * with module parameter.
7494 if (enlightened_vmcs &&
7495 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
7496 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
7497 KVM_EVMCS_VERSION) {
7500 /* Check that we have assist pages on all online CPUs */
7501 for_each_online_cpu(cpu) {
7502 if (!hv_get_vp_assist_page(cpu)) {
7503 enlightened_vmcs = false;
7508 if (enlightened_vmcs) {
7509 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
7510 static_branch_enable(&enable_evmcs);
7513 enlightened_vmcs = false;
7517 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
7518 __alignof__(struct vcpu_vmx), THIS_MODULE);
7523 * Must be called after kvm_init() so enable_ept is properly set
7524 * up. Hand the parameter mitigation value in which was stored in
7525 * the pre module init parser. If no parameter was given, it will
7526 * contain 'auto' which will be turned into the default 'cond'
7529 if (boot_cpu_has(X86_BUG_L1TF)) {
7530 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
7537 #ifdef CONFIG_KEXEC_CORE
7538 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
7539 crash_vmclear_local_loaded_vmcss);
7541 vmx_check_vmcs12_offsets();
7545 module_init(vmx_init);