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"
67 MODULE_AUTHOR("Qumranet");
68 MODULE_LICENSE("GPL");
70 static const struct x86_cpu_id vmx_cpu_id[] = {
71 X86_FEATURE_MATCH(X86_FEATURE_VMX),
74 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
76 bool __read_mostly enable_vpid = 1;
77 module_param_named(vpid, enable_vpid, bool, 0444);
79 static bool __read_mostly enable_vnmi = 1;
80 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
82 bool __read_mostly flexpriority_enabled = 1;
83 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
85 bool __read_mostly enable_ept = 1;
86 module_param_named(ept, enable_ept, bool, S_IRUGO);
88 bool __read_mostly enable_unrestricted_guest = 1;
89 module_param_named(unrestricted_guest,
90 enable_unrestricted_guest, bool, S_IRUGO);
92 bool __read_mostly enable_ept_ad_bits = 1;
93 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
95 static bool __read_mostly emulate_invalid_guest_state = true;
96 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
98 static bool __read_mostly fasteoi = 1;
99 module_param(fasteoi, bool, S_IRUGO);
101 static bool __read_mostly enable_apicv = 1;
102 module_param(enable_apicv, bool, S_IRUGO);
105 * If nested=1, nested virtualization is supported, i.e., guests may use
106 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
107 * use VMX instructions.
109 static bool __read_mostly nested = 1;
110 module_param(nested, bool, S_IRUGO);
112 static u64 __read_mostly host_xss;
114 bool __read_mostly enable_pml = 1;
115 module_param_named(pml, enable_pml, bool, S_IRUGO);
117 #define MSR_BITMAP_MODE_X2APIC 1
118 #define MSR_BITMAP_MODE_X2APIC_APICV 2
120 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
122 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
123 static int __read_mostly cpu_preemption_timer_multi;
124 static bool __read_mostly enable_preemption_timer = 1;
126 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
129 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
130 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
131 #define KVM_VM_CR0_ALWAYS_ON \
132 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
133 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
134 #define KVM_CR4_GUEST_OWNED_BITS \
135 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
136 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
138 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
139 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
140 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
142 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
145 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
146 * ple_gap: upper bound on the amount of time between two successive
147 * executions of PAUSE in a loop. Also indicate if ple enabled.
148 * According to test, this time is usually smaller than 128 cycles.
149 * ple_window: upper bound on the amount of time a guest is allowed to execute
150 * in a PAUSE loop. Tests indicate that most spinlocks are held for
151 * less than 2^12 cycles
152 * Time is measured based on a counter that runs at the same rate as the TSC,
153 * refer SDM volume 3b section 21.6.13 & 22.1.3.
155 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
156 module_param(ple_gap, uint, 0444);
158 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
159 module_param(ple_window, uint, 0444);
161 /* Default doubles per-vcpu window every exit. */
162 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
163 module_param(ple_window_grow, uint, 0444);
165 /* Default resets per-vcpu window every exit to ple_window. */
166 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
167 module_param(ple_window_shrink, uint, 0444);
169 /* Default is to compute the maximum so we can never overflow. */
170 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
171 module_param(ple_window_max, uint, 0444);
173 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
174 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
175 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
177 /* Storage for pre module init parameter parsing */
178 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
180 static const struct {
183 } vmentry_l1d_param[] = {
184 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
185 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
186 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
187 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
188 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
189 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
192 #define L1D_CACHE_ORDER 4
193 static void *vmx_l1d_flush_pages;
195 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
201 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
205 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
208 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
209 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
210 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
215 /* If set to auto use the default l1tf mitigation method */
216 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
217 switch (l1tf_mitigation) {
218 case L1TF_MITIGATION_OFF:
219 l1tf = VMENTER_L1D_FLUSH_NEVER;
221 case L1TF_MITIGATION_FLUSH_NOWARN:
222 case L1TF_MITIGATION_FLUSH:
223 case L1TF_MITIGATION_FLUSH_NOSMT:
224 l1tf = VMENTER_L1D_FLUSH_COND;
226 case L1TF_MITIGATION_FULL:
227 case L1TF_MITIGATION_FULL_FORCE:
228 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
231 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
232 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
235 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
236 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
237 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
240 vmx_l1d_flush_pages = page_address(page);
243 * Initialize each page with a different pattern in
244 * order to protect against KSM in the nested
245 * virtualization case.
247 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
248 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
253 l1tf_vmx_mitigation = l1tf;
255 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
256 static_branch_enable(&vmx_l1d_should_flush);
258 static_branch_disable(&vmx_l1d_should_flush);
260 if (l1tf == VMENTER_L1D_FLUSH_COND)
261 static_branch_enable(&vmx_l1d_flush_cond);
263 static_branch_disable(&vmx_l1d_flush_cond);
267 static int vmentry_l1d_flush_parse(const char *s)
272 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
273 if (vmentry_l1d_param[i].for_parse &&
274 sysfs_streq(s, vmentry_l1d_param[i].option))
281 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
285 l1tf = vmentry_l1d_flush_parse(s);
289 if (!boot_cpu_has(X86_BUG_L1TF))
293 * Has vmx_init() run already? If not then this is the pre init
294 * parameter parsing. In that case just store the value and let
295 * vmx_init() do the proper setup after enable_ept has been
298 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
299 vmentry_l1d_flush_param = l1tf;
303 mutex_lock(&vmx_l1d_flush_mutex);
304 ret = vmx_setup_l1d_flush(l1tf);
305 mutex_unlock(&vmx_l1d_flush_mutex);
309 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
311 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
312 return sprintf(s, "???\n");
314 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
317 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
318 .set = vmentry_l1d_flush_set,
319 .get = vmentry_l1d_flush_get,
321 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
323 static bool guest_state_valid(struct kvm_vcpu *vcpu);
324 static u32 vmx_segment_access_rights(struct kvm_segment *var);
325 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
328 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
329 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
331 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
332 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
334 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
337 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
338 * can find which vCPU should be waken up.
340 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
341 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
343 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
344 static DEFINE_SPINLOCK(vmx_vpid_lock);
346 struct vmcs_config vmcs_config;
347 struct vmx_capability vmx_capability;
349 #define VMX_SEGMENT_FIELD(seg) \
350 [VCPU_SREG_##seg] = { \
351 .selector = GUEST_##seg##_SELECTOR, \
352 .base = GUEST_##seg##_BASE, \
353 .limit = GUEST_##seg##_LIMIT, \
354 .ar_bytes = GUEST_##seg##_AR_BYTES, \
357 static const struct kvm_vmx_segment_field {
362 } kvm_vmx_segment_fields[] = {
363 VMX_SEGMENT_FIELD(CS),
364 VMX_SEGMENT_FIELD(DS),
365 VMX_SEGMENT_FIELD(ES),
366 VMX_SEGMENT_FIELD(FS),
367 VMX_SEGMENT_FIELD(GS),
368 VMX_SEGMENT_FIELD(SS),
369 VMX_SEGMENT_FIELD(TR),
370 VMX_SEGMENT_FIELD(LDTR),
376 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
377 * will emulate SYSCALL in legacy mode if the vendor string in guest
378 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
379 * support this emulation, IA32_STAR must always be included in
380 * vmx_msr_index[], even in i386 builds.
382 const u32 vmx_msr_index[] = {
384 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
386 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
389 #if IS_ENABLED(CONFIG_HYPERV)
390 static bool __read_mostly enlightened_vmcs = true;
391 module_param(enlightened_vmcs, bool, 0444);
393 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
394 static void check_ept_pointer_match(struct kvm *kvm)
396 struct kvm_vcpu *vcpu;
397 u64 tmp_eptp = INVALID_PAGE;
400 kvm_for_each_vcpu(i, vcpu, kvm) {
401 if (!VALID_PAGE(tmp_eptp)) {
402 tmp_eptp = to_vmx(vcpu)->ept_pointer;
403 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
404 to_kvm_vmx(kvm)->ept_pointers_match
405 = EPT_POINTERS_MISMATCH;
410 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
413 static int vmx_hv_remote_flush_tlb(struct kvm *kvm)
415 struct kvm_vcpu *vcpu;
416 int ret = -ENOTSUPP, i;
418 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
420 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
421 check_ept_pointer_match(kvm);
424 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs the address of the
425 * base of EPT PML4 table, strip off EPT configuration information.
426 * If ept_pointer is invalid pointer, bypass the flush request.
428 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
429 kvm_for_each_vcpu(i, vcpu, kvm) {
430 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
432 if (!VALID_PAGE(ept_pointer))
435 ret |= hyperv_flush_guest_mapping(
436 ept_pointer & PAGE_MASK);
439 ret = hyperv_flush_guest_mapping(
440 to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer & PAGE_MASK);
443 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
446 #endif /* IS_ENABLED(CONFIG_HYPERV) */
449 * Comment's format: document - errata name - stepping - processor name.
451 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
453 static u32 vmx_preemption_cpu_tfms[] = {
454 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
456 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
457 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
458 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
460 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
462 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
463 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
465 * 320767.pdf - AAP86 - B1 -
466 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
469 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
471 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
473 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
475 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
476 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
477 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
479 /* Xeon E3-1220 V2 */
483 static inline bool cpu_has_broken_vmx_preemption_timer(void)
485 u32 eax = cpuid_eax(0x00000001), i;
487 /* Clear the reserved bits */
488 eax &= ~(0x3U << 14 | 0xfU << 28);
489 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
490 if (eax == vmx_preemption_cpu_tfms[i])
496 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
498 return flexpriority_enabled && lapic_in_kernel(vcpu);
501 static inline bool report_flexpriority(void)
503 return flexpriority_enabled;
506 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
510 for (i = 0; i < vmx->nmsrs; ++i)
511 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
516 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
520 i = __find_msr_index(vmx, msr);
522 return &vmx->guest_msrs[i];
526 void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
528 vmcs_clear(loaded_vmcs->vmcs);
529 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
530 vmcs_clear(loaded_vmcs->shadow_vmcs);
531 loaded_vmcs->cpu = -1;
532 loaded_vmcs->launched = 0;
535 #ifdef CONFIG_KEXEC_CORE
537 * This bitmap is used to indicate whether the vmclear
538 * operation is enabled on all cpus. All disabled by
541 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
543 static inline void crash_enable_local_vmclear(int cpu)
545 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
548 static inline void crash_disable_local_vmclear(int cpu)
550 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
553 static inline int crash_local_vmclear_enabled(int cpu)
555 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
558 static void crash_vmclear_local_loaded_vmcss(void)
560 int cpu = raw_smp_processor_id();
561 struct loaded_vmcs *v;
563 if (!crash_local_vmclear_enabled(cpu))
566 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
567 loaded_vmcss_on_cpu_link)
571 static inline void crash_enable_local_vmclear(int cpu) { }
572 static inline void crash_disable_local_vmclear(int cpu) { }
573 #endif /* CONFIG_KEXEC_CORE */
575 static void __loaded_vmcs_clear(void *arg)
577 struct loaded_vmcs *loaded_vmcs = arg;
578 int cpu = raw_smp_processor_id();
580 if (loaded_vmcs->cpu != cpu)
581 return; /* vcpu migration can race with cpu offline */
582 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
583 per_cpu(current_vmcs, cpu) = NULL;
584 crash_disable_local_vmclear(cpu);
585 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
588 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
589 * is before setting loaded_vmcs->vcpu to -1 which is done in
590 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
591 * then adds the vmcs into percpu list before it is deleted.
595 loaded_vmcs_init(loaded_vmcs);
596 crash_enable_local_vmclear(cpu);
599 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
601 int cpu = loaded_vmcs->cpu;
604 smp_call_function_single(cpu,
605 __loaded_vmcs_clear, loaded_vmcs, 1);
608 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
612 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
614 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
615 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
616 vmx->segment_cache.bitmask = 0;
618 ret = vmx->segment_cache.bitmask & mask;
619 vmx->segment_cache.bitmask |= mask;
623 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
625 u16 *p = &vmx->segment_cache.seg[seg].selector;
627 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
628 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
632 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
634 ulong *p = &vmx->segment_cache.seg[seg].base;
636 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
637 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
641 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
643 u32 *p = &vmx->segment_cache.seg[seg].limit;
645 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
646 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
650 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
652 u32 *p = &vmx->segment_cache.seg[seg].ar;
654 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
655 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
659 void update_exception_bitmap(struct kvm_vcpu *vcpu)
663 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
664 (1u << DB_VECTOR) | (1u << AC_VECTOR);
666 * Guest access to VMware backdoor ports could legitimately
667 * trigger #GP because of TSS I/O permission bitmap.
668 * We intercept those #GP and allow access to them anyway
671 if (enable_vmware_backdoor)
672 eb |= (1u << GP_VECTOR);
673 if ((vcpu->guest_debug &
674 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
675 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
676 eb |= 1u << BP_VECTOR;
677 if (to_vmx(vcpu)->rmode.vm86_active)
680 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
682 /* When we are running a nested L2 guest and L1 specified for it a
683 * certain exception bitmap, we must trap the same exceptions and pass
684 * them to L1. When running L2, we will only handle the exceptions
685 * specified above if L1 did not want them.
687 if (is_guest_mode(vcpu))
688 eb |= get_vmcs12(vcpu)->exception_bitmap;
690 vmcs_write32(EXCEPTION_BITMAP, eb);
694 * Check if MSR is intercepted for currently loaded MSR bitmap.
696 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
698 unsigned long *msr_bitmap;
699 int f = sizeof(unsigned long);
701 if (!cpu_has_vmx_msr_bitmap())
704 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
707 return !!test_bit(msr, msr_bitmap + 0x800 / f);
708 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
710 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
716 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
717 unsigned long entry, unsigned long exit)
719 vm_entry_controls_clearbit(vmx, entry);
720 vm_exit_controls_clearbit(vmx, exit);
723 static int find_msr(struct vmx_msrs *m, unsigned int msr)
727 for (i = 0; i < m->nr; ++i) {
728 if (m->val[i].index == msr)
734 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
737 struct msr_autoload *m = &vmx->msr_autoload;
741 if (cpu_has_load_ia32_efer()) {
742 clear_atomic_switch_msr_special(vmx,
743 VM_ENTRY_LOAD_IA32_EFER,
744 VM_EXIT_LOAD_IA32_EFER);
748 case MSR_CORE_PERF_GLOBAL_CTRL:
749 if (cpu_has_load_perf_global_ctrl()) {
750 clear_atomic_switch_msr_special(vmx,
751 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
752 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
757 i = find_msr(&m->guest, msr);
761 m->guest.val[i] = m->guest.val[m->guest.nr];
762 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
765 i = find_msr(&m->host, msr);
770 m->host.val[i] = m->host.val[m->host.nr];
771 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
774 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
775 unsigned long entry, unsigned long exit,
776 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
777 u64 guest_val, u64 host_val)
779 vmcs_write64(guest_val_vmcs, guest_val);
780 if (host_val_vmcs != HOST_IA32_EFER)
781 vmcs_write64(host_val_vmcs, host_val);
782 vm_entry_controls_setbit(vmx, entry);
783 vm_exit_controls_setbit(vmx, exit);
786 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
787 u64 guest_val, u64 host_val, bool entry_only)
790 struct msr_autoload *m = &vmx->msr_autoload;
794 if (cpu_has_load_ia32_efer()) {
795 add_atomic_switch_msr_special(vmx,
796 VM_ENTRY_LOAD_IA32_EFER,
797 VM_EXIT_LOAD_IA32_EFER,
800 guest_val, host_val);
804 case MSR_CORE_PERF_GLOBAL_CTRL:
805 if (cpu_has_load_perf_global_ctrl()) {
806 add_atomic_switch_msr_special(vmx,
807 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
808 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
809 GUEST_IA32_PERF_GLOBAL_CTRL,
810 HOST_IA32_PERF_GLOBAL_CTRL,
811 guest_val, host_val);
815 case MSR_IA32_PEBS_ENABLE:
816 /* PEBS needs a quiescent period after being disabled (to write
817 * a record). Disabling PEBS through VMX MSR swapping doesn't
818 * provide that period, so a CPU could write host's record into
821 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
824 i = find_msr(&m->guest, msr);
826 j = find_msr(&m->host, msr);
828 if (i == NR_AUTOLOAD_MSRS || j == NR_AUTOLOAD_MSRS) {
829 printk_once(KERN_WARNING "Not enough msr switch entries. "
830 "Can't add msr %x\n", msr);
835 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
837 m->guest.val[i].index = msr;
838 m->guest.val[i].value = guest_val;
845 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
847 m->host.val[j].index = msr;
848 m->host.val[j].value = host_val;
851 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
853 u64 guest_efer = vmx->vcpu.arch.efer;
858 * NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
859 * host CPUID is more efficient than testing guest CPUID
860 * or CR4. Host SMEP is anyway a requirement for guest SMEP.
862 if (boot_cpu_has(X86_FEATURE_SMEP))
863 guest_efer |= EFER_NX;
864 else if (!(guest_efer & EFER_NX))
865 ignore_bits |= EFER_NX;
869 * LMA and LME handled by hardware; SCE meaningless outside long mode.
871 ignore_bits |= EFER_SCE;
873 ignore_bits |= EFER_LMA | EFER_LME;
874 /* SCE is meaningful only in long mode on Intel */
875 if (guest_efer & EFER_LMA)
876 ignore_bits &= ~(u64)EFER_SCE;
880 * On EPT, we can't emulate NX, so we must switch EFER atomically.
881 * On CPUs that support "load IA32_EFER", always switch EFER
882 * atomically, since it's faster than switching it manually.
884 if (cpu_has_load_ia32_efer() ||
885 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
886 if (!(guest_efer & EFER_LMA))
887 guest_efer &= ~EFER_LME;
888 if (guest_efer != host_efer)
889 add_atomic_switch_msr(vmx, MSR_EFER,
890 guest_efer, host_efer, false);
892 clear_atomic_switch_msr(vmx, MSR_EFER);
895 clear_atomic_switch_msr(vmx, MSR_EFER);
897 guest_efer &= ~ignore_bits;
898 guest_efer |= host_efer & ignore_bits;
900 vmx->guest_msrs[efer_offset].data = guest_efer;
901 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
909 * On 32-bit kernels, VM exits still load the FS and GS bases from the
910 * VMCS rather than the segment table. KVM uses this helper to figure
911 * out the current bases to poke them into the VMCS before entry.
913 static unsigned long segment_base(u16 selector)
915 struct desc_struct *table;
918 if (!(selector & ~SEGMENT_RPL_MASK))
921 table = get_current_gdt_ro();
923 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
924 u16 ldt_selector = kvm_read_ldt();
926 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
929 table = (struct desc_struct *)segment_base(ldt_selector);
931 v = get_desc_base(&table[selector >> 3]);
936 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
938 struct vcpu_vmx *vmx = to_vmx(vcpu);
939 struct vmcs_host_state *host_state;
941 int cpu = raw_smp_processor_id();
943 unsigned long fs_base, gs_base;
947 vmx->req_immediate_exit = false;
950 * Note that guest MSRs to be saved/restored can also be changed
951 * when guest state is loaded. This happens when guest transitions
952 * to/from long-mode by setting MSR_EFER.LMA.
954 if (!vmx->loaded_cpu_state || vmx->guest_msrs_dirty) {
955 vmx->guest_msrs_dirty = false;
956 for (i = 0; i < vmx->save_nmsrs; ++i)
957 kvm_set_shared_msr(vmx->guest_msrs[i].index,
958 vmx->guest_msrs[i].data,
959 vmx->guest_msrs[i].mask);
963 if (vmx->loaded_cpu_state)
966 vmx->loaded_cpu_state = vmx->loaded_vmcs;
967 host_state = &vmx->loaded_cpu_state->host_state;
970 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
971 * allow segment selectors with cpl > 0 or ti == 1.
973 host_state->ldt_sel = kvm_read_ldt();
976 savesegment(ds, host_state->ds_sel);
977 savesegment(es, host_state->es_sel);
979 gs_base = cpu_kernelmode_gs_base(cpu);
980 if (likely(is_64bit_mm(current->mm))) {
982 fs_sel = current->thread.fsindex;
983 gs_sel = current->thread.gsindex;
984 fs_base = current->thread.fsbase;
985 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
987 savesegment(fs, fs_sel);
988 savesegment(gs, gs_sel);
989 fs_base = read_msr(MSR_FS_BASE);
990 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
993 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
995 savesegment(fs, fs_sel);
996 savesegment(gs, gs_sel);
997 fs_base = segment_base(fs_sel);
998 gs_base = segment_base(gs_sel);
1001 if (unlikely(fs_sel != host_state->fs_sel)) {
1003 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1005 vmcs_write16(HOST_FS_SELECTOR, 0);
1006 host_state->fs_sel = fs_sel;
1008 if (unlikely(gs_sel != host_state->gs_sel)) {
1010 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1012 vmcs_write16(HOST_GS_SELECTOR, 0);
1013 host_state->gs_sel = gs_sel;
1015 if (unlikely(fs_base != host_state->fs_base)) {
1016 vmcs_writel(HOST_FS_BASE, fs_base);
1017 host_state->fs_base = fs_base;
1019 if (unlikely(gs_base != host_state->gs_base)) {
1020 vmcs_writel(HOST_GS_BASE, gs_base);
1021 host_state->gs_base = gs_base;
1025 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1027 struct vmcs_host_state *host_state;
1029 if (!vmx->loaded_cpu_state)
1032 WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
1033 host_state = &vmx->loaded_cpu_state->host_state;
1035 ++vmx->vcpu.stat.host_state_reload;
1036 vmx->loaded_cpu_state = NULL;
1038 #ifdef CONFIG_X86_64
1039 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1041 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1042 kvm_load_ldt(host_state->ldt_sel);
1043 #ifdef CONFIG_X86_64
1044 load_gs_index(host_state->gs_sel);
1046 loadsegment(gs, host_state->gs_sel);
1049 if (host_state->fs_sel & 7)
1050 loadsegment(fs, host_state->fs_sel);
1051 #ifdef CONFIG_X86_64
1052 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1053 loadsegment(ds, host_state->ds_sel);
1054 loadsegment(es, host_state->es_sel);
1057 invalidate_tss_limit();
1058 #ifdef CONFIG_X86_64
1059 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1061 load_fixmap_gdt(raw_smp_processor_id());
1064 #ifdef CONFIG_X86_64
1065 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1068 if (vmx->loaded_cpu_state)
1069 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1071 return vmx->msr_guest_kernel_gs_base;
1074 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1077 if (vmx->loaded_cpu_state)
1078 wrmsrl(MSR_KERNEL_GS_BASE, data);
1080 vmx->msr_guest_kernel_gs_base = data;
1084 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1086 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1087 struct pi_desc old, new;
1091 * In case of hot-plug or hot-unplug, we may have to undo
1092 * vmx_vcpu_pi_put even if there is no assigned device. And we
1093 * always keep PI.NDST up to date for simplicity: it makes the
1094 * code easier, and CPU migration is not a fast path.
1096 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1100 * First handle the simple case where no cmpxchg is necessary; just
1101 * allow posting non-urgent interrupts.
1103 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
1104 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
1105 * expects the VCPU to be on the blocked_vcpu_list that matches
1108 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
1110 pi_clear_sn(pi_desc);
1114 /* The full case. */
1116 old.control = new.control = pi_desc->control;
1118 dest = cpu_physical_id(cpu);
1120 if (x2apic_enabled())
1123 new.ndst = (dest << 8) & 0xFF00;
1126 } while (cmpxchg64(&pi_desc->control, old.control,
1127 new.control) != old.control);
1131 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1132 * vcpu mutex is already taken.
1134 void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1136 struct vcpu_vmx *vmx = to_vmx(vcpu);
1137 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1139 if (!already_loaded) {
1140 loaded_vmcs_clear(vmx->loaded_vmcs);
1141 local_irq_disable();
1142 crash_disable_local_vmclear(cpu);
1145 * Read loaded_vmcs->cpu should be before fetching
1146 * loaded_vmcs->loaded_vmcss_on_cpu_link.
1147 * See the comments in __loaded_vmcs_clear().
1151 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1152 &per_cpu(loaded_vmcss_on_cpu, cpu));
1153 crash_enable_local_vmclear(cpu);
1157 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1158 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1159 vmcs_load(vmx->loaded_vmcs->vmcs);
1160 indirect_branch_prediction_barrier();
1163 if (!already_loaded) {
1164 void *gdt = get_current_gdt_ro();
1165 unsigned long sysenter_esp;
1167 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1170 * Linux uses per-cpu TSS and GDT, so set these when switching
1171 * processors. See 22.2.4.
1173 vmcs_writel(HOST_TR_BASE,
1174 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1175 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1178 * VM exits change the host TR limit to 0x67 after a VM
1179 * exit. This is okay, since 0x67 covers everything except
1180 * the IO bitmap and have have code to handle the IO bitmap
1181 * being lost after a VM exit.
1183 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
1185 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1186 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1188 vmx->loaded_vmcs->cpu = cpu;
1191 /* Setup TSC multiplier */
1192 if (kvm_has_tsc_control &&
1193 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1194 decache_tsc_multiplier(vmx);
1196 vmx_vcpu_pi_load(vcpu, cpu);
1197 vmx->host_pkru = read_pkru();
1198 vmx->host_debugctlmsr = get_debugctlmsr();
1201 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1203 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1205 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1206 !irq_remapping_cap(IRQ_POSTING_CAP) ||
1207 !kvm_vcpu_apicv_active(vcpu))
1210 /* Set SN when the vCPU is preempted */
1211 if (vcpu->preempted)
1215 void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1217 vmx_vcpu_pi_put(vcpu);
1219 vmx_prepare_switch_to_host(to_vmx(vcpu));
1222 static bool emulation_required(struct kvm_vcpu *vcpu)
1224 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1227 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1229 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1231 unsigned long rflags, save_rflags;
1233 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1234 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1235 rflags = vmcs_readl(GUEST_RFLAGS);
1236 if (to_vmx(vcpu)->rmode.vm86_active) {
1237 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1238 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1239 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1241 to_vmx(vcpu)->rflags = rflags;
1243 return to_vmx(vcpu)->rflags;
1246 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1248 unsigned long old_rflags = vmx_get_rflags(vcpu);
1250 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1251 to_vmx(vcpu)->rflags = rflags;
1252 if (to_vmx(vcpu)->rmode.vm86_active) {
1253 to_vmx(vcpu)->rmode.save_rflags = rflags;
1254 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1256 vmcs_writel(GUEST_RFLAGS, rflags);
1258 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
1259 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
1262 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1264 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1267 if (interruptibility & GUEST_INTR_STATE_STI)
1268 ret |= KVM_X86_SHADOW_INT_STI;
1269 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1270 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1275 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1277 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1278 u32 interruptibility = interruptibility_old;
1280 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1282 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1283 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1284 else if (mask & KVM_X86_SHADOW_INT_STI)
1285 interruptibility |= GUEST_INTR_STATE_STI;
1287 if ((interruptibility != interruptibility_old))
1288 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1291 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1295 rip = kvm_rip_read(vcpu);
1296 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1297 kvm_rip_write(vcpu, rip);
1299 /* skipping an emulated instruction also counts */
1300 vmx_set_interrupt_shadow(vcpu, 0);
1303 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1306 * Ensure that we clear the HLT state in the VMCS. We don't need to
1307 * explicitly skip the instruction because if the HLT state is set,
1308 * then the instruction is already executing and RIP has already been
1311 if (kvm_hlt_in_guest(vcpu->kvm) &&
1312 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1313 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1316 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1318 struct vcpu_vmx *vmx = to_vmx(vcpu);
1319 unsigned nr = vcpu->arch.exception.nr;
1320 bool has_error_code = vcpu->arch.exception.has_error_code;
1321 u32 error_code = vcpu->arch.exception.error_code;
1322 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1324 kvm_deliver_exception_payload(vcpu);
1326 if (has_error_code) {
1327 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1328 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1331 if (vmx->rmode.vm86_active) {
1333 if (kvm_exception_is_soft(nr))
1334 inc_eip = vcpu->arch.event_exit_inst_len;
1335 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1336 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1340 WARN_ON_ONCE(vmx->emulation_required);
1342 if (kvm_exception_is_soft(nr)) {
1343 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1344 vmx->vcpu.arch.event_exit_inst_len);
1345 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1347 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1349 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1351 vmx_clear_hlt(vcpu);
1354 static bool vmx_rdtscp_supported(void)
1356 return cpu_has_vmx_rdtscp();
1359 static bool vmx_invpcid_supported(void)
1361 return cpu_has_vmx_invpcid();
1365 * Swap MSR entry in host/guest MSR entry array.
1367 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1369 struct shared_msr_entry tmp;
1371 tmp = vmx->guest_msrs[to];
1372 vmx->guest_msrs[to] = vmx->guest_msrs[from];
1373 vmx->guest_msrs[from] = tmp;
1377 * Set up the vmcs to automatically save and restore system
1378 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1379 * mode, as fiddling with msrs is very expensive.
1381 static void setup_msrs(struct vcpu_vmx *vmx)
1383 int save_nmsrs, index;
1386 #ifdef CONFIG_X86_64
1388 * The SYSCALL MSRs are only needed on long mode guests, and only
1389 * when EFER.SCE is set.
1391 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1392 index = __find_msr_index(vmx, MSR_STAR);
1394 move_msr_up(vmx, index, save_nmsrs++);
1395 index = __find_msr_index(vmx, MSR_LSTAR);
1397 move_msr_up(vmx, index, save_nmsrs++);
1398 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1400 move_msr_up(vmx, index, save_nmsrs++);
1403 index = __find_msr_index(vmx, MSR_EFER);
1404 if (index >= 0 && update_transition_efer(vmx, index))
1405 move_msr_up(vmx, index, save_nmsrs++);
1406 index = __find_msr_index(vmx, MSR_TSC_AUX);
1407 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1408 move_msr_up(vmx, index, save_nmsrs++);
1410 vmx->save_nmsrs = save_nmsrs;
1411 vmx->guest_msrs_dirty = true;
1413 if (cpu_has_vmx_msr_bitmap())
1414 vmx_update_msr_bitmap(&vmx->vcpu);
1417 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1419 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1421 if (is_guest_mode(vcpu) &&
1422 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1423 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
1425 return vcpu->arch.tsc_offset;
1428 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1430 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1431 u64 g_tsc_offset = 0;
1434 * We're here if L1 chose not to trap WRMSR to TSC. According
1435 * to the spec, this should set L1's TSC; The offset that L1
1436 * set for L2 remains unchanged, and still needs to be added
1437 * to the newly set TSC to get L2's TSC.
1439 if (is_guest_mode(vcpu) &&
1440 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1441 g_tsc_offset = vmcs12->tsc_offset;
1443 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1444 vcpu->arch.tsc_offset - g_tsc_offset,
1446 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1447 return offset + g_tsc_offset;
1451 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1452 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1453 * all guests if the "nested" module option is off, and can also be disabled
1454 * for a single guest by disabling its VMX cpuid bit.
1456 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1458 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1461 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1464 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1466 return !(val & ~valid_bits);
1469 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1471 switch (msr->index) {
1472 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1475 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1484 * Reads an msr value (of 'msr_index') into 'pdata'.
1485 * Returns 0 on success, non-0 otherwise.
1486 * Assumes vcpu_load() was already called.
1488 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1490 struct vcpu_vmx *vmx = to_vmx(vcpu);
1491 struct shared_msr_entry *msr;
1493 switch (msr_info->index) {
1494 #ifdef CONFIG_X86_64
1496 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1499 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1501 case MSR_KERNEL_GS_BASE:
1502 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1506 return kvm_get_msr_common(vcpu, msr_info);
1507 case MSR_IA32_SPEC_CTRL:
1508 if (!msr_info->host_initiated &&
1509 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1512 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1514 case MSR_IA32_ARCH_CAPABILITIES:
1515 if (!msr_info->host_initiated &&
1516 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
1518 msr_info->data = to_vmx(vcpu)->arch_capabilities;
1520 case MSR_IA32_SYSENTER_CS:
1521 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1523 case MSR_IA32_SYSENTER_EIP:
1524 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1526 case MSR_IA32_SYSENTER_ESP:
1527 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1529 case MSR_IA32_BNDCFGS:
1530 if (!kvm_mpx_supported() ||
1531 (!msr_info->host_initiated &&
1532 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1534 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1536 case MSR_IA32_MCG_EXT_CTL:
1537 if (!msr_info->host_initiated &&
1538 !(vmx->msr_ia32_feature_control &
1539 FEATURE_CONTROL_LMCE))
1541 msr_info->data = vcpu->arch.mcg_ext_ctl;
1543 case MSR_IA32_FEATURE_CONTROL:
1544 msr_info->data = vmx->msr_ia32_feature_control;
1546 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1547 if (!nested_vmx_allowed(vcpu))
1549 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1552 if (!vmx_xsaves_supported())
1554 msr_info->data = vcpu->arch.ia32_xss;
1557 if (!msr_info->host_initiated &&
1558 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1560 /* Otherwise falls through */
1562 msr = find_msr_entry(vmx, msr_info->index);
1564 msr_info->data = msr->data;
1567 return kvm_get_msr_common(vcpu, msr_info);
1574 * Writes msr value into into the appropriate "register".
1575 * Returns 0 on success, non-0 otherwise.
1576 * Assumes vcpu_load() was already called.
1578 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1580 struct vcpu_vmx *vmx = to_vmx(vcpu);
1581 struct shared_msr_entry *msr;
1583 u32 msr_index = msr_info->index;
1584 u64 data = msr_info->data;
1586 switch (msr_index) {
1588 ret = kvm_set_msr_common(vcpu, msr_info);
1590 #ifdef CONFIG_X86_64
1592 vmx_segment_cache_clear(vmx);
1593 vmcs_writel(GUEST_FS_BASE, data);
1596 vmx_segment_cache_clear(vmx);
1597 vmcs_writel(GUEST_GS_BASE, data);
1599 case MSR_KERNEL_GS_BASE:
1600 vmx_write_guest_kernel_gs_base(vmx, data);
1603 case MSR_IA32_SYSENTER_CS:
1604 vmcs_write32(GUEST_SYSENTER_CS, data);
1606 case MSR_IA32_SYSENTER_EIP:
1607 vmcs_writel(GUEST_SYSENTER_EIP, data);
1609 case MSR_IA32_SYSENTER_ESP:
1610 vmcs_writel(GUEST_SYSENTER_ESP, data);
1612 case MSR_IA32_BNDCFGS:
1613 if (!kvm_mpx_supported() ||
1614 (!msr_info->host_initiated &&
1615 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1617 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
1618 (data & MSR_IA32_BNDCFGS_RSVD))
1620 vmcs_write64(GUEST_BNDCFGS, data);
1622 case MSR_IA32_SPEC_CTRL:
1623 if (!msr_info->host_initiated &&
1624 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1627 /* The STIBP bit doesn't fault even if it's not advertised */
1628 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
1631 vmx->spec_ctrl = data;
1638 * When it's written (to non-zero) for the first time, pass
1642 * The handling of the MSR bitmap for L2 guests is done in
1643 * nested_vmx_merge_msr_bitmap. We should not touch the
1644 * vmcs02.msr_bitmap here since it gets completely overwritten
1645 * in the merging. We update the vmcs01 here for L1 as well
1646 * since it will end up touching the MSR anyway now.
1648 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
1652 case MSR_IA32_PRED_CMD:
1653 if (!msr_info->host_initiated &&
1654 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1657 if (data & ~PRED_CMD_IBPB)
1663 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
1667 * When it's written (to non-zero) for the first time, pass
1671 * The handling of the MSR bitmap for L2 guests is done in
1672 * nested_vmx_merge_msr_bitmap. We should not touch the
1673 * vmcs02.msr_bitmap here since it gets completely overwritten
1676 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
1679 case MSR_IA32_ARCH_CAPABILITIES:
1680 if (!msr_info->host_initiated)
1682 vmx->arch_capabilities = data;
1684 case MSR_IA32_CR_PAT:
1685 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
1686 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
1688 vmcs_write64(GUEST_IA32_PAT, data);
1689 vcpu->arch.pat = data;
1692 ret = kvm_set_msr_common(vcpu, msr_info);
1694 case MSR_IA32_TSC_ADJUST:
1695 ret = kvm_set_msr_common(vcpu, msr_info);
1697 case MSR_IA32_MCG_EXT_CTL:
1698 if ((!msr_info->host_initiated &&
1699 !(to_vmx(vcpu)->msr_ia32_feature_control &
1700 FEATURE_CONTROL_LMCE)) ||
1701 (data & ~MCG_EXT_CTL_LMCE_EN))
1703 vcpu->arch.mcg_ext_ctl = data;
1705 case MSR_IA32_FEATURE_CONTROL:
1706 if (!vmx_feature_control_msr_valid(vcpu, data) ||
1707 (to_vmx(vcpu)->msr_ia32_feature_control &
1708 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
1710 vmx->msr_ia32_feature_control = data;
1711 if (msr_info->host_initiated && data == 0)
1712 vmx_leave_nested(vcpu);
1714 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1715 if (!msr_info->host_initiated)
1716 return 1; /* they are read-only */
1717 if (!nested_vmx_allowed(vcpu))
1719 return vmx_set_vmx_msr(vcpu, msr_index, data);
1721 if (!vmx_xsaves_supported())
1724 * The only supported bit as of Skylake is bit 8, but
1725 * it is not supported on KVM.
1729 vcpu->arch.ia32_xss = data;
1730 if (vcpu->arch.ia32_xss != host_xss)
1731 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
1732 vcpu->arch.ia32_xss, host_xss, false);
1734 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
1737 if (!msr_info->host_initiated &&
1738 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1740 /* Check reserved bit, higher 32 bits should be zero */
1741 if ((data >> 32) != 0)
1743 /* Otherwise falls through */
1745 msr = find_msr_entry(vmx, msr_index);
1747 u64 old_msr_data = msr->data;
1749 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
1751 ret = kvm_set_shared_msr(msr->index, msr->data,
1755 msr->data = old_msr_data;
1759 ret = kvm_set_msr_common(vcpu, msr_info);
1765 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1767 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
1770 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
1773 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
1775 case VCPU_EXREG_PDPTR:
1777 ept_save_pdptrs(vcpu);
1784 static __init int cpu_has_kvm_support(void)
1786 return cpu_has_vmx();
1789 static __init int vmx_disabled_by_bios(void)
1793 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
1794 if (msr & FEATURE_CONTROL_LOCKED) {
1795 /* launched w/ TXT and VMX disabled */
1796 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
1799 /* launched w/o TXT and VMX only enabled w/ TXT */
1800 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
1801 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
1802 && !tboot_enabled()) {
1803 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
1804 "activate TXT before enabling KVM\n");
1807 /* launched w/o TXT and VMX disabled */
1808 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
1809 && !tboot_enabled())
1816 static void kvm_cpu_vmxon(u64 addr)
1818 cr4_set_bits(X86_CR4_VMXE);
1819 intel_pt_handle_vmx(1);
1821 asm volatile ("vmxon %0" : : "m"(addr));
1824 static int hardware_enable(void)
1826 int cpu = raw_smp_processor_id();
1827 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
1830 if (cr4_read_shadow() & X86_CR4_VMXE)
1834 * This can happen if we hot-added a CPU but failed to allocate
1835 * VP assist page for it.
1837 if (static_branch_unlikely(&enable_evmcs) &&
1838 !hv_get_vp_assist_page(cpu))
1841 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
1842 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
1843 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
1846 * Now we can enable the vmclear operation in kdump
1847 * since the loaded_vmcss_on_cpu list on this cpu
1848 * has been initialized.
1850 * Though the cpu is not in VMX operation now, there
1851 * is no problem to enable the vmclear operation
1852 * for the loaded_vmcss_on_cpu list is empty!
1854 crash_enable_local_vmclear(cpu);
1856 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
1858 test_bits = FEATURE_CONTROL_LOCKED;
1859 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
1860 if (tboot_enabled())
1861 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
1863 if ((old & test_bits) != test_bits) {
1864 /* enable and lock */
1865 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
1867 kvm_cpu_vmxon(phys_addr);
1874 static void vmclear_local_loaded_vmcss(void)
1876 int cpu = raw_smp_processor_id();
1877 struct loaded_vmcs *v, *n;
1879 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
1880 loaded_vmcss_on_cpu_link)
1881 __loaded_vmcs_clear(v);
1885 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
1888 static void kvm_cpu_vmxoff(void)
1890 asm volatile (__ex("vmxoff"));
1892 intel_pt_handle_vmx(0);
1893 cr4_clear_bits(X86_CR4_VMXE);
1896 static void hardware_disable(void)
1898 vmclear_local_loaded_vmcss();
1902 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
1903 u32 msr, u32 *result)
1905 u32 vmx_msr_low, vmx_msr_high;
1906 u32 ctl = ctl_min | ctl_opt;
1908 rdmsr(msr, vmx_msr_low, vmx_msr_high);
1910 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
1911 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
1913 /* Ensure minimum (required) set of control bits are supported. */
1921 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
1922 struct vmx_capability *vmx_cap)
1924 u32 vmx_msr_low, vmx_msr_high;
1925 u32 min, opt, min2, opt2;
1926 u32 _pin_based_exec_control = 0;
1927 u32 _cpu_based_exec_control = 0;
1928 u32 _cpu_based_2nd_exec_control = 0;
1929 u32 _vmexit_control = 0;
1930 u32 _vmentry_control = 0;
1932 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
1933 min = CPU_BASED_HLT_EXITING |
1934 #ifdef CONFIG_X86_64
1935 CPU_BASED_CR8_LOAD_EXITING |
1936 CPU_BASED_CR8_STORE_EXITING |
1938 CPU_BASED_CR3_LOAD_EXITING |
1939 CPU_BASED_CR3_STORE_EXITING |
1940 CPU_BASED_UNCOND_IO_EXITING |
1941 CPU_BASED_MOV_DR_EXITING |
1942 CPU_BASED_USE_TSC_OFFSETING |
1943 CPU_BASED_MWAIT_EXITING |
1944 CPU_BASED_MONITOR_EXITING |
1945 CPU_BASED_INVLPG_EXITING |
1946 CPU_BASED_RDPMC_EXITING;
1948 opt = CPU_BASED_TPR_SHADOW |
1949 CPU_BASED_USE_MSR_BITMAPS |
1950 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1951 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
1952 &_cpu_based_exec_control) < 0)
1954 #ifdef CONFIG_X86_64
1955 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
1956 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
1957 ~CPU_BASED_CR8_STORE_EXITING;
1959 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
1961 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
1962 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
1963 SECONDARY_EXEC_WBINVD_EXITING |
1964 SECONDARY_EXEC_ENABLE_VPID |
1965 SECONDARY_EXEC_ENABLE_EPT |
1966 SECONDARY_EXEC_UNRESTRICTED_GUEST |
1967 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
1968 SECONDARY_EXEC_DESC |
1969 SECONDARY_EXEC_RDTSCP |
1970 SECONDARY_EXEC_ENABLE_INVPCID |
1971 SECONDARY_EXEC_APIC_REGISTER_VIRT |
1972 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
1973 SECONDARY_EXEC_SHADOW_VMCS |
1974 SECONDARY_EXEC_XSAVES |
1975 SECONDARY_EXEC_RDSEED_EXITING |
1976 SECONDARY_EXEC_RDRAND_EXITING |
1977 SECONDARY_EXEC_ENABLE_PML |
1978 SECONDARY_EXEC_TSC_SCALING |
1979 SECONDARY_EXEC_ENABLE_VMFUNC |
1980 SECONDARY_EXEC_ENCLS_EXITING;
1981 if (adjust_vmx_controls(min2, opt2,
1982 MSR_IA32_VMX_PROCBASED_CTLS2,
1983 &_cpu_based_2nd_exec_control) < 0)
1986 #ifndef CONFIG_X86_64
1987 if (!(_cpu_based_2nd_exec_control &
1988 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
1989 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
1992 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
1993 _cpu_based_2nd_exec_control &= ~(
1994 SECONDARY_EXEC_APIC_REGISTER_VIRT |
1995 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
1996 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1998 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
1999 &vmx_cap->ept, &vmx_cap->vpid);
2001 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2002 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2004 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2005 CPU_BASED_CR3_STORE_EXITING |
2006 CPU_BASED_INVLPG_EXITING);
2007 } else if (vmx_cap->ept) {
2009 pr_warn_once("EPT CAP should not exist if not support "
2010 "1-setting enable EPT VM-execution control\n");
2012 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2015 pr_warn_once("VPID CAP should not exist if not support "
2016 "1-setting enable VPID VM-execution control\n");
2019 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2020 #ifdef CONFIG_X86_64
2021 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2023 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2024 VM_EXIT_SAVE_IA32_PAT |
2025 VM_EXIT_LOAD_IA32_PAT |
2026 VM_EXIT_LOAD_IA32_EFER |
2027 VM_EXIT_CLEAR_BNDCFGS;
2028 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2029 &_vmexit_control) < 0)
2032 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2033 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2034 PIN_BASED_VMX_PREEMPTION_TIMER;
2035 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2036 &_pin_based_exec_control) < 0)
2039 if (cpu_has_broken_vmx_preemption_timer())
2040 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2041 if (!(_cpu_based_2nd_exec_control &
2042 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2043 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2045 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2046 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2047 VM_ENTRY_LOAD_IA32_PAT |
2048 VM_ENTRY_LOAD_IA32_EFER |
2049 VM_ENTRY_LOAD_BNDCFGS;
2050 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2051 &_vmentry_control) < 0)
2055 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2056 * can't be used due to an errata where VM Exit may incorrectly clear
2057 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2058 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2060 if (boot_cpu_data.x86 == 0x6) {
2061 switch (boot_cpu_data.x86_model) {
2062 case 26: /* AAK155 */
2063 case 30: /* AAP115 */
2064 case 37: /* AAT100 */
2065 case 44: /* BC86,AAY89,BD102 */
2067 _vmexit_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2068 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2069 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2070 "does not work properly. Using workaround\n");
2078 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2080 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2081 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2084 #ifdef CONFIG_X86_64
2085 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2086 if (vmx_msr_high & (1u<<16))
2090 /* Require Write-Back (WB) memory type for VMCS accesses. */
2091 if (((vmx_msr_high >> 18) & 15) != 6)
2094 vmcs_conf->size = vmx_msr_high & 0x1fff;
2095 vmcs_conf->order = get_order(vmcs_conf->size);
2096 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2098 vmcs_conf->revision_id = vmx_msr_low;
2100 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2101 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2102 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2103 vmcs_conf->vmexit_ctrl = _vmexit_control;
2104 vmcs_conf->vmentry_ctrl = _vmentry_control;
2106 if (static_branch_unlikely(&enable_evmcs))
2107 evmcs_sanitize_exec_ctrls(vmcs_conf);
2112 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
2114 int node = cpu_to_node(cpu);
2118 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
2121 vmcs = page_address(pages);
2122 memset(vmcs, 0, vmcs_config.size);
2124 /* KVM supports Enlightened VMCS v1 only */
2125 if (static_branch_unlikely(&enable_evmcs))
2126 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2128 vmcs->hdr.revision_id = vmcs_config.revision_id;
2131 vmcs->hdr.shadow_vmcs = 1;
2135 void free_vmcs(struct vmcs *vmcs)
2137 free_pages((unsigned long)vmcs, vmcs_config.order);
2141 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2143 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2145 if (!loaded_vmcs->vmcs)
2147 loaded_vmcs_clear(loaded_vmcs);
2148 free_vmcs(loaded_vmcs->vmcs);
2149 loaded_vmcs->vmcs = NULL;
2150 if (loaded_vmcs->msr_bitmap)
2151 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2152 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2155 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2157 loaded_vmcs->vmcs = alloc_vmcs(false);
2158 if (!loaded_vmcs->vmcs)
2161 loaded_vmcs->shadow_vmcs = NULL;
2162 loaded_vmcs_init(loaded_vmcs);
2164 if (cpu_has_vmx_msr_bitmap()) {
2165 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
2166 if (!loaded_vmcs->msr_bitmap)
2168 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2170 if (IS_ENABLED(CONFIG_HYPERV) &&
2171 static_branch_unlikely(&enable_evmcs) &&
2172 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2173 struct hv_enlightened_vmcs *evmcs =
2174 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2176 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2180 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2185 free_loaded_vmcs(loaded_vmcs);
2189 static void free_kvm_area(void)
2193 for_each_possible_cpu(cpu) {
2194 free_vmcs(per_cpu(vmxarea, cpu));
2195 per_cpu(vmxarea, cpu) = NULL;
2199 static __init int alloc_kvm_area(void)
2203 for_each_possible_cpu(cpu) {
2206 vmcs = alloc_vmcs_cpu(false, cpu);
2213 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2214 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2215 * revision_id reported by MSR_IA32_VMX_BASIC.
2217 * However, even though not explictly documented by
2218 * TLFS, VMXArea passed as VMXON argument should
2219 * still be marked with revision_id reported by
2222 if (static_branch_unlikely(&enable_evmcs))
2223 vmcs->hdr.revision_id = vmcs_config.revision_id;
2225 per_cpu(vmxarea, cpu) = vmcs;
2230 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2231 struct kvm_segment *save)
2233 if (!emulate_invalid_guest_state) {
2235 * CS and SS RPL should be equal during guest entry according
2236 * to VMX spec, but in reality it is not always so. Since vcpu
2237 * is in the middle of the transition from real mode to
2238 * protected mode it is safe to assume that RPL 0 is a good
2241 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2242 save->selector &= ~SEGMENT_RPL_MASK;
2243 save->dpl = save->selector & SEGMENT_RPL_MASK;
2246 vmx_set_segment(vcpu, save, seg);
2249 static void enter_pmode(struct kvm_vcpu *vcpu)
2251 unsigned long flags;
2252 struct vcpu_vmx *vmx = to_vmx(vcpu);
2255 * Update real mode segment cache. It may be not up-to-date if sement
2256 * register was written while vcpu was in a guest mode.
2258 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2259 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2260 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2261 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2262 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2263 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2265 vmx->rmode.vm86_active = 0;
2267 vmx_segment_cache_clear(vmx);
2269 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2271 flags = vmcs_readl(GUEST_RFLAGS);
2272 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2273 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2274 vmcs_writel(GUEST_RFLAGS, flags);
2276 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2277 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2279 update_exception_bitmap(vcpu);
2281 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2282 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2283 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2284 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2285 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2286 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2289 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2291 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2292 struct kvm_segment var = *save;
2295 if (seg == VCPU_SREG_CS)
2298 if (!emulate_invalid_guest_state) {
2299 var.selector = var.base >> 4;
2300 var.base = var.base & 0xffff0;
2310 if (save->base & 0xf)
2311 printk_once(KERN_WARNING "kvm: segment base is not "
2312 "paragraph aligned when entering "
2313 "protected mode (seg=%d)", seg);
2316 vmcs_write16(sf->selector, var.selector);
2317 vmcs_writel(sf->base, var.base);
2318 vmcs_write32(sf->limit, var.limit);
2319 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2322 static void enter_rmode(struct kvm_vcpu *vcpu)
2324 unsigned long flags;
2325 struct vcpu_vmx *vmx = to_vmx(vcpu);
2326 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2328 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2329 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2330 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2331 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2332 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2333 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2334 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2336 vmx->rmode.vm86_active = 1;
2339 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2340 * vcpu. Warn the user that an update is overdue.
2342 if (!kvm_vmx->tss_addr)
2343 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2344 "called before entering vcpu\n");
2346 vmx_segment_cache_clear(vmx);
2348 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2349 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2350 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2352 flags = vmcs_readl(GUEST_RFLAGS);
2353 vmx->rmode.save_rflags = flags;
2355 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2357 vmcs_writel(GUEST_RFLAGS, flags);
2358 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2359 update_exception_bitmap(vcpu);
2361 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2362 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2363 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2364 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2365 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2366 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2368 kvm_mmu_reset_context(vcpu);
2371 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2373 struct vcpu_vmx *vmx = to_vmx(vcpu);
2374 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2379 vcpu->arch.efer = efer;
2380 if (efer & EFER_LMA) {
2381 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2384 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2386 msr->data = efer & ~EFER_LME;
2391 #ifdef CONFIG_X86_64
2393 static void enter_lmode(struct kvm_vcpu *vcpu)
2397 vmx_segment_cache_clear(to_vmx(vcpu));
2399 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2400 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2401 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2403 vmcs_write32(GUEST_TR_AR_BYTES,
2404 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2405 | VMX_AR_TYPE_BUSY_64_TSS);
2407 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2410 static void exit_lmode(struct kvm_vcpu *vcpu)
2412 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2413 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2418 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2420 int vpid = to_vmx(vcpu)->vpid;
2422 if (!vpid_sync_vcpu_addr(vpid, addr))
2423 vpid_sync_context(vpid);
2426 * If VPIDs are not supported or enabled, then the above is a no-op.
2427 * But we don't really need a TLB flush in that case anyway, because
2428 * each VM entry/exit includes an implicit flush when VPID is 0.
2432 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2434 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2436 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
2437 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
2440 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2442 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
2443 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2444 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2447 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2449 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2451 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2452 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2455 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2457 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2459 if (!test_bit(VCPU_EXREG_PDPTR,
2460 (unsigned long *)&vcpu->arch.regs_dirty))
2463 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2464 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2465 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2466 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2467 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2471 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2473 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2475 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2476 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2477 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2478 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2479 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2482 __set_bit(VCPU_EXREG_PDPTR,
2483 (unsigned long *)&vcpu->arch.regs_avail);
2484 __set_bit(VCPU_EXREG_PDPTR,
2485 (unsigned long *)&vcpu->arch.regs_dirty);
2488 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2490 struct kvm_vcpu *vcpu)
2492 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2493 vmx_decache_cr3(vcpu);
2494 if (!(cr0 & X86_CR0_PG)) {
2495 /* From paging/starting to nonpaging */
2496 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2497 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
2498 (CPU_BASED_CR3_LOAD_EXITING |
2499 CPU_BASED_CR3_STORE_EXITING));
2500 vcpu->arch.cr0 = cr0;
2501 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2502 } else if (!is_paging(vcpu)) {
2503 /* From nonpaging to paging */
2504 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2505 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
2506 ~(CPU_BASED_CR3_LOAD_EXITING |
2507 CPU_BASED_CR3_STORE_EXITING));
2508 vcpu->arch.cr0 = cr0;
2509 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2512 if (!(cr0 & X86_CR0_WP))
2513 *hw_cr0 &= ~X86_CR0_WP;
2516 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2518 struct vcpu_vmx *vmx = to_vmx(vcpu);
2519 unsigned long hw_cr0;
2521 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
2522 if (enable_unrestricted_guest)
2523 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
2525 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
2527 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
2530 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
2534 #ifdef CONFIG_X86_64
2535 if (vcpu->arch.efer & EFER_LME) {
2536 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
2538 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
2543 if (enable_ept && !enable_unrestricted_guest)
2544 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
2546 vmcs_writel(CR0_READ_SHADOW, cr0);
2547 vmcs_writel(GUEST_CR0, hw_cr0);
2548 vcpu->arch.cr0 = cr0;
2550 /* depends on vcpu->arch.cr0 to be set to a new value */
2551 vmx->emulation_required = emulation_required(vcpu);
2554 static int get_ept_level(struct kvm_vcpu *vcpu)
2556 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
2561 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
2563 u64 eptp = VMX_EPTP_MT_WB;
2565 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
2567 if (enable_ept_ad_bits &&
2568 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
2569 eptp |= VMX_EPTP_AD_ENABLE_BIT;
2570 eptp |= (root_hpa & PAGE_MASK);
2575 void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
2577 struct kvm *kvm = vcpu->kvm;
2578 unsigned long guest_cr3;
2583 eptp = construct_eptp(vcpu, cr3);
2584 vmcs_write64(EPT_POINTER, eptp);
2586 if (kvm_x86_ops->tlb_remote_flush) {
2587 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2588 to_vmx(vcpu)->ept_pointer = eptp;
2589 to_kvm_vmx(kvm)->ept_pointers_match
2590 = EPT_POINTERS_CHECK;
2591 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2594 if (enable_unrestricted_guest || is_paging(vcpu) ||
2595 is_guest_mode(vcpu))
2596 guest_cr3 = kvm_read_cr3(vcpu);
2598 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
2599 ept_load_pdptrs(vcpu);
2602 vmcs_writel(GUEST_CR3, guest_cr3);
2605 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2608 * Pass through host's Machine Check Enable value to hw_cr4, which
2609 * is in force while we are in guest mode. Do not let guests control
2610 * this bit, even if host CR4.MCE == 0.
2612 unsigned long hw_cr4;
2614 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
2615 if (enable_unrestricted_guest)
2616 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
2617 else if (to_vmx(vcpu)->rmode.vm86_active)
2618 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
2620 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
2622 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
2623 if (cr4 & X86_CR4_UMIP) {
2624 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
2625 SECONDARY_EXEC_DESC);
2626 hw_cr4 &= ~X86_CR4_UMIP;
2627 } else if (!is_guest_mode(vcpu) ||
2628 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
2629 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
2630 SECONDARY_EXEC_DESC);
2633 if (cr4 & X86_CR4_VMXE) {
2635 * To use VMXON (and later other VMX instructions), a guest
2636 * must first be able to turn on cr4.VMXE (see handle_vmon()).
2637 * So basically the check on whether to allow nested VMX
2638 * is here. We operate under the default treatment of SMM,
2639 * so VMX cannot be enabled under SMM.
2641 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
2645 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
2648 vcpu->arch.cr4 = cr4;
2650 if (!enable_unrestricted_guest) {
2652 if (!is_paging(vcpu)) {
2653 hw_cr4 &= ~X86_CR4_PAE;
2654 hw_cr4 |= X86_CR4_PSE;
2655 } else if (!(cr4 & X86_CR4_PAE)) {
2656 hw_cr4 &= ~X86_CR4_PAE;
2661 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
2662 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
2663 * to be manually disabled when guest switches to non-paging
2666 * If !enable_unrestricted_guest, the CPU is always running
2667 * with CR0.PG=1 and CR4 needs to be modified.
2668 * If enable_unrestricted_guest, the CPU automatically
2669 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
2671 if (!is_paging(vcpu))
2672 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
2675 vmcs_writel(CR4_READ_SHADOW, cr4);
2676 vmcs_writel(GUEST_CR4, hw_cr4);
2680 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
2682 struct vcpu_vmx *vmx = to_vmx(vcpu);
2685 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
2686 *var = vmx->rmode.segs[seg];
2687 if (seg == VCPU_SREG_TR
2688 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
2690 var->base = vmx_read_guest_seg_base(vmx, seg);
2691 var->selector = vmx_read_guest_seg_selector(vmx, seg);
2694 var->base = vmx_read_guest_seg_base(vmx, seg);
2695 var->limit = vmx_read_guest_seg_limit(vmx, seg);
2696 var->selector = vmx_read_guest_seg_selector(vmx, seg);
2697 ar = vmx_read_guest_seg_ar(vmx, seg);
2698 var->unusable = (ar >> 16) & 1;
2699 var->type = ar & 15;
2700 var->s = (ar >> 4) & 1;
2701 var->dpl = (ar >> 5) & 3;
2703 * Some userspaces do not preserve unusable property. Since usable
2704 * segment has to be present according to VMX spec we can use present
2705 * property to amend userspace bug by making unusable segment always
2706 * nonpresent. vmx_segment_access_rights() already marks nonpresent
2707 * segment as unusable.
2709 var->present = !var->unusable;
2710 var->avl = (ar >> 12) & 1;
2711 var->l = (ar >> 13) & 1;
2712 var->db = (ar >> 14) & 1;
2713 var->g = (ar >> 15) & 1;
2716 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2718 struct kvm_segment s;
2720 if (to_vmx(vcpu)->rmode.vm86_active) {
2721 vmx_get_segment(vcpu, &s, seg);
2724 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
2727 int vmx_get_cpl(struct kvm_vcpu *vcpu)
2729 struct vcpu_vmx *vmx = to_vmx(vcpu);
2731 if (unlikely(vmx->rmode.vm86_active))
2734 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
2735 return VMX_AR_DPL(ar);
2739 static u32 vmx_segment_access_rights(struct kvm_segment *var)
2743 if (var->unusable || !var->present)
2746 ar = var->type & 15;
2747 ar |= (var->s & 1) << 4;
2748 ar |= (var->dpl & 3) << 5;
2749 ar |= (var->present & 1) << 7;
2750 ar |= (var->avl & 1) << 12;
2751 ar |= (var->l & 1) << 13;
2752 ar |= (var->db & 1) << 14;
2753 ar |= (var->g & 1) << 15;
2759 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
2761 struct vcpu_vmx *vmx = to_vmx(vcpu);
2762 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2764 vmx_segment_cache_clear(vmx);
2766 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
2767 vmx->rmode.segs[seg] = *var;
2768 if (seg == VCPU_SREG_TR)
2769 vmcs_write16(sf->selector, var->selector);
2771 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
2775 vmcs_writel(sf->base, var->base);
2776 vmcs_write32(sf->limit, var->limit);
2777 vmcs_write16(sf->selector, var->selector);
2780 * Fix the "Accessed" bit in AR field of segment registers for older
2782 * IA32 arch specifies that at the time of processor reset the
2783 * "Accessed" bit in the AR field of segment registers is 1. And qemu
2784 * is setting it to 0 in the userland code. This causes invalid guest
2785 * state vmexit when "unrestricted guest" mode is turned on.
2786 * Fix for this setup issue in cpu_reset is being pushed in the qemu
2787 * tree. Newer qemu binaries with that qemu fix would not need this
2790 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
2791 var->type |= 0x1; /* Accessed */
2793 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
2796 vmx->emulation_required = emulation_required(vcpu);
2799 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
2801 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
2803 *db = (ar >> 14) & 1;
2804 *l = (ar >> 13) & 1;
2807 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2809 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
2810 dt->address = vmcs_readl(GUEST_IDTR_BASE);
2813 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2815 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
2816 vmcs_writel(GUEST_IDTR_BASE, dt->address);
2819 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2821 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
2822 dt->address = vmcs_readl(GUEST_GDTR_BASE);
2825 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2827 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
2828 vmcs_writel(GUEST_GDTR_BASE, dt->address);
2831 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
2833 struct kvm_segment var;
2836 vmx_get_segment(vcpu, &var, seg);
2838 if (seg == VCPU_SREG_CS)
2840 ar = vmx_segment_access_rights(&var);
2842 if (var.base != (var.selector << 4))
2844 if (var.limit != 0xffff)
2852 static bool code_segment_valid(struct kvm_vcpu *vcpu)
2854 struct kvm_segment cs;
2855 unsigned int cs_rpl;
2857 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
2858 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
2862 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
2866 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
2867 if (cs.dpl > cs_rpl)
2870 if (cs.dpl != cs_rpl)
2876 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
2880 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
2882 struct kvm_segment ss;
2883 unsigned int ss_rpl;
2885 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
2886 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
2890 if (ss.type != 3 && ss.type != 7)
2894 if (ss.dpl != ss_rpl) /* DPL != RPL */
2902 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
2904 struct kvm_segment var;
2907 vmx_get_segment(vcpu, &var, seg);
2908 rpl = var.selector & SEGMENT_RPL_MASK;
2916 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
2917 if (var.dpl < rpl) /* DPL < RPL */
2921 /* TODO: Add other members to kvm_segment_field to allow checking for other access
2927 static bool tr_valid(struct kvm_vcpu *vcpu)
2929 struct kvm_segment tr;
2931 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
2935 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
2937 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
2945 static bool ldtr_valid(struct kvm_vcpu *vcpu)
2947 struct kvm_segment ldtr;
2949 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
2953 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
2963 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
2965 struct kvm_segment cs, ss;
2967 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
2968 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
2970 return ((cs.selector & SEGMENT_RPL_MASK) ==
2971 (ss.selector & SEGMENT_RPL_MASK));
2975 * Check if guest state is valid. Returns true if valid, false if
2977 * We assume that registers are always usable
2979 static bool guest_state_valid(struct kvm_vcpu *vcpu)
2981 if (enable_unrestricted_guest)
2984 /* real mode guest state checks */
2985 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
2986 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
2988 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
2990 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
2992 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
2994 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
2996 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
2999 /* protected mode guest state checks */
3000 if (!cs_ss_rpl_check(vcpu))
3002 if (!code_segment_valid(vcpu))
3004 if (!stack_segment_valid(vcpu))
3006 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3008 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3010 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3012 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3014 if (!tr_valid(vcpu))
3016 if (!ldtr_valid(vcpu))
3020 * - Add checks on RIP
3021 * - Add checks on RFLAGS
3027 static int init_rmode_tss(struct kvm *kvm)
3033 idx = srcu_read_lock(&kvm->srcu);
3034 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3035 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3038 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3039 r = kvm_write_guest_page(kvm, fn++, &data,
3040 TSS_IOPB_BASE_OFFSET, sizeof(u16));
3043 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3046 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3050 r = kvm_write_guest_page(kvm, fn, &data,
3051 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3054 srcu_read_unlock(&kvm->srcu, idx);
3058 static int init_rmode_identity_map(struct kvm *kvm)
3060 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3062 kvm_pfn_t identity_map_pfn;
3065 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3066 mutex_lock(&kvm->slots_lock);
3068 if (likely(kvm_vmx->ept_identity_pagetable_done))
3071 if (!kvm_vmx->ept_identity_map_addr)
3072 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3073 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3075 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3076 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3080 idx = srcu_read_lock(&kvm->srcu);
3081 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3084 /* Set up identity-mapping pagetable for EPT in real mode */
3085 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3086 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3087 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3088 r = kvm_write_guest_page(kvm, identity_map_pfn,
3089 &tmp, i * sizeof(tmp), sizeof(tmp));
3093 kvm_vmx->ept_identity_pagetable_done = true;
3096 srcu_read_unlock(&kvm->srcu, idx);
3099 mutex_unlock(&kvm->slots_lock);
3103 static void seg_setup(int seg)
3105 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3108 vmcs_write16(sf->selector, 0);
3109 vmcs_writel(sf->base, 0);
3110 vmcs_write32(sf->limit, 0xffff);
3112 if (seg == VCPU_SREG_CS)
3113 ar |= 0x08; /* code segment */
3115 vmcs_write32(sf->ar_bytes, ar);
3118 static int alloc_apic_access_page(struct kvm *kvm)
3123 mutex_lock(&kvm->slots_lock);
3124 if (kvm->arch.apic_access_page_done)
3126 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3127 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3131 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3132 if (is_error_page(page)) {
3138 * Do not pin the page in memory, so that memory hot-unplug
3139 * is able to migrate it.
3142 kvm->arch.apic_access_page_done = true;
3144 mutex_unlock(&kvm->slots_lock);
3148 int allocate_vpid(void)
3154 spin_lock(&vmx_vpid_lock);
3155 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3156 if (vpid < VMX_NR_VPIDS)
3157 __set_bit(vpid, vmx_vpid_bitmap);
3160 spin_unlock(&vmx_vpid_lock);
3164 void free_vpid(int vpid)
3166 if (!enable_vpid || vpid == 0)
3168 spin_lock(&vmx_vpid_lock);
3169 __clear_bit(vpid, vmx_vpid_bitmap);
3170 spin_unlock(&vmx_vpid_lock);
3173 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3176 int f = sizeof(unsigned long);
3178 if (!cpu_has_vmx_msr_bitmap())
3181 if (static_branch_unlikely(&enable_evmcs))
3182 evmcs_touch_msr_bitmap();
3185 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3186 * have the write-low and read-high bitmap offsets the wrong way round.
3187 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3189 if (msr <= 0x1fff) {
3190 if (type & MSR_TYPE_R)
3192 __clear_bit(msr, msr_bitmap + 0x000 / f);
3194 if (type & MSR_TYPE_W)
3196 __clear_bit(msr, msr_bitmap + 0x800 / f);
3198 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3200 if (type & MSR_TYPE_R)
3202 __clear_bit(msr, msr_bitmap + 0x400 / f);
3204 if (type & MSR_TYPE_W)
3206 __clear_bit(msr, msr_bitmap + 0xc00 / f);
3211 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3214 int f = sizeof(unsigned long);
3216 if (!cpu_has_vmx_msr_bitmap())
3219 if (static_branch_unlikely(&enable_evmcs))
3220 evmcs_touch_msr_bitmap();
3223 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3224 * have the write-low and read-high bitmap offsets the wrong way round.
3225 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3227 if (msr <= 0x1fff) {
3228 if (type & MSR_TYPE_R)
3230 __set_bit(msr, msr_bitmap + 0x000 / f);
3232 if (type & MSR_TYPE_W)
3234 __set_bit(msr, msr_bitmap + 0x800 / f);
3236 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3238 if (type & MSR_TYPE_R)
3240 __set_bit(msr, msr_bitmap + 0x400 / f);
3242 if (type & MSR_TYPE_W)
3244 __set_bit(msr, msr_bitmap + 0xc00 / f);
3249 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3250 u32 msr, int type, bool value)
3253 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3255 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3258 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3262 if (cpu_has_secondary_exec_ctrls() &&
3263 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
3264 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3265 mode |= MSR_BITMAP_MODE_X2APIC;
3266 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3267 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3273 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3278 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3279 unsigned word = msr / BITS_PER_LONG;
3280 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3281 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3284 if (mode & MSR_BITMAP_MODE_X2APIC) {
3286 * TPR reads and writes can be virtualized even if virtual interrupt
3287 * delivery is not in use.
3289 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3290 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3291 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3292 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3293 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3298 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3300 struct vcpu_vmx *vmx = to_vmx(vcpu);
3301 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3302 u8 mode = vmx_msr_bitmap_mode(vcpu);
3303 u8 changed = mode ^ vmx->msr_bitmap_mode;
3308 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3309 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3311 vmx->msr_bitmap_mode = mode;
3314 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
3316 return enable_apicv;
3319 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3321 struct vcpu_vmx *vmx = to_vmx(vcpu);
3326 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3327 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3328 WARN_ON_ONCE(!vmx->nested.virtual_apic_page))
3331 rvi = vmx_get_rvi();
3333 vapic_page = kmap(vmx->nested.virtual_apic_page);
3334 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3335 kunmap(vmx->nested.virtual_apic_page);
3337 return ((rvi & 0xf0) > (vppr & 0xf0));
3340 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3344 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3346 if (vcpu->mode == IN_GUEST_MODE) {
3348 * The vector of interrupt to be delivered to vcpu had
3349 * been set in PIR before this function.
3351 * Following cases will be reached in this block, and
3352 * we always send a notification event in all cases as
3355 * Case 1: vcpu keeps in non-root mode. Sending a
3356 * notification event posts the interrupt to vcpu.
3358 * Case 2: vcpu exits to root mode and is still
3359 * runnable. PIR will be synced to vIRR before the
3360 * next vcpu entry. Sending a notification event in
3361 * this case has no effect, as vcpu is not in root
3364 * Case 3: vcpu exits to root mode and is blocked.
3365 * vcpu_block() has already synced PIR to vIRR and
3366 * never blocks vcpu if vIRR is not cleared. Therefore,
3367 * a blocked vcpu here does not wait for any requested
3368 * interrupts in PIR, and sending a notification event
3369 * which has no effect is safe here.
3372 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3379 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3382 struct vcpu_vmx *vmx = to_vmx(vcpu);
3384 if (is_guest_mode(vcpu) &&
3385 vector == vmx->nested.posted_intr_nv) {
3387 * If a posted intr is not recognized by hardware,
3388 * we will accomplish it in the next vmentry.
3390 vmx->nested.pi_pending = true;
3391 kvm_make_request(KVM_REQ_EVENT, vcpu);
3392 /* the PIR and ON have been set by L1. */
3393 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3394 kvm_vcpu_kick(vcpu);
3400 * Send interrupt to vcpu via posted interrupt way.
3401 * 1. If target vcpu is running(non-root mode), send posted interrupt
3402 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3403 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3404 * interrupt from PIR in next vmentry.
3406 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3408 struct vcpu_vmx *vmx = to_vmx(vcpu);
3411 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3415 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3418 /* If a previous notification has sent the IPI, nothing to do. */
3419 if (pi_test_and_set_on(&vmx->pi_desc))
3422 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3423 kvm_vcpu_kick(vcpu);
3427 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3428 * will not change in the lifetime of the guest.
3429 * Note that host-state that does change is set elsewhere. E.g., host-state
3430 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3432 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3437 unsigned long cr0, cr3, cr4;
3440 WARN_ON(cr0 & X86_CR0_TS);
3441 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
3444 * Save the most likely value for this task's CR3 in the VMCS.
3445 * We can't use __get_current_cr3_fast() because we're not atomic.
3448 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
3449 vmx->loaded_vmcs->host_state.cr3 = cr3;
3451 /* Save the most likely value for this task's CR4 in the VMCS. */
3452 cr4 = cr4_read_shadow();
3453 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
3454 vmx->loaded_vmcs->host_state.cr4 = cr4;
3456 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
3457 #ifdef CONFIG_X86_64
3459 * Load null selectors, so we can avoid reloading them in
3460 * vmx_prepare_switch_to_host(), in case userspace uses
3461 * the null selectors too (the expected case).
3463 vmcs_write16(HOST_DS_SELECTOR, 0);
3464 vmcs_write16(HOST_ES_SELECTOR, 0);
3466 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3467 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3469 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3470 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
3473 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
3474 vmx->host_idt_base = dt.address;
3476 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
3478 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3479 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3480 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
3481 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
3483 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
3484 rdmsr(MSR_IA32_CR_PAT, low32, high32);
3485 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
3488 if (cpu_has_load_ia32_efer())
3489 vmcs_write64(HOST_IA32_EFER, host_efer);
3492 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
3494 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
3496 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
3497 if (is_guest_mode(&vmx->vcpu))
3498 vmx->vcpu.arch.cr4_guest_owned_bits &=
3499 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
3500 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
3503 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
3505 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
3507 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
3508 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
3511 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
3513 /* Enable the preemption timer dynamically */
3514 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3515 return pin_based_exec_ctrl;
3518 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
3520 struct vcpu_vmx *vmx = to_vmx(vcpu);
3522 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
3523 if (cpu_has_secondary_exec_ctrls()) {
3524 if (kvm_vcpu_apicv_active(vcpu))
3525 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
3526 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3527 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3529 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
3530 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3531 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3534 if (cpu_has_vmx_msr_bitmap())
3535 vmx_update_msr_bitmap(vcpu);
3538 u32 vmx_exec_control(struct vcpu_vmx *vmx)
3540 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
3542 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
3543 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
3545 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
3546 exec_control &= ~CPU_BASED_TPR_SHADOW;
3547 #ifdef CONFIG_X86_64
3548 exec_control |= CPU_BASED_CR8_STORE_EXITING |
3549 CPU_BASED_CR8_LOAD_EXITING;
3553 exec_control |= CPU_BASED_CR3_STORE_EXITING |
3554 CPU_BASED_CR3_LOAD_EXITING |
3555 CPU_BASED_INVLPG_EXITING;
3556 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
3557 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
3558 CPU_BASED_MONITOR_EXITING);
3559 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
3560 exec_control &= ~CPU_BASED_HLT_EXITING;
3561 return exec_control;
3565 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
3567 struct kvm_vcpu *vcpu = &vmx->vcpu;
3569 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
3571 if (!cpu_need_virtualize_apic_accesses(vcpu))
3572 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3574 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
3576 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
3577 enable_unrestricted_guest = 0;
3579 if (!enable_unrestricted_guest)
3580 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
3581 if (kvm_pause_in_guest(vmx->vcpu.kvm))
3582 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
3583 if (!kvm_vcpu_apicv_active(vcpu))
3584 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
3585 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3586 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
3588 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
3589 * in vmx_set_cr4. */
3590 exec_control &= ~SECONDARY_EXEC_DESC;
3592 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
3594 We can NOT enable shadow_vmcs here because we don't have yet
3597 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
3600 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
3602 if (vmx_xsaves_supported()) {
3603 /* Exposing XSAVES only when XSAVE is exposed */
3604 bool xsaves_enabled =
3605 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
3606 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
3608 if (!xsaves_enabled)
3609 exec_control &= ~SECONDARY_EXEC_XSAVES;
3613 vmx->nested.msrs.secondary_ctls_high |=
3614 SECONDARY_EXEC_XSAVES;
3616 vmx->nested.msrs.secondary_ctls_high &=
3617 ~SECONDARY_EXEC_XSAVES;
3621 if (vmx_rdtscp_supported()) {
3622 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
3623 if (!rdtscp_enabled)
3624 exec_control &= ~SECONDARY_EXEC_RDTSCP;
3628 vmx->nested.msrs.secondary_ctls_high |=
3629 SECONDARY_EXEC_RDTSCP;
3631 vmx->nested.msrs.secondary_ctls_high &=
3632 ~SECONDARY_EXEC_RDTSCP;
3636 if (vmx_invpcid_supported()) {
3637 /* Exposing INVPCID only when PCID is exposed */
3638 bool invpcid_enabled =
3639 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
3640 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
3642 if (!invpcid_enabled) {
3643 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
3644 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
3648 if (invpcid_enabled)
3649 vmx->nested.msrs.secondary_ctls_high |=
3650 SECONDARY_EXEC_ENABLE_INVPCID;
3652 vmx->nested.msrs.secondary_ctls_high &=
3653 ~SECONDARY_EXEC_ENABLE_INVPCID;
3657 if (vmx_rdrand_supported()) {
3658 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
3660 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
3664 vmx->nested.msrs.secondary_ctls_high |=
3665 SECONDARY_EXEC_RDRAND_EXITING;
3667 vmx->nested.msrs.secondary_ctls_high &=
3668 ~SECONDARY_EXEC_RDRAND_EXITING;
3672 if (vmx_rdseed_supported()) {
3673 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
3675 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
3679 vmx->nested.msrs.secondary_ctls_high |=
3680 SECONDARY_EXEC_RDSEED_EXITING;
3682 vmx->nested.msrs.secondary_ctls_high &=
3683 ~SECONDARY_EXEC_RDSEED_EXITING;
3687 vmx->secondary_exec_control = exec_control;
3690 static void ept_set_mmio_spte_mask(void)
3693 * EPT Misconfigurations can be generated if the value of bits 2:0
3694 * of an EPT paging-structure entry is 110b (write/execute).
3696 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
3697 VMX_EPT_MISCONFIG_WX_VALUE);
3700 #define VMX_XSS_EXIT_BITMAP 0
3703 * Sets up the vmcs for emulated real mode.
3705 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
3710 nested_vmx_vcpu_setup();
3712 if (cpu_has_vmx_msr_bitmap())
3713 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
3715 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
3718 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
3719 vmx->hv_deadline_tsc = -1;
3721 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
3723 if (cpu_has_secondary_exec_ctrls()) {
3724 vmx_compute_secondary_exec_control(vmx);
3725 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
3726 vmx->secondary_exec_control);
3729 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
3730 vmcs_write64(EOI_EXIT_BITMAP0, 0);
3731 vmcs_write64(EOI_EXIT_BITMAP1, 0);
3732 vmcs_write64(EOI_EXIT_BITMAP2, 0);
3733 vmcs_write64(EOI_EXIT_BITMAP3, 0);
3735 vmcs_write16(GUEST_INTR_STATUS, 0);
3737 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
3738 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
3741 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
3742 vmcs_write32(PLE_GAP, ple_gap);
3743 vmx->ple_window = ple_window;
3744 vmx->ple_window_dirty = true;
3747 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
3748 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
3749 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
3751 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
3752 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
3753 vmx_set_constant_host_state(vmx);
3754 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
3755 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
3757 if (cpu_has_vmx_vmfunc())
3758 vmcs_write64(VM_FUNCTION_CONTROL, 0);
3760 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
3761 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
3762 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
3763 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
3764 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
3766 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
3767 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
3769 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
3770 u32 index = vmx_msr_index[i];
3771 u32 data_low, data_high;
3774 if (rdmsr_safe(index, &data_low, &data_high) < 0)
3776 if (wrmsr_safe(index, data_low, data_high) < 0)
3778 vmx->guest_msrs[j].index = i;
3779 vmx->guest_msrs[j].data = 0;
3780 vmx->guest_msrs[j].mask = -1ull;
3784 vmx->arch_capabilities = kvm_get_arch_capabilities();
3786 vm_exit_controls_init(vmx, vmx_vmexit_ctrl());
3788 /* 22.2.1, 20.8.1 */
3789 vm_entry_controls_init(vmx, vmx_vmentry_ctrl());
3791 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
3792 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
3794 set_cr4_guest_host_mask(vmx);
3796 if (vmx_xsaves_supported())
3797 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
3800 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
3801 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
3804 if (cpu_has_vmx_encls_vmexit())
3805 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
3808 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
3810 struct vcpu_vmx *vmx = to_vmx(vcpu);
3811 struct msr_data apic_base_msr;
3814 vmx->rmode.vm86_active = 0;
3817 vcpu->arch.microcode_version = 0x100000000ULL;
3818 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
3819 kvm_set_cr8(vcpu, 0);
3822 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
3823 MSR_IA32_APICBASE_ENABLE;
3824 if (kvm_vcpu_is_reset_bsp(vcpu))
3825 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
3826 apic_base_msr.host_initiated = true;
3827 kvm_set_apic_base(vcpu, &apic_base_msr);
3830 vmx_segment_cache_clear(vmx);
3832 seg_setup(VCPU_SREG_CS);
3833 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
3834 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
3836 seg_setup(VCPU_SREG_DS);
3837 seg_setup(VCPU_SREG_ES);
3838 seg_setup(VCPU_SREG_FS);
3839 seg_setup(VCPU_SREG_GS);
3840 seg_setup(VCPU_SREG_SS);
3842 vmcs_write16(GUEST_TR_SELECTOR, 0);
3843 vmcs_writel(GUEST_TR_BASE, 0);
3844 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
3845 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3847 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
3848 vmcs_writel(GUEST_LDTR_BASE, 0);
3849 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
3850 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
3853 vmcs_write32(GUEST_SYSENTER_CS, 0);
3854 vmcs_writel(GUEST_SYSENTER_ESP, 0);
3855 vmcs_writel(GUEST_SYSENTER_EIP, 0);
3856 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
3859 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
3860 kvm_rip_write(vcpu, 0xfff0);
3862 vmcs_writel(GUEST_GDTR_BASE, 0);
3863 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
3865 vmcs_writel(GUEST_IDTR_BASE, 0);
3866 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
3868 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3869 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
3870 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
3871 if (kvm_mpx_supported())
3872 vmcs_write64(GUEST_BNDCFGS, 0);
3876 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
3878 if (cpu_has_vmx_tpr_shadow() && !init_event) {
3879 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
3880 if (cpu_need_tpr_shadow(vcpu))
3881 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
3882 __pa(vcpu->arch.apic->regs));
3883 vmcs_write32(TPR_THRESHOLD, 0);
3886 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
3889 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
3891 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
3892 vmx->vcpu.arch.cr0 = cr0;
3893 vmx_set_cr0(vcpu, cr0); /* enter rmode */
3894 vmx_set_cr4(vcpu, 0);
3895 vmx_set_efer(vcpu, 0);
3897 update_exception_bitmap(vcpu);
3899 vpid_sync_context(vmx->vpid);
3901 vmx_clear_hlt(vcpu);
3904 static void enable_irq_window(struct kvm_vcpu *vcpu)
3906 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
3907 CPU_BASED_VIRTUAL_INTR_PENDING);
3910 static void enable_nmi_window(struct kvm_vcpu *vcpu)
3913 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
3914 enable_irq_window(vcpu);
3918 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
3919 CPU_BASED_VIRTUAL_NMI_PENDING);
3922 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
3924 struct vcpu_vmx *vmx = to_vmx(vcpu);
3926 int irq = vcpu->arch.interrupt.nr;
3928 trace_kvm_inj_virq(irq);
3930 ++vcpu->stat.irq_injections;
3931 if (vmx->rmode.vm86_active) {
3933 if (vcpu->arch.interrupt.soft)
3934 inc_eip = vcpu->arch.event_exit_inst_len;
3935 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
3936 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3939 intr = irq | INTR_INFO_VALID_MASK;
3940 if (vcpu->arch.interrupt.soft) {
3941 intr |= INTR_TYPE_SOFT_INTR;
3942 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
3943 vmx->vcpu.arch.event_exit_inst_len);
3945 intr |= INTR_TYPE_EXT_INTR;
3946 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
3948 vmx_clear_hlt(vcpu);
3951 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
3953 struct vcpu_vmx *vmx = to_vmx(vcpu);
3957 * Tracking the NMI-blocked state in software is built upon
3958 * finding the next open IRQ window. This, in turn, depends on
3959 * well-behaving guests: They have to keep IRQs disabled at
3960 * least as long as the NMI handler runs. Otherwise we may
3961 * cause NMI nesting, maybe breaking the guest. But as this is
3962 * highly unlikely, we can live with the residual risk.
3964 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
3965 vmx->loaded_vmcs->vnmi_blocked_time = 0;
3968 ++vcpu->stat.nmi_injections;
3969 vmx->loaded_vmcs->nmi_known_unmasked = false;
3971 if (vmx->rmode.vm86_active) {
3972 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
3973 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3977 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
3978 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
3980 vmx_clear_hlt(vcpu);
3983 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
3985 struct vcpu_vmx *vmx = to_vmx(vcpu);
3989 return vmx->loaded_vmcs->soft_vnmi_blocked;
3990 if (vmx->loaded_vmcs->nmi_known_unmasked)
3992 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
3993 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
3997 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
3999 struct vcpu_vmx *vmx = to_vmx(vcpu);
4002 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4003 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4004 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4007 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4009 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4010 GUEST_INTR_STATE_NMI);
4012 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4013 GUEST_INTR_STATE_NMI);
4017 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4019 if (to_vmx(vcpu)->nested.nested_run_pending)
4023 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4026 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4027 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4028 | GUEST_INTR_STATE_NMI));
4031 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4033 return (!to_vmx(vcpu)->nested.nested_run_pending &&
4034 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4035 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4036 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4039 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4043 if (enable_unrestricted_guest)
4046 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4050 to_kvm_vmx(kvm)->tss_addr = addr;
4051 return init_rmode_tss(kvm);
4054 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4056 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4060 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4065 * Update instruction length as we may reinject the exception
4066 * from user space while in guest debugging mode.
4068 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4069 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4070 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4074 if (vcpu->guest_debug &
4075 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4092 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4093 int vec, u32 err_code)
4096 * Instruction with address size override prefix opcode 0x67
4097 * Cause the #SS fault with 0 error code in VM86 mode.
4099 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4100 if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
4101 if (vcpu->arch.halt_request) {
4102 vcpu->arch.halt_request = 0;
4103 return kvm_vcpu_halt(vcpu);
4111 * Forward all other exceptions that are valid in real mode.
4112 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4113 * the required debugging infrastructure rework.
4115 kvm_queue_exception(vcpu, vec);
4120 * Trigger machine check on the host. We assume all the MSRs are already set up
4121 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4122 * We pass a fake environment to the machine check handler because we want
4123 * the guest to be always treated like user space, no matter what context
4124 * it used internally.
4126 static void kvm_machine_check(void)
4128 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4129 struct pt_regs regs = {
4130 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4131 .flags = X86_EFLAGS_IF,
4134 do_machine_check(®s, 0);
4138 static int handle_machine_check(struct kvm_vcpu *vcpu)
4140 /* already handled by vcpu_run */
4144 static int handle_exception(struct kvm_vcpu *vcpu)
4146 struct vcpu_vmx *vmx = to_vmx(vcpu);
4147 struct kvm_run *kvm_run = vcpu->run;
4148 u32 intr_info, ex_no, error_code;
4149 unsigned long cr2, rip, dr6;
4151 enum emulation_result er;
4153 vect_info = vmx->idt_vectoring_info;
4154 intr_info = vmx->exit_intr_info;
4156 if (is_machine_check(intr_info))
4157 return handle_machine_check(vcpu);
4159 if (is_nmi(intr_info))
4160 return 1; /* already handled by vmx_vcpu_run() */
4162 if (is_invalid_opcode(intr_info))
4163 return handle_ud(vcpu);
4166 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4167 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4169 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4170 WARN_ON_ONCE(!enable_vmware_backdoor);
4171 er = kvm_emulate_instruction(vcpu,
4172 EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
4173 if (er == EMULATE_USER_EXIT)
4175 else if (er != EMULATE_DONE)
4176 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4181 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4182 * MMIO, it is better to report an internal error.
4183 * See the comments in vmx_handle_exit.
4185 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4186 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4187 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4188 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4189 vcpu->run->internal.ndata = 3;
4190 vcpu->run->internal.data[0] = vect_info;
4191 vcpu->run->internal.data[1] = intr_info;
4192 vcpu->run->internal.data[2] = error_code;
4196 if (is_page_fault(intr_info)) {
4197 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4198 /* EPT won't cause page fault directly */
4199 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
4200 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4203 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4205 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4206 return handle_rmode_exception(vcpu, ex_no, error_code);
4210 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4213 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4214 if (!(vcpu->guest_debug &
4215 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4216 vcpu->arch.dr6 &= ~15;
4217 vcpu->arch.dr6 |= dr6 | DR6_RTM;
4218 if (is_icebp(intr_info))
4219 skip_emulated_instruction(vcpu);
4221 kvm_queue_exception(vcpu, DB_VECTOR);
4224 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4225 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4229 * Update instruction length as we may reinject #BP from
4230 * user space while in guest debugging mode. Reading it for
4231 * #DB as well causes no harm, it is not used in that case.
4233 vmx->vcpu.arch.event_exit_inst_len =
4234 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4235 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4236 rip = kvm_rip_read(vcpu);
4237 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4238 kvm_run->debug.arch.exception = ex_no;
4241 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4242 kvm_run->ex.exception = ex_no;
4243 kvm_run->ex.error_code = error_code;
4249 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4251 ++vcpu->stat.irq_exits;
4255 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4257 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4258 vcpu->mmio_needed = 0;
4262 static int handle_io(struct kvm_vcpu *vcpu)
4264 unsigned long exit_qualification;
4265 int size, in, string;
4268 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4269 string = (exit_qualification & 16) != 0;
4271 ++vcpu->stat.io_exits;
4274 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4276 port = exit_qualification >> 16;
4277 size = (exit_qualification & 7) + 1;
4278 in = (exit_qualification & 8) != 0;
4280 return kvm_fast_pio(vcpu, size, port, in);
4284 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4287 * Patch in the VMCALL instruction:
4289 hypercall[0] = 0x0f;
4290 hypercall[1] = 0x01;
4291 hypercall[2] = 0xc1;
4294 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4295 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4297 if (is_guest_mode(vcpu)) {
4298 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4299 unsigned long orig_val = val;
4302 * We get here when L2 changed cr0 in a way that did not change
4303 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4304 * but did change L0 shadowed bits. So we first calculate the
4305 * effective cr0 value that L1 would like to write into the
4306 * hardware. It consists of the L2-owned bits from the new
4307 * value combined with the L1-owned bits from L1's guest_cr0.
4309 val = (val & ~vmcs12->cr0_guest_host_mask) |
4310 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4312 if (!nested_guest_cr0_valid(vcpu, val))
4315 if (kvm_set_cr0(vcpu, val))
4317 vmcs_writel(CR0_READ_SHADOW, orig_val);
4320 if (to_vmx(vcpu)->nested.vmxon &&
4321 !nested_host_cr0_valid(vcpu, val))
4324 return kvm_set_cr0(vcpu, val);
4328 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4330 if (is_guest_mode(vcpu)) {
4331 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4332 unsigned long orig_val = val;
4334 /* analogously to handle_set_cr0 */
4335 val = (val & ~vmcs12->cr4_guest_host_mask) |
4336 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4337 if (kvm_set_cr4(vcpu, val))
4339 vmcs_writel(CR4_READ_SHADOW, orig_val);
4342 return kvm_set_cr4(vcpu, val);
4345 static int handle_desc(struct kvm_vcpu *vcpu)
4347 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4348 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4351 static int handle_cr(struct kvm_vcpu *vcpu)
4353 unsigned long exit_qualification, val;
4359 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4360 cr = exit_qualification & 15;
4361 reg = (exit_qualification >> 8) & 15;
4362 switch ((exit_qualification >> 4) & 3) {
4363 case 0: /* mov to cr */
4364 val = kvm_register_readl(vcpu, reg);
4365 trace_kvm_cr_write(cr, val);
4368 err = handle_set_cr0(vcpu, val);
4369 return kvm_complete_insn_gp(vcpu, err);
4371 WARN_ON_ONCE(enable_unrestricted_guest);
4372 err = kvm_set_cr3(vcpu, val);
4373 return kvm_complete_insn_gp(vcpu, err);
4375 err = handle_set_cr4(vcpu, val);
4376 return kvm_complete_insn_gp(vcpu, err);
4378 u8 cr8_prev = kvm_get_cr8(vcpu);
4380 err = kvm_set_cr8(vcpu, cr8);
4381 ret = kvm_complete_insn_gp(vcpu, err);
4382 if (lapic_in_kernel(vcpu))
4384 if (cr8_prev <= cr8)
4387 * TODO: we might be squashing a
4388 * KVM_GUESTDBG_SINGLESTEP-triggered
4389 * KVM_EXIT_DEBUG here.
4391 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4397 WARN_ONCE(1, "Guest should always own CR0.TS");
4398 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4399 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4400 return kvm_skip_emulated_instruction(vcpu);
4401 case 1: /*mov from cr*/
4404 WARN_ON_ONCE(enable_unrestricted_guest);
4405 val = kvm_read_cr3(vcpu);
4406 kvm_register_write(vcpu, reg, val);
4407 trace_kvm_cr_read(cr, val);
4408 return kvm_skip_emulated_instruction(vcpu);
4410 val = kvm_get_cr8(vcpu);
4411 kvm_register_write(vcpu, reg, val);
4412 trace_kvm_cr_read(cr, val);
4413 return kvm_skip_emulated_instruction(vcpu);
4417 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4418 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4419 kvm_lmsw(vcpu, val);
4421 return kvm_skip_emulated_instruction(vcpu);
4425 vcpu->run->exit_reason = 0;
4426 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4427 (int)(exit_qualification >> 4) & 3, cr);
4431 static int handle_dr(struct kvm_vcpu *vcpu)
4433 unsigned long exit_qualification;
4436 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4437 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
4439 /* First, if DR does not exist, trigger UD */
4440 if (!kvm_require_dr(vcpu, dr))
4443 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
4444 if (!kvm_require_cpl(vcpu, 0))
4446 dr7 = vmcs_readl(GUEST_DR7);
4449 * As the vm-exit takes precedence over the debug trap, we
4450 * need to emulate the latter, either for the host or the
4451 * guest debugging itself.
4453 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
4454 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
4455 vcpu->run->debug.arch.dr7 = dr7;
4456 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
4457 vcpu->run->debug.arch.exception = DB_VECTOR;
4458 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
4461 vcpu->arch.dr6 &= ~15;
4462 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
4463 kvm_queue_exception(vcpu, DB_VECTOR);
4468 if (vcpu->guest_debug == 0) {
4469 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4470 CPU_BASED_MOV_DR_EXITING);
4473 * No more DR vmexits; force a reload of the debug registers
4474 * and reenter on this instruction. The next vmexit will
4475 * retrieve the full state of the debug registers.
4477 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4481 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
4482 if (exit_qualification & TYPE_MOV_FROM_DR) {
4485 if (kvm_get_dr(vcpu, dr, &val))
4487 kvm_register_write(vcpu, reg, val);
4489 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
4492 return kvm_skip_emulated_instruction(vcpu);
4495 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
4497 return vcpu->arch.dr6;
4500 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
4504 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
4506 get_debugreg(vcpu->arch.db[0], 0);
4507 get_debugreg(vcpu->arch.db[1], 1);
4508 get_debugreg(vcpu->arch.db[2], 2);
4509 get_debugreg(vcpu->arch.db[3], 3);
4510 get_debugreg(vcpu->arch.dr6, 6);
4511 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
4513 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
4514 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
4517 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
4519 vmcs_writel(GUEST_DR7, val);
4522 static int handle_cpuid(struct kvm_vcpu *vcpu)
4524 return kvm_emulate_cpuid(vcpu);
4527 static int handle_rdmsr(struct kvm_vcpu *vcpu)
4529 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4530 struct msr_data msr_info;
4532 msr_info.index = ecx;
4533 msr_info.host_initiated = false;
4534 if (vmx_get_msr(vcpu, &msr_info)) {
4535 trace_kvm_msr_read_ex(ecx);
4536 kvm_inject_gp(vcpu, 0);
4540 trace_kvm_msr_read(ecx, msr_info.data);
4542 /* FIXME: handling of bits 32:63 of rax, rdx */
4543 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
4544 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
4545 return kvm_skip_emulated_instruction(vcpu);
4548 static int handle_wrmsr(struct kvm_vcpu *vcpu)
4550 struct msr_data msr;
4551 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4552 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
4553 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
4557 msr.host_initiated = false;
4558 if (kvm_set_msr(vcpu, &msr) != 0) {
4559 trace_kvm_msr_write_ex(ecx, data);
4560 kvm_inject_gp(vcpu, 0);
4564 trace_kvm_msr_write(ecx, data);
4565 return kvm_skip_emulated_instruction(vcpu);
4568 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
4570 kvm_apic_update_ppr(vcpu);
4574 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
4576 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4577 CPU_BASED_VIRTUAL_INTR_PENDING);
4579 kvm_make_request(KVM_REQ_EVENT, vcpu);
4581 ++vcpu->stat.irq_window_exits;
4585 static int handle_halt(struct kvm_vcpu *vcpu)
4587 return kvm_emulate_halt(vcpu);
4590 static int handle_vmcall(struct kvm_vcpu *vcpu)
4592 return kvm_emulate_hypercall(vcpu);
4595 static int handle_invd(struct kvm_vcpu *vcpu)
4597 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4600 static int handle_invlpg(struct kvm_vcpu *vcpu)
4602 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4604 kvm_mmu_invlpg(vcpu, exit_qualification);
4605 return kvm_skip_emulated_instruction(vcpu);
4608 static int handle_rdpmc(struct kvm_vcpu *vcpu)
4612 err = kvm_rdpmc(vcpu);
4613 return kvm_complete_insn_gp(vcpu, err);
4616 static int handle_wbinvd(struct kvm_vcpu *vcpu)
4618 return kvm_emulate_wbinvd(vcpu);
4621 static int handle_xsetbv(struct kvm_vcpu *vcpu)
4623 u64 new_bv = kvm_read_edx_eax(vcpu);
4624 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
4626 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
4627 return kvm_skip_emulated_instruction(vcpu);
4631 static int handle_xsaves(struct kvm_vcpu *vcpu)
4633 kvm_skip_emulated_instruction(vcpu);
4634 WARN(1, "this should never happen\n");
4638 static int handle_xrstors(struct kvm_vcpu *vcpu)
4640 kvm_skip_emulated_instruction(vcpu);
4641 WARN(1, "this should never happen\n");
4645 static int handle_apic_access(struct kvm_vcpu *vcpu)
4647 if (likely(fasteoi)) {
4648 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4649 int access_type, offset;
4651 access_type = exit_qualification & APIC_ACCESS_TYPE;
4652 offset = exit_qualification & APIC_ACCESS_OFFSET;
4654 * Sane guest uses MOV to write EOI, with written value
4655 * not cared. So make a short-circuit here by avoiding
4656 * heavy instruction emulation.
4658 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
4659 (offset == APIC_EOI)) {
4660 kvm_lapic_set_eoi(vcpu);
4661 return kvm_skip_emulated_instruction(vcpu);
4664 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4667 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
4669 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4670 int vector = exit_qualification & 0xff;
4672 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
4673 kvm_apic_set_eoi_accelerated(vcpu, vector);
4677 static int handle_apic_write(struct kvm_vcpu *vcpu)
4679 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4680 u32 offset = exit_qualification & 0xfff;
4682 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
4683 kvm_apic_write_nodecode(vcpu, offset);
4687 static int handle_task_switch(struct kvm_vcpu *vcpu)
4689 struct vcpu_vmx *vmx = to_vmx(vcpu);
4690 unsigned long exit_qualification;
4691 bool has_error_code = false;
4694 int reason, type, idt_v, idt_index;
4696 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
4697 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
4698 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
4700 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4702 reason = (u32)exit_qualification >> 30;
4703 if (reason == TASK_SWITCH_GATE && idt_v) {
4705 case INTR_TYPE_NMI_INTR:
4706 vcpu->arch.nmi_injected = false;
4707 vmx_set_nmi_mask(vcpu, true);
4709 case INTR_TYPE_EXT_INTR:
4710 case INTR_TYPE_SOFT_INTR:
4711 kvm_clear_interrupt_queue(vcpu);
4713 case INTR_TYPE_HARD_EXCEPTION:
4714 if (vmx->idt_vectoring_info &
4715 VECTORING_INFO_DELIVER_CODE_MASK) {
4716 has_error_code = true;
4718 vmcs_read32(IDT_VECTORING_ERROR_CODE);
4721 case INTR_TYPE_SOFT_EXCEPTION:
4722 kvm_clear_exception_queue(vcpu);
4728 tss_selector = exit_qualification;
4730 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
4731 type != INTR_TYPE_EXT_INTR &&
4732 type != INTR_TYPE_NMI_INTR))
4733 skip_emulated_instruction(vcpu);
4735 if (kvm_task_switch(vcpu, tss_selector,
4736 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
4737 has_error_code, error_code) == EMULATE_FAIL) {
4738 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4739 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4740 vcpu->run->internal.ndata = 0;
4745 * TODO: What about debug traps on tss switch?
4746 * Are we supposed to inject them and update dr6?
4752 static int handle_ept_violation(struct kvm_vcpu *vcpu)
4754 unsigned long exit_qualification;
4758 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4761 * EPT violation happened while executing iret from NMI,
4762 * "blocked by NMI" bit has to be set before next VM entry.
4763 * There are errata that may cause this bit to not be set:
4766 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
4768 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
4769 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
4771 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
4772 trace_kvm_page_fault(gpa, exit_qualification);
4774 /* Is it a read fault? */
4775 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
4776 ? PFERR_USER_MASK : 0;
4777 /* Is it a write fault? */
4778 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
4779 ? PFERR_WRITE_MASK : 0;
4780 /* Is it a fetch fault? */
4781 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
4782 ? PFERR_FETCH_MASK : 0;
4783 /* ept page table entry is present? */
4784 error_code |= (exit_qualification &
4785 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
4786 EPT_VIOLATION_EXECUTABLE))
4787 ? PFERR_PRESENT_MASK : 0;
4789 error_code |= (exit_qualification & 0x100) != 0 ?
4790 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
4792 vcpu->arch.exit_qualification = exit_qualification;
4793 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
4796 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
4801 * A nested guest cannot optimize MMIO vmexits, because we have an
4802 * nGPA here instead of the required GPA.
4804 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
4805 if (!is_guest_mode(vcpu) &&
4806 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
4807 trace_kvm_fast_mmio(gpa);
4809 * Doing kvm_skip_emulated_instruction() depends on undefined
4810 * behavior: Intel's manual doesn't mandate
4811 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
4812 * occurs and while on real hardware it was observed to be set,
4813 * other hypervisors (namely Hyper-V) don't set it, we end up
4814 * advancing IP with some random value. Disable fast mmio when
4815 * running nested and keep it for real hardware in hope that
4816 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
4818 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
4819 return kvm_skip_emulated_instruction(vcpu);
4821 return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
4825 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
4828 static int handle_nmi_window(struct kvm_vcpu *vcpu)
4830 WARN_ON_ONCE(!enable_vnmi);
4831 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4832 CPU_BASED_VIRTUAL_NMI_PENDING);
4833 ++vcpu->stat.nmi_window_exits;
4834 kvm_make_request(KVM_REQ_EVENT, vcpu);
4839 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
4841 struct vcpu_vmx *vmx = to_vmx(vcpu);
4842 enum emulation_result err = EMULATE_DONE;
4845 bool intr_window_requested;
4846 unsigned count = 130;
4849 * We should never reach the point where we are emulating L2
4850 * due to invalid guest state as that means we incorrectly
4851 * allowed a nested VMEntry with an invalid vmcs12.
4853 WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
4855 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
4856 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
4858 while (vmx->emulation_required && count-- != 0) {
4859 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
4860 return handle_interrupt_window(&vmx->vcpu);
4862 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
4865 err = kvm_emulate_instruction(vcpu, 0);
4867 if (err == EMULATE_USER_EXIT) {
4868 ++vcpu->stat.mmio_exits;
4873 if (err != EMULATE_DONE)
4874 goto emulation_error;
4876 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
4877 vcpu->arch.exception.pending)
4878 goto emulation_error;
4880 if (vcpu->arch.halt_request) {
4881 vcpu->arch.halt_request = 0;
4882 ret = kvm_vcpu_halt(vcpu);
4886 if (signal_pending(current))
4896 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4897 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
4898 vcpu->run->internal.ndata = 0;
4902 static void grow_ple_window(struct kvm_vcpu *vcpu)
4904 struct vcpu_vmx *vmx = to_vmx(vcpu);
4905 int old = vmx->ple_window;
4907 vmx->ple_window = __grow_ple_window(old, ple_window,
4911 if (vmx->ple_window != old)
4912 vmx->ple_window_dirty = true;
4914 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
4917 static void shrink_ple_window(struct kvm_vcpu *vcpu)
4919 struct vcpu_vmx *vmx = to_vmx(vcpu);
4920 int old = vmx->ple_window;
4922 vmx->ple_window = __shrink_ple_window(old, ple_window,
4926 if (vmx->ple_window != old)
4927 vmx->ple_window_dirty = true;
4929 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
4933 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
4935 static void wakeup_handler(void)
4937 struct kvm_vcpu *vcpu;
4938 int cpu = smp_processor_id();
4940 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4941 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
4942 blocked_vcpu_list) {
4943 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
4945 if (pi_test_on(pi_desc) == 1)
4946 kvm_vcpu_kick(vcpu);
4948 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4951 static void vmx_enable_tdp(void)
4953 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
4954 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
4955 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
4956 0ull, VMX_EPT_EXECUTABLE_MASK,
4957 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
4958 VMX_EPT_RWX_MASK, 0ull);
4960 ept_set_mmio_spte_mask();
4965 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
4966 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
4968 static int handle_pause(struct kvm_vcpu *vcpu)
4970 if (!kvm_pause_in_guest(vcpu->kvm))
4971 grow_ple_window(vcpu);
4974 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
4975 * VM-execution control is ignored if CPL > 0. OTOH, KVM
4976 * never set PAUSE_EXITING and just set PLE if supported,
4977 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
4979 kvm_vcpu_on_spin(vcpu, true);
4980 return kvm_skip_emulated_instruction(vcpu);
4983 static int handle_nop(struct kvm_vcpu *vcpu)
4985 return kvm_skip_emulated_instruction(vcpu);
4988 static int handle_mwait(struct kvm_vcpu *vcpu)
4990 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4991 return handle_nop(vcpu);
4994 static int handle_invalid_op(struct kvm_vcpu *vcpu)
4996 kvm_queue_exception(vcpu, UD_VECTOR);
5000 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5005 static int handle_monitor(struct kvm_vcpu *vcpu)
5007 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5008 return handle_nop(vcpu);
5011 static int handle_invpcid(struct kvm_vcpu *vcpu)
5013 u32 vmx_instruction_info;
5017 struct x86_exception e;
5019 unsigned long roots_to_free = 0;
5025 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5026 kvm_queue_exception(vcpu, UD_VECTOR);
5030 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5031 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5034 kvm_inject_gp(vcpu, 0);
5038 /* According to the Intel instruction reference, the memory operand
5039 * is read even if it isn't needed (e.g., for type==all)
5041 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5042 vmx_instruction_info, false, &gva))
5045 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5046 kvm_inject_page_fault(vcpu, &e);
5050 if (operand.pcid >> 12 != 0) {
5051 kvm_inject_gp(vcpu, 0);
5055 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5058 case INVPCID_TYPE_INDIV_ADDR:
5059 if ((!pcid_enabled && (operand.pcid != 0)) ||
5060 is_noncanonical_address(operand.gla, vcpu)) {
5061 kvm_inject_gp(vcpu, 0);
5064 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5065 return kvm_skip_emulated_instruction(vcpu);
5067 case INVPCID_TYPE_SINGLE_CTXT:
5068 if (!pcid_enabled && (operand.pcid != 0)) {
5069 kvm_inject_gp(vcpu, 0);
5073 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5074 kvm_mmu_sync_roots(vcpu);
5075 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5078 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5079 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
5081 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5083 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5085 * If neither the current cr3 nor any of the prev_roots use the
5086 * given PCID, then nothing needs to be done here because a
5087 * resync will happen anyway before switching to any other CR3.
5090 return kvm_skip_emulated_instruction(vcpu);
5092 case INVPCID_TYPE_ALL_NON_GLOBAL:
5094 * Currently, KVM doesn't mark global entries in the shadow
5095 * page tables, so a non-global flush just degenerates to a
5096 * global flush. If needed, we could optimize this later by
5097 * keeping track of global entries in shadow page tables.
5101 case INVPCID_TYPE_ALL_INCL_GLOBAL:
5102 kvm_mmu_unload(vcpu);
5103 return kvm_skip_emulated_instruction(vcpu);
5106 BUG(); /* We have already checked above that type <= 3 */
5110 static int handle_pml_full(struct kvm_vcpu *vcpu)
5112 unsigned long exit_qualification;
5114 trace_kvm_pml_full(vcpu->vcpu_id);
5116 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5119 * PML buffer FULL happened while executing iret from NMI,
5120 * "blocked by NMI" bit has to be set before next VM entry.
5122 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5124 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5125 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5126 GUEST_INTR_STATE_NMI);
5129 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5130 * here.., and there's no userspace involvement needed for PML.
5135 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5137 if (!to_vmx(vcpu)->req_immediate_exit)
5138 kvm_lapic_expired_hv_timer(vcpu);
5143 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5144 * are overwritten by nested_vmx_setup() when nested=1.
5146 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5148 kvm_queue_exception(vcpu, UD_VECTOR);
5152 static int handle_encls(struct kvm_vcpu *vcpu)
5155 * SGX virtualization is not yet supported. There is no software
5156 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5157 * to prevent the guest from executing ENCLS.
5159 kvm_queue_exception(vcpu, UD_VECTOR);
5164 * The exit handlers return 1 if the exit was handled fully and guest execution
5165 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5166 * to be done to userspace and return 0.
5168 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5169 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
5170 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5171 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5172 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5173 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5174 [EXIT_REASON_CR_ACCESS] = handle_cr,
5175 [EXIT_REASON_DR_ACCESS] = handle_dr,
5176 [EXIT_REASON_CPUID] = handle_cpuid,
5177 [EXIT_REASON_MSR_READ] = handle_rdmsr,
5178 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
5179 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
5180 [EXIT_REASON_HLT] = handle_halt,
5181 [EXIT_REASON_INVD] = handle_invd,
5182 [EXIT_REASON_INVLPG] = handle_invlpg,
5183 [EXIT_REASON_RDPMC] = handle_rdpmc,
5184 [EXIT_REASON_VMCALL] = handle_vmcall,
5185 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5186 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5187 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5188 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5189 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5190 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5191 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5192 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5193 [EXIT_REASON_VMON] = handle_vmx_instruction,
5194 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5195 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5196 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5197 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5198 [EXIT_REASON_WBINVD] = handle_wbinvd,
5199 [EXIT_REASON_XSETBV] = handle_xsetbv,
5200 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5201 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5202 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5203 [EXIT_REASON_LDTR_TR] = handle_desc,
5204 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5205 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5206 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5207 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5208 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5209 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5210 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5211 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5212 [EXIT_REASON_RDRAND] = handle_invalid_op,
5213 [EXIT_REASON_RDSEED] = handle_invalid_op,
5214 [EXIT_REASON_XSAVES] = handle_xsaves,
5215 [EXIT_REASON_XRSTORS] = handle_xrstors,
5216 [EXIT_REASON_PML_FULL] = handle_pml_full,
5217 [EXIT_REASON_INVPCID] = handle_invpcid,
5218 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5219 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5220 [EXIT_REASON_ENCLS] = handle_encls,
5223 static const int kvm_vmx_max_exit_handlers =
5224 ARRAY_SIZE(kvm_vmx_exit_handlers);
5226 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5228 *info1 = vmcs_readl(EXIT_QUALIFICATION);
5229 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
5232 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5235 __free_page(vmx->pml_pg);
5240 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5242 struct vcpu_vmx *vmx = to_vmx(vcpu);
5246 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5248 /* Do nothing if PML buffer is empty */
5249 if (pml_idx == (PML_ENTITY_NUM - 1))
5252 /* PML index always points to next available PML buffer entity */
5253 if (pml_idx >= PML_ENTITY_NUM)
5258 pml_buf = page_address(vmx->pml_pg);
5259 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5262 gpa = pml_buf[pml_idx];
5263 WARN_ON(gpa & (PAGE_SIZE - 1));
5264 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5267 /* reset PML index */
5268 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5272 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5273 * Called before reporting dirty_bitmap to userspace.
5275 static void kvm_flush_pml_buffers(struct kvm *kvm)
5278 struct kvm_vcpu *vcpu;
5280 * We only need to kick vcpu out of guest mode here, as PML buffer
5281 * is flushed at beginning of all VMEXITs, and it's obvious that only
5282 * vcpus running in guest are possible to have unflushed GPAs in PML
5285 kvm_for_each_vcpu(i, vcpu, kvm)
5286 kvm_vcpu_kick(vcpu);
5289 static void vmx_dump_sel(char *name, uint32_t sel)
5291 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5292 name, vmcs_read16(sel),
5293 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5294 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5295 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5298 static void vmx_dump_dtsel(char *name, uint32_t limit)
5300 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5301 name, vmcs_read32(limit),
5302 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5305 static void dump_vmcs(void)
5307 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5308 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5309 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5310 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5311 u32 secondary_exec_control = 0;
5312 unsigned long cr4 = vmcs_readl(GUEST_CR4);
5313 u64 efer = vmcs_read64(GUEST_IA32_EFER);
5316 if (cpu_has_secondary_exec_ctrls())
5317 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5319 pr_err("*** Guest State ***\n");
5320 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5321 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5322 vmcs_readl(CR0_GUEST_HOST_MASK));
5323 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5324 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5325 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5326 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5327 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5329 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5330 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5331 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5332 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5334 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5335 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5336 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5337 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5338 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5339 vmcs_readl(GUEST_SYSENTER_ESP),
5340 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5341 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5342 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5343 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5344 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5345 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5346 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5347 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5348 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5349 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5350 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5351 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5352 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5353 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5354 efer, vmcs_read64(GUEST_IA32_PAT));
5355 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5356 vmcs_read64(GUEST_IA32_DEBUGCTL),
5357 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5358 if (cpu_has_load_perf_global_ctrl() &&
5359 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5360 pr_err("PerfGlobCtl = 0x%016llx\n",
5361 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5362 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5363 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5364 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5365 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5366 vmcs_read32(GUEST_ACTIVITY_STATE));
5367 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5368 pr_err("InterruptStatus = %04x\n",
5369 vmcs_read16(GUEST_INTR_STATUS));
5371 pr_err("*** Host State ***\n");
5372 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5373 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5374 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5375 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5376 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5377 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5378 vmcs_read16(HOST_TR_SELECTOR));
5379 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5380 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5381 vmcs_readl(HOST_TR_BASE));
5382 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5383 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5384 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5385 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5386 vmcs_readl(HOST_CR4));
5387 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5388 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5389 vmcs_read32(HOST_IA32_SYSENTER_CS),
5390 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5391 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5392 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5393 vmcs_read64(HOST_IA32_EFER),
5394 vmcs_read64(HOST_IA32_PAT));
5395 if (cpu_has_load_perf_global_ctrl() &&
5396 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5397 pr_err("PerfGlobCtl = 0x%016llx\n",
5398 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5400 pr_err("*** Control State ***\n");
5401 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5402 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5403 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5404 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5405 vmcs_read32(EXCEPTION_BITMAP),
5406 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5407 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5408 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5409 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5410 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5411 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5412 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5413 vmcs_read32(VM_EXIT_INTR_INFO),
5414 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5415 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5416 pr_err(" reason=%08x qualification=%016lx\n",
5417 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5418 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5419 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5420 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5421 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5422 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5423 pr_err("TSC Multiplier = 0x%016llx\n",
5424 vmcs_read64(TSC_MULTIPLIER));
5425 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
5426 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5427 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5428 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5429 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5430 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5431 n = vmcs_read32(CR3_TARGET_COUNT);
5432 for (i = 0; i + 1 < n; i += 4)
5433 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
5434 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
5435 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
5437 pr_err("CR3 target%u=%016lx\n",
5438 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
5439 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5440 pr_err("PLE Gap=%08x Window=%08x\n",
5441 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5442 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5443 pr_err("Virtual processor ID = 0x%04x\n",
5444 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5448 * The guest has exited. See if we can fix it or if we need userspace
5451 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
5453 struct vcpu_vmx *vmx = to_vmx(vcpu);
5454 u32 exit_reason = vmx->exit_reason;
5455 u32 vectoring_info = vmx->idt_vectoring_info;
5457 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
5460 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5461 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5462 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5463 * mode as if vcpus is in root mode, the PML buffer must has been
5467 vmx_flush_pml_buffer(vcpu);
5469 /* If guest state is invalid, start emulating */
5470 if (vmx->emulation_required)
5471 return handle_invalid_guest_state(vcpu);
5473 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
5474 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
5476 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5478 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5479 vcpu->run->fail_entry.hardware_entry_failure_reason
5484 if (unlikely(vmx->fail)) {
5485 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5486 vcpu->run->fail_entry.hardware_entry_failure_reason
5487 = vmcs_read32(VM_INSTRUCTION_ERROR);
5493 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5494 * delivery event since it indicates guest is accessing MMIO.
5495 * The vm-exit can be triggered again after return to guest that
5496 * will cause infinite loop.
5498 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5499 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5500 exit_reason != EXIT_REASON_EPT_VIOLATION &&
5501 exit_reason != EXIT_REASON_PML_FULL &&
5502 exit_reason != EXIT_REASON_TASK_SWITCH)) {
5503 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5504 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
5505 vcpu->run->internal.ndata = 3;
5506 vcpu->run->internal.data[0] = vectoring_info;
5507 vcpu->run->internal.data[1] = exit_reason;
5508 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
5509 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
5510 vcpu->run->internal.ndata++;
5511 vcpu->run->internal.data[3] =
5512 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5517 if (unlikely(!enable_vnmi &&
5518 vmx->loaded_vmcs->soft_vnmi_blocked)) {
5519 if (vmx_interrupt_allowed(vcpu)) {
5520 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5521 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
5522 vcpu->arch.nmi_pending) {
5524 * This CPU don't support us in finding the end of an
5525 * NMI-blocked window if the guest runs with IRQs
5526 * disabled. So we pull the trigger after 1 s of
5527 * futile waiting, but inform the user about this.
5529 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
5530 "state on VCPU %d after 1 s timeout\n",
5531 __func__, vcpu->vcpu_id);
5532 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5536 if (exit_reason < kvm_vmx_max_exit_handlers
5537 && kvm_vmx_exit_handlers[exit_reason])
5538 return kvm_vmx_exit_handlers[exit_reason](vcpu);
5540 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
5542 kvm_queue_exception(vcpu, UD_VECTOR);
5548 * Software based L1D cache flush which is used when microcode providing
5549 * the cache control MSR is not loaded.
5551 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
5552 * flush it is required to read in 64 KiB because the replacement algorithm
5553 * is not exactly LRU. This could be sized at runtime via topology
5554 * information but as all relevant affected CPUs have 32KiB L1D cache size
5555 * there is no point in doing so.
5557 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
5559 int size = PAGE_SIZE << L1D_CACHE_ORDER;
5562 * This code is only executed when the the flush mode is 'cond' or
5565 if (static_branch_likely(&vmx_l1d_flush_cond)) {
5569 * Clear the per-vcpu flush bit, it gets set again
5570 * either from vcpu_run() or from one of the unsafe
5573 flush_l1d = vcpu->arch.l1tf_flush_l1d;
5574 vcpu->arch.l1tf_flush_l1d = false;
5577 * Clear the per-cpu flush bit, it gets set again from
5578 * the interrupt handlers.
5580 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
5581 kvm_clear_cpu_l1tf_flush_l1d();
5587 vcpu->stat.l1d_flush++;
5589 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
5590 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
5595 /* First ensure the pages are in the TLB */
5596 "xorl %%eax, %%eax\n"
5597 ".Lpopulate_tlb:\n\t"
5598 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5599 "addl $4096, %%eax\n\t"
5600 "cmpl %%eax, %[size]\n\t"
5601 "jne .Lpopulate_tlb\n\t"
5602 "xorl %%eax, %%eax\n\t"
5604 /* Now fill the cache */
5605 "xorl %%eax, %%eax\n"
5607 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5608 "addl $64, %%eax\n\t"
5609 "cmpl %%eax, %[size]\n\t"
5610 "jne .Lfill_cache\n\t"
5612 :: [flush_pages] "r" (vmx_l1d_flush_pages),
5614 : "eax", "ebx", "ecx", "edx");
5617 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5619 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5621 if (is_guest_mode(vcpu) &&
5622 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
5625 if (irr == -1 || tpr < irr) {
5626 vmcs_write32(TPR_THRESHOLD, 0);
5630 vmcs_write32(TPR_THRESHOLD, irr);
5633 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5635 u32 sec_exec_control;
5637 if (!lapic_in_kernel(vcpu))
5640 if (!flexpriority_enabled &&
5641 !cpu_has_vmx_virtualize_x2apic_mode())
5644 /* Postpone execution until vmcs01 is the current VMCS. */
5645 if (is_guest_mode(vcpu)) {
5646 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
5650 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5651 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
5652 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
5654 switch (kvm_get_apic_mode(vcpu)) {
5655 case LAPIC_MODE_INVALID:
5656 WARN_ONCE(true, "Invalid local APIC state");
5657 case LAPIC_MODE_DISABLED:
5659 case LAPIC_MODE_XAPIC:
5660 if (flexpriority_enabled) {
5662 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5663 vmx_flush_tlb(vcpu, true);
5666 case LAPIC_MODE_X2APIC:
5667 if (cpu_has_vmx_virtualize_x2apic_mode())
5669 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5672 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
5674 vmx_update_msr_bitmap(vcpu);
5677 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
5679 if (!is_guest_mode(vcpu)) {
5680 vmcs_write64(APIC_ACCESS_ADDR, hpa);
5681 vmx_flush_tlb(vcpu, true);
5685 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
5693 status = vmcs_read16(GUEST_INTR_STATUS);
5695 if (max_isr != old) {
5697 status |= max_isr << 8;
5698 vmcs_write16(GUEST_INTR_STATUS, status);
5702 static void vmx_set_rvi(int vector)
5710 status = vmcs_read16(GUEST_INTR_STATUS);
5711 old = (u8)status & 0xff;
5712 if ((u8)vector != old) {
5714 status |= (u8)vector;
5715 vmcs_write16(GUEST_INTR_STATUS, status);
5719 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
5722 * When running L2, updating RVI is only relevant when
5723 * vmcs12 virtual-interrupt-delivery enabled.
5724 * However, it can be enabled only when L1 also
5725 * intercepts external-interrupts and in that case
5726 * we should not update vmcs02 RVI but instead intercept
5727 * interrupt. Therefore, do nothing when running L2.
5729 if (!is_guest_mode(vcpu))
5730 vmx_set_rvi(max_irr);
5733 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
5735 struct vcpu_vmx *vmx = to_vmx(vcpu);
5737 bool max_irr_updated;
5739 WARN_ON(!vcpu->arch.apicv_active);
5740 if (pi_test_on(&vmx->pi_desc)) {
5741 pi_clear_on(&vmx->pi_desc);
5743 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
5744 * But on x86 this is just a compiler barrier anyway.
5746 smp_mb__after_atomic();
5748 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
5751 * If we are running L2 and L1 has a new pending interrupt
5752 * which can be injected, we should re-evaluate
5753 * what should be done with this new L1 interrupt.
5754 * If L1 intercepts external-interrupts, we should
5755 * exit from L2 to L1. Otherwise, interrupt should be
5756 * delivered directly to L2.
5758 if (is_guest_mode(vcpu) && max_irr_updated) {
5759 if (nested_exit_on_intr(vcpu))
5760 kvm_vcpu_exiting_guest_mode(vcpu);
5762 kvm_make_request(KVM_REQ_EVENT, vcpu);
5765 max_irr = kvm_lapic_find_highest_irr(vcpu);
5767 vmx_hwapic_irr_update(vcpu, max_irr);
5771 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
5773 if (!kvm_vcpu_apicv_active(vcpu))
5776 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
5777 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
5778 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
5779 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
5782 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
5784 struct vcpu_vmx *vmx = to_vmx(vcpu);
5786 pi_clear_on(&vmx->pi_desc);
5787 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
5790 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
5792 u32 exit_intr_info = 0;
5793 u16 basic_exit_reason = (u16)vmx->exit_reason;
5795 if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
5796 || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
5799 if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
5800 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5801 vmx->exit_intr_info = exit_intr_info;
5803 /* if exit due to PF check for async PF */
5804 if (is_page_fault(exit_intr_info))
5805 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5807 /* Handle machine checks before interrupts are enabled */
5808 if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
5809 is_machine_check(exit_intr_info))
5810 kvm_machine_check();
5812 /* We need to handle NMIs before interrupts are enabled */
5813 if (is_nmi(exit_intr_info)) {
5814 kvm_before_interrupt(&vmx->vcpu);
5816 kvm_after_interrupt(&vmx->vcpu);
5820 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
5822 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5824 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
5825 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
5826 unsigned int vector;
5827 unsigned long entry;
5829 struct vcpu_vmx *vmx = to_vmx(vcpu);
5830 #ifdef CONFIG_X86_64
5834 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
5835 desc = (gate_desc *)vmx->host_idt_base + vector;
5836 entry = gate_offset(desc);
5838 #ifdef CONFIG_X86_64
5839 "mov %%" _ASM_SP ", %[sp]\n\t"
5840 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
5845 __ASM_SIZE(push) " $%c[cs]\n\t"
5848 #ifdef CONFIG_X86_64
5853 THUNK_TARGET(entry),
5854 [ss]"i"(__KERNEL_DS),
5855 [cs]"i"(__KERNEL_CS)
5859 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
5861 static bool vmx_has_emulated_msr(int index)
5864 case MSR_IA32_SMBASE:
5866 * We cannot do SMM unless we can run the guest in big
5869 return enable_unrestricted_guest || emulate_invalid_guest_state;
5870 case MSR_AMD64_VIRT_SPEC_CTRL:
5871 /* This is AMD only. */
5878 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
5883 bool idtv_info_valid;
5885 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
5888 if (vmx->loaded_vmcs->nmi_known_unmasked)
5891 * Can't use vmx->exit_intr_info since we're not sure what
5892 * the exit reason is.
5894 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
5895 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
5896 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
5898 * SDM 3: 27.7.1.2 (September 2008)
5899 * Re-set bit "block by NMI" before VM entry if vmexit caused by
5900 * a guest IRET fault.
5901 * SDM 3: 23.2.2 (September 2008)
5902 * Bit 12 is undefined in any of the following cases:
5903 * If the VM exit sets the valid bit in the IDT-vectoring
5904 * information field.
5905 * If the VM exit is due to a double fault.
5907 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
5908 vector != DF_VECTOR && !idtv_info_valid)
5909 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5910 GUEST_INTR_STATE_NMI);
5912 vmx->loaded_vmcs->nmi_known_unmasked =
5913 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
5914 & GUEST_INTR_STATE_NMI);
5915 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
5916 vmx->loaded_vmcs->vnmi_blocked_time +=
5917 ktime_to_ns(ktime_sub(ktime_get(),
5918 vmx->loaded_vmcs->entry_time));
5921 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
5922 u32 idt_vectoring_info,
5923 int instr_len_field,
5924 int error_code_field)
5928 bool idtv_info_valid;
5930 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
5932 vcpu->arch.nmi_injected = false;
5933 kvm_clear_exception_queue(vcpu);
5934 kvm_clear_interrupt_queue(vcpu);
5936 if (!idtv_info_valid)
5939 kvm_make_request(KVM_REQ_EVENT, vcpu);
5941 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
5942 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
5945 case INTR_TYPE_NMI_INTR:
5946 vcpu->arch.nmi_injected = true;
5948 * SDM 3: 27.7.1.2 (September 2008)
5949 * Clear bit "block by NMI" before VM entry if a NMI
5952 vmx_set_nmi_mask(vcpu, false);
5954 case INTR_TYPE_SOFT_EXCEPTION:
5955 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
5957 case INTR_TYPE_HARD_EXCEPTION:
5958 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
5959 u32 err = vmcs_read32(error_code_field);
5960 kvm_requeue_exception_e(vcpu, vector, err);
5962 kvm_requeue_exception(vcpu, vector);
5964 case INTR_TYPE_SOFT_INTR:
5965 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
5967 case INTR_TYPE_EXT_INTR:
5968 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
5975 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
5977 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
5978 VM_EXIT_INSTRUCTION_LEN,
5979 IDT_VECTORING_ERROR_CODE);
5982 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
5984 __vmx_complete_interrupts(vcpu,
5985 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5986 VM_ENTRY_INSTRUCTION_LEN,
5987 VM_ENTRY_EXCEPTION_ERROR_CODE);
5989 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
5992 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
5995 struct perf_guest_switch_msr *msrs;
5997 msrs = perf_guest_get_msrs(&nr_msrs);
6002 for (i = 0; i < nr_msrs; i++)
6003 if (msrs[i].host == msrs[i].guest)
6004 clear_atomic_switch_msr(vmx, msrs[i].msr);
6006 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6007 msrs[i].host, false);
6010 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
6012 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
6013 if (!vmx->loaded_vmcs->hv_timer_armed)
6014 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
6015 PIN_BASED_VMX_PREEMPTION_TIMER);
6016 vmx->loaded_vmcs->hv_timer_armed = true;
6019 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6021 struct vcpu_vmx *vmx = to_vmx(vcpu);
6025 if (vmx->req_immediate_exit) {
6026 vmx_arm_hv_timer(vmx, 0);
6030 if (vmx->hv_deadline_tsc != -1) {
6032 if (vmx->hv_deadline_tsc > tscl)
6033 /* set_hv_timer ensures the delta fits in 32-bits */
6034 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6035 cpu_preemption_timer_multi);
6039 vmx_arm_hv_timer(vmx, delta_tsc);
6043 if (vmx->loaded_vmcs->hv_timer_armed)
6044 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
6045 PIN_BASED_VMX_PREEMPTION_TIMER);
6046 vmx->loaded_vmcs->hv_timer_armed = false;
6049 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
6051 struct vcpu_vmx *vmx = to_vmx(vcpu);
6052 unsigned long cr3, cr4, evmcs_rsp;
6054 /* Record the guest's net vcpu time for enforced NMI injections. */
6055 if (unlikely(!enable_vnmi &&
6056 vmx->loaded_vmcs->soft_vnmi_blocked))
6057 vmx->loaded_vmcs->entry_time = ktime_get();
6059 /* Don't enter VMX if guest state is invalid, let the exit handler
6060 start emulation until we arrive back to a valid state */
6061 if (vmx->emulation_required)
6064 if (vmx->ple_window_dirty) {
6065 vmx->ple_window_dirty = false;
6066 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6069 if (vmx->nested.need_vmcs12_sync)
6070 nested_sync_from_vmcs12(vcpu);
6072 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
6073 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6074 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
6075 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6077 cr3 = __get_current_cr3_fast();
6078 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6079 vmcs_writel(HOST_CR3, cr3);
6080 vmx->loaded_vmcs->host_state.cr3 = cr3;
6083 cr4 = cr4_read_shadow();
6084 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6085 vmcs_writel(HOST_CR4, cr4);
6086 vmx->loaded_vmcs->host_state.cr4 = cr4;
6089 /* When single-stepping over STI and MOV SS, we must clear the
6090 * corresponding interruptibility bits in the guest state. Otherwise
6091 * vmentry fails as it then expects bit 14 (BS) in pending debug
6092 * exceptions being set, but that's not correct for the guest debugging
6094 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6095 vmx_set_interrupt_shadow(vcpu, 0);
6097 if (static_cpu_has(X86_FEATURE_PKU) &&
6098 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
6099 vcpu->arch.pkru != vmx->host_pkru)
6100 __write_pkru(vcpu->arch.pkru);
6102 atomic_switch_perf_msrs(vmx);
6104 vmx_update_hv_timer(vcpu);
6107 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6108 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6109 * is no need to worry about the conditional branch over the wrmsr
6110 * being speculatively taken.
6112 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6114 vmx->__launched = vmx->loaded_vmcs->launched;
6116 evmcs_rsp = static_branch_unlikely(&enable_evmcs) ?
6117 (unsigned long)¤t_evmcs->host_rsp : 0;
6119 if (static_branch_unlikely(&vmx_l1d_should_flush))
6120 vmx_l1d_flush(vcpu);
6123 /* Store host registers */
6124 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
6125 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
6126 "push %%" _ASM_CX " \n\t"
6127 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
6129 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
6130 /* Avoid VMWRITE when Enlightened VMCS is in use */
6131 "test %%" _ASM_SI ", %%" _ASM_SI " \n\t"
6133 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
6136 __ex("vmwrite %%" _ASM_SP ", %%" _ASM_DX) "\n\t"
6138 /* Reload cr2 if changed */
6139 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
6140 "mov %%cr2, %%" _ASM_DX " \n\t"
6141 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
6143 "mov %%" _ASM_AX", %%cr2 \n\t"
6145 /* Check if vmlaunch or vmresume is needed */
6146 "cmpl $0, %c[launched](%0) \n\t"
6147 /* Load guest registers. Don't clobber flags. */
6148 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
6149 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
6150 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
6151 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
6152 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
6153 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
6154 #ifdef CONFIG_X86_64
6155 "mov %c[r8](%0), %%r8 \n\t"
6156 "mov %c[r9](%0), %%r9 \n\t"
6157 "mov %c[r10](%0), %%r10 \n\t"
6158 "mov %c[r11](%0), %%r11 \n\t"
6159 "mov %c[r12](%0), %%r12 \n\t"
6160 "mov %c[r13](%0), %%r13 \n\t"
6161 "mov %c[r14](%0), %%r14 \n\t"
6162 "mov %c[r15](%0), %%r15 \n\t"
6164 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
6166 /* Enter guest mode */
6168 __ex("vmlaunch") "\n\t"
6170 "1: " __ex("vmresume") "\n\t"
6172 /* Save guest registers, load host registers, keep flags */
6173 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
6175 "setbe %c[fail](%0)\n\t"
6176 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
6177 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
6178 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
6179 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
6180 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
6181 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
6182 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
6183 #ifdef CONFIG_X86_64
6184 "mov %%r8, %c[r8](%0) \n\t"
6185 "mov %%r9, %c[r9](%0) \n\t"
6186 "mov %%r10, %c[r10](%0) \n\t"
6187 "mov %%r11, %c[r11](%0) \n\t"
6188 "mov %%r12, %c[r12](%0) \n\t"
6189 "mov %%r13, %c[r13](%0) \n\t"
6190 "mov %%r14, %c[r14](%0) \n\t"
6191 "mov %%r15, %c[r15](%0) \n\t"
6193 * Clear host registers marked as clobbered to prevent
6196 "xor %%r8d, %%r8d \n\t"
6197 "xor %%r9d, %%r9d \n\t"
6198 "xor %%r10d, %%r10d \n\t"
6199 "xor %%r11d, %%r11d \n\t"
6200 "xor %%r12d, %%r12d \n\t"
6201 "xor %%r13d, %%r13d \n\t"
6202 "xor %%r14d, %%r14d \n\t"
6203 "xor %%r15d, %%r15d \n\t"
6205 "mov %%cr2, %%" _ASM_AX " \n\t"
6206 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
6208 "xor %%eax, %%eax \n\t"
6209 "xor %%ebx, %%ebx \n\t"
6210 "xor %%esi, %%esi \n\t"
6211 "xor %%edi, %%edi \n\t"
6212 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
6213 ".pushsection .rodata \n\t"
6214 ".global vmx_return \n\t"
6215 "vmx_return: " _ASM_PTR " 2b \n\t"
6217 : : "c"(vmx), "d"((unsigned long)HOST_RSP), "S"(evmcs_rsp),
6218 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
6219 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
6220 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
6221 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
6222 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
6223 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
6224 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
6225 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
6226 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
6227 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
6228 #ifdef CONFIG_X86_64
6229 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
6230 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
6231 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
6232 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
6233 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
6234 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
6235 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
6236 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
6238 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
6239 [wordsize]"i"(sizeof(ulong))
6241 #ifdef CONFIG_X86_64
6242 , "rax", "rbx", "rdi"
6243 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
6245 , "eax", "ebx", "edi"
6250 * We do not use IBRS in the kernel. If this vCPU has used the
6251 * SPEC_CTRL MSR it may have left it on; save the value and
6252 * turn it off. This is much more efficient than blindly adding
6253 * it to the atomic save/restore list. Especially as the former
6254 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6256 * For non-nested case:
6257 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6261 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6264 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6265 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6267 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6269 /* Eliminate branch target predictions from guest mode */
6272 /* All fields are clean at this point */
6273 if (static_branch_unlikely(&enable_evmcs))
6274 current_evmcs->hv_clean_fields |=
6275 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6277 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6278 if (vmx->host_debugctlmsr)
6279 update_debugctlmsr(vmx->host_debugctlmsr);
6281 #ifndef CONFIG_X86_64
6283 * The sysexit path does not restore ds/es, so we must set them to
6284 * a reasonable value ourselves.
6286 * We can't defer this to vmx_prepare_switch_to_host() since that
6287 * function may be executed in interrupt context, which saves and
6288 * restore segments around it, nullifying its effect.
6290 loadsegment(ds, __USER_DS);
6291 loadsegment(es, __USER_DS);
6294 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
6295 | (1 << VCPU_EXREG_RFLAGS)
6296 | (1 << VCPU_EXREG_PDPTR)
6297 | (1 << VCPU_EXREG_SEGMENTS)
6298 | (1 << VCPU_EXREG_CR3));
6299 vcpu->arch.regs_dirty = 0;
6302 * eager fpu is enabled if PKEY is supported and CR4 is switched
6303 * back on host, so it is safe to read guest PKRU from current
6306 if (static_cpu_has(X86_FEATURE_PKU) &&
6307 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
6308 vcpu->arch.pkru = __read_pkru();
6309 if (vcpu->arch.pkru != vmx->host_pkru)
6310 __write_pkru(vmx->host_pkru);
6313 vmx->nested.nested_run_pending = 0;
6314 vmx->idt_vectoring_info = 0;
6316 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
6317 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6320 vmx->loaded_vmcs->launched = 1;
6321 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6323 vmx_complete_atomic_exit(vmx);
6324 vmx_recover_nmi_blocking(vmx);
6325 vmx_complete_interrupts(vmx);
6327 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
6329 static struct kvm *vmx_vm_alloc(void)
6331 struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
6332 return &kvm_vmx->kvm;
6335 static void vmx_vm_free(struct kvm *kvm)
6337 vfree(to_kvm_vmx(kvm));
6340 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6342 struct vcpu_vmx *vmx = to_vmx(vcpu);
6345 vmx_destroy_pml_buffer(vmx);
6346 free_vpid(vmx->vpid);
6347 leave_guest_mode(vcpu);
6348 nested_vmx_free_vcpu(vcpu);
6349 free_loaded_vmcs(vmx->loaded_vmcs);
6350 kfree(vmx->guest_msrs);
6351 kvm_vcpu_uninit(vcpu);
6352 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6353 kmem_cache_free(kvm_vcpu_cache, vmx);
6356 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
6359 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
6360 unsigned long *msr_bitmap;
6364 return ERR_PTR(-ENOMEM);
6366 vmx->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache, GFP_KERNEL);
6367 if (!vmx->vcpu.arch.guest_fpu) {
6368 printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
6370 goto free_partial_vcpu;
6373 vmx->vpid = allocate_vpid();
6375 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
6382 * If PML is turned on, failure on enabling PML just results in failure
6383 * of creating the vcpu, therefore we can simplify PML logic (by
6384 * avoiding dealing with cases, such as enabling PML partially on vcpus
6385 * for the guest, etc.
6388 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
6393 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
6394 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
6397 if (!vmx->guest_msrs)
6400 err = alloc_loaded_vmcs(&vmx->vmcs01);
6404 msr_bitmap = vmx->vmcs01.msr_bitmap;
6405 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6406 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6407 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6408 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6409 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6410 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6411 vmx->msr_bitmap_mode = 0;
6413 vmx->loaded_vmcs = &vmx->vmcs01;
6415 vmx_vcpu_load(&vmx->vcpu, cpu);
6416 vmx->vcpu.cpu = cpu;
6417 vmx_vcpu_setup(vmx);
6418 vmx_vcpu_put(&vmx->vcpu);
6420 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
6421 err = alloc_apic_access_page(kvm);
6426 if (enable_ept && !enable_unrestricted_guest) {
6427 err = init_rmode_identity_map(kvm);
6433 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
6435 kvm_vcpu_apicv_active(&vmx->vcpu));
6437 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6439 vmx->nested.posted_intr_nv = -1;
6440 vmx->nested.current_vmptr = -1ull;
6442 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
6445 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6446 * or POSTED_INTR_WAKEUP_VECTOR.
6448 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6449 vmx->pi_desc.sn = 1;
6451 vmx->ept_pointer = INVALID_PAGE;
6456 free_loaded_vmcs(vmx->loaded_vmcs);
6458 kfree(vmx->guest_msrs);
6460 vmx_destroy_pml_buffer(vmx);
6462 kvm_vcpu_uninit(&vmx->vcpu);
6464 free_vpid(vmx->vpid);
6465 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6467 kmem_cache_free(kvm_vcpu_cache, vmx);
6468 return ERR_PTR(err);
6471 #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"
6472 #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"
6474 static int vmx_vm_init(struct kvm *kvm)
6476 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
6479 kvm->arch.pause_in_guest = true;
6481 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6482 switch (l1tf_mitigation) {
6483 case L1TF_MITIGATION_OFF:
6484 case L1TF_MITIGATION_FLUSH_NOWARN:
6485 /* 'I explicitly don't care' is set */
6487 case L1TF_MITIGATION_FLUSH:
6488 case L1TF_MITIGATION_FLUSH_NOSMT:
6489 case L1TF_MITIGATION_FULL:
6491 * Warn upon starting the first VM in a potentially
6492 * insecure environment.
6494 if (cpu_smt_control == CPU_SMT_ENABLED)
6495 pr_warn_once(L1TF_MSG_SMT);
6496 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6497 pr_warn_once(L1TF_MSG_L1D);
6499 case L1TF_MITIGATION_FULL_FORCE:
6500 /* Flush is enforced */
6507 static void __init vmx_check_processor_compat(void *rtn)
6509 struct vmcs_config vmcs_conf;
6510 struct vmx_capability vmx_cap;
6513 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
6516 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept,
6518 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6519 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6520 smp_processor_id());
6525 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6530 /* For VT-d and EPT combination
6531 * 1. MMIO: always map as UC
6533 * a. VT-d without snooping control feature: can't guarantee the
6534 * result, try to trust guest.
6535 * b. VT-d with snooping control feature: snooping control feature of
6536 * VT-d engine can guarantee the cache correctness. Just set it
6537 * to WB to keep consistent with host. So the same as item 3.
6538 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
6539 * consistent with host MTRR
6542 cache = MTRR_TYPE_UNCACHABLE;
6546 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
6547 ipat = VMX_EPT_IPAT_BIT;
6548 cache = MTRR_TYPE_WRBACK;
6552 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
6553 ipat = VMX_EPT_IPAT_BIT;
6554 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
6555 cache = MTRR_TYPE_WRBACK;
6557 cache = MTRR_TYPE_UNCACHABLE;
6561 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
6564 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
6567 static int vmx_get_lpage_level(void)
6569 if (enable_ept && !cpu_has_vmx_ept_1g_page())
6570 return PT_DIRECTORY_LEVEL;
6572 /* For shadow and EPT supported 1GB page */
6573 return PT_PDPE_LEVEL;
6576 static void vmcs_set_secondary_exec_control(u32 new_ctl)
6579 * These bits in the secondary execution controls field
6580 * are dynamic, the others are mostly based on the hypervisor
6581 * architecture and the guest's CPUID. Do not touch the
6585 SECONDARY_EXEC_SHADOW_VMCS |
6586 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
6587 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6588 SECONDARY_EXEC_DESC;
6590 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6592 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6593 (new_ctl & ~mask) | (cur_ctl & mask));
6597 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
6598 * (indicating "allowed-1") if they are supported in the guest's CPUID.
6600 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
6602 struct vcpu_vmx *vmx = to_vmx(vcpu);
6603 struct kvm_cpuid_entry2 *entry;
6605 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
6606 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
6608 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
6609 if (entry && (entry->_reg & (_cpuid_mask))) \
6610 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
6613 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
6614 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
6615 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
6616 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
6617 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
6618 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
6619 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
6620 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
6621 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
6622 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
6623 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
6624 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
6625 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
6626 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
6627 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
6629 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
6630 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
6631 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
6632 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
6633 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
6634 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
6636 #undef cr4_fixed1_update
6639 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
6641 struct vcpu_vmx *vmx = to_vmx(vcpu);
6643 if (kvm_mpx_supported()) {
6644 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
6647 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
6648 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
6650 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
6651 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
6656 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
6658 struct vcpu_vmx *vmx = to_vmx(vcpu);
6660 if (cpu_has_secondary_exec_ctrls()) {
6661 vmx_compute_secondary_exec_control(vmx);
6662 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
6665 if (nested_vmx_allowed(vcpu))
6666 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
6667 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
6669 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
6670 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
6672 if (nested_vmx_allowed(vcpu)) {
6673 nested_vmx_cr_fixed1_bits_update(vcpu);
6674 nested_vmx_entry_exit_ctls_update(vcpu);
6678 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
6680 if (func == 1 && nested)
6681 entry->ecx |= bit(X86_FEATURE_VMX);
6684 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
6686 to_vmx(vcpu)->req_immediate_exit = true;
6689 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
6690 struct x86_instruction_info *info,
6691 enum x86_intercept_stage stage)
6693 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6694 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6697 * RDPID causes #UD if disabled through secondary execution controls.
6698 * Because it is marked as EmulateOnUD, we need to intercept it here.
6700 if (info->intercept == x86_intercept_rdtscp &&
6701 !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
6702 ctxt->exception.vector = UD_VECTOR;
6703 ctxt->exception.error_code_valid = false;
6704 return X86EMUL_PROPAGATE_FAULT;
6707 /* TODO: check more intercepts... */
6708 return X86EMUL_CONTINUE;
6711 #ifdef CONFIG_X86_64
6712 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
6713 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
6714 u64 divisor, u64 *result)
6716 u64 low = a << shift, high = a >> (64 - shift);
6718 /* To avoid the overflow on divq */
6719 if (high >= divisor)
6722 /* Low hold the result, high hold rem which is discarded */
6723 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
6724 "rm" (divisor), "0" (low), "1" (high));
6730 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
6732 struct vcpu_vmx *vmx;
6733 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
6735 if (kvm_mwait_in_guest(vcpu->kvm))
6740 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
6741 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
6742 lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
6744 if (delta_tsc > lapic_timer_advance_cycles)
6745 delta_tsc -= lapic_timer_advance_cycles;
6749 /* Convert to host delta tsc if tsc scaling is enabled */
6750 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
6751 u64_shl_div_u64(delta_tsc,
6752 kvm_tsc_scaling_ratio_frac_bits,
6753 vcpu->arch.tsc_scaling_ratio,
6758 * If the delta tsc can't fit in the 32 bit after the multi shift,
6759 * we can't use the preemption timer.
6760 * It's possible that it fits on later vmentries, but checking
6761 * on every vmentry is costly so we just use an hrtimer.
6763 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
6766 vmx->hv_deadline_tsc = tscl + delta_tsc;
6767 return delta_tsc == 0;
6770 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
6772 to_vmx(vcpu)->hv_deadline_tsc = -1;
6776 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
6778 if (!kvm_pause_in_guest(vcpu->kvm))
6779 shrink_ple_window(vcpu);
6782 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
6783 struct kvm_memory_slot *slot)
6785 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
6786 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
6789 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
6790 struct kvm_memory_slot *slot)
6792 kvm_mmu_slot_set_dirty(kvm, slot);
6795 static void vmx_flush_log_dirty(struct kvm *kvm)
6797 kvm_flush_pml_buffers(kvm);
6800 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
6802 struct vmcs12 *vmcs12;
6803 struct vcpu_vmx *vmx = to_vmx(vcpu);
6805 struct page *page = NULL;
6808 if (is_guest_mode(vcpu)) {
6809 WARN_ON_ONCE(vmx->nested.pml_full);
6812 * Check if PML is enabled for the nested guest.
6813 * Whether eptp bit 6 is set is already checked
6814 * as part of A/D emulation.
6816 vmcs12 = get_vmcs12(vcpu);
6817 if (!nested_cpu_has_pml(vmcs12))
6820 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
6821 vmx->nested.pml_full = true;
6825 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
6827 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
6828 if (is_error_page(page))
6831 pml_address = kmap(page);
6832 pml_address[vmcs12->guest_pml_index--] = gpa;
6834 kvm_release_page_clean(page);
6840 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
6841 struct kvm_memory_slot *memslot,
6842 gfn_t offset, unsigned long mask)
6844 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
6847 static void __pi_post_block(struct kvm_vcpu *vcpu)
6849 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6850 struct pi_desc old, new;
6854 old.control = new.control = pi_desc->control;
6855 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
6856 "Wakeup handler not enabled while the VCPU is blocked\n");
6858 dest = cpu_physical_id(vcpu->cpu);
6860 if (x2apic_enabled())
6863 new.ndst = (dest << 8) & 0xFF00;
6865 /* set 'NV' to 'notification vector' */
6866 new.nv = POSTED_INTR_VECTOR;
6867 } while (cmpxchg64(&pi_desc->control, old.control,
6868 new.control) != old.control);
6870 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
6871 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
6872 list_del(&vcpu->blocked_vcpu_list);
6873 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
6874 vcpu->pre_pcpu = -1;
6879 * This routine does the following things for vCPU which is going
6880 * to be blocked if VT-d PI is enabled.
6881 * - Store the vCPU to the wakeup list, so when interrupts happen
6882 * we can find the right vCPU to wake up.
6883 * - Change the Posted-interrupt descriptor as below:
6884 * 'NDST' <-- vcpu->pre_pcpu
6885 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
6886 * - If 'ON' is set during this process, which means at least one
6887 * interrupt is posted for this vCPU, we cannot block it, in
6888 * this case, return 1, otherwise, return 0.
6891 static int pi_pre_block(struct kvm_vcpu *vcpu)
6894 struct pi_desc old, new;
6895 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6897 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
6898 !irq_remapping_cap(IRQ_POSTING_CAP) ||
6899 !kvm_vcpu_apicv_active(vcpu))
6902 WARN_ON(irqs_disabled());
6903 local_irq_disable();
6904 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
6905 vcpu->pre_pcpu = vcpu->cpu;
6906 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
6907 list_add_tail(&vcpu->blocked_vcpu_list,
6908 &per_cpu(blocked_vcpu_on_cpu,
6910 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
6914 old.control = new.control = pi_desc->control;
6916 WARN((pi_desc->sn == 1),
6917 "Warning: SN field of posted-interrupts "
6918 "is set before blocking\n");
6921 * Since vCPU can be preempted during this process,
6922 * vcpu->cpu could be different with pre_pcpu, we
6923 * need to set pre_pcpu as the destination of wakeup
6924 * notification event, then we can find the right vCPU
6925 * to wakeup in wakeup handler if interrupts happen
6926 * when the vCPU is in blocked state.
6928 dest = cpu_physical_id(vcpu->pre_pcpu);
6930 if (x2apic_enabled())
6933 new.ndst = (dest << 8) & 0xFF00;
6935 /* set 'NV' to 'wakeup vector' */
6936 new.nv = POSTED_INTR_WAKEUP_VECTOR;
6937 } while (cmpxchg64(&pi_desc->control, old.control,
6938 new.control) != old.control);
6940 /* We should not block the vCPU if an interrupt is posted for it. */
6941 if (pi_test_on(pi_desc) == 1)
6942 __pi_post_block(vcpu);
6945 return (vcpu->pre_pcpu == -1);
6948 static int vmx_pre_block(struct kvm_vcpu *vcpu)
6950 if (pi_pre_block(vcpu))
6953 if (kvm_lapic_hv_timer_in_use(vcpu))
6954 kvm_lapic_switch_to_sw_timer(vcpu);
6959 static void pi_post_block(struct kvm_vcpu *vcpu)
6961 if (vcpu->pre_pcpu == -1)
6964 WARN_ON(irqs_disabled());
6965 local_irq_disable();
6966 __pi_post_block(vcpu);
6970 static void vmx_post_block(struct kvm_vcpu *vcpu)
6972 if (kvm_x86_ops->set_hv_timer)
6973 kvm_lapic_switch_to_hv_timer(vcpu);
6975 pi_post_block(vcpu);
6979 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
6982 * @host_irq: host irq of the interrupt
6983 * @guest_irq: gsi of the interrupt
6984 * @set: set or unset PI
6985 * returns 0 on success, < 0 on failure
6987 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
6988 uint32_t guest_irq, bool set)
6990 struct kvm_kernel_irq_routing_entry *e;
6991 struct kvm_irq_routing_table *irq_rt;
6992 struct kvm_lapic_irq irq;
6993 struct kvm_vcpu *vcpu;
6994 struct vcpu_data vcpu_info;
6997 if (!kvm_arch_has_assigned_device(kvm) ||
6998 !irq_remapping_cap(IRQ_POSTING_CAP) ||
6999 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7002 idx = srcu_read_lock(&kvm->irq_srcu);
7003 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7004 if (guest_irq >= irq_rt->nr_rt_entries ||
7005 hlist_empty(&irq_rt->map[guest_irq])) {
7006 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7007 guest_irq, irq_rt->nr_rt_entries);
7011 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7012 if (e->type != KVM_IRQ_ROUTING_MSI)
7015 * VT-d PI cannot support posting multicast/broadcast
7016 * interrupts to a vCPU, we still use interrupt remapping
7017 * for these kind of interrupts.
7019 * For lowest-priority interrupts, we only support
7020 * those with single CPU as the destination, e.g. user
7021 * configures the interrupts via /proc/irq or uses
7022 * irqbalance to make the interrupts single-CPU.
7024 * We will support full lowest-priority interrupt later.
7027 kvm_set_msi_irq(kvm, e, &irq);
7028 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
7030 * Make sure the IRTE is in remapped mode if
7031 * we don't handle it in posted mode.
7033 ret = irq_set_vcpu_affinity(host_irq, NULL);
7036 "failed to back to remapped mode, irq: %u\n",
7044 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7045 vcpu_info.vector = irq.vector;
7047 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7048 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7051 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7053 ret = irq_set_vcpu_affinity(host_irq, NULL);
7056 printk(KERN_INFO "%s: failed to update PI IRTE\n",
7064 srcu_read_unlock(&kvm->irq_srcu, idx);
7068 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7070 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7071 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7072 FEATURE_CONTROL_LMCE;
7074 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7075 ~FEATURE_CONTROL_LMCE;
7078 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
7080 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7081 if (to_vmx(vcpu)->nested.nested_run_pending)
7086 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7088 struct vcpu_vmx *vmx = to_vmx(vcpu);
7090 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7091 if (vmx->nested.smm.guest_mode)
7092 nested_vmx_vmexit(vcpu, -1, 0, 0);
7094 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7095 vmx->nested.vmxon = false;
7096 vmx_clear_hlt(vcpu);
7100 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
7102 struct vcpu_vmx *vmx = to_vmx(vcpu);
7105 if (vmx->nested.smm.vmxon) {
7106 vmx->nested.vmxon = true;
7107 vmx->nested.smm.vmxon = false;
7110 if (vmx->nested.smm.guest_mode) {
7111 vcpu->arch.hflags &= ~HF_SMM_MASK;
7112 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7113 vcpu->arch.hflags |= HF_SMM_MASK;
7117 vmx->nested.smm.guest_mode = false;
7122 static int enable_smi_window(struct kvm_vcpu *vcpu)
7127 static __init int hardware_setup(void)
7129 unsigned long host_bndcfgs;
7132 rdmsrl_safe(MSR_EFER, &host_efer);
7134 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7135 kvm_define_shared_msr(i, vmx_msr_index[i]);
7137 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7140 if (boot_cpu_has(X86_FEATURE_NX))
7141 kvm_enable_efer_bits(EFER_NX);
7143 if (boot_cpu_has(X86_FEATURE_MPX)) {
7144 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7145 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7148 if (boot_cpu_has(X86_FEATURE_XSAVES))
7149 rdmsrl(MSR_IA32_XSS, host_xss);
7151 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7152 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7155 if (!cpu_has_vmx_ept() ||
7156 !cpu_has_vmx_ept_4levels() ||
7157 !cpu_has_vmx_ept_mt_wb() ||
7158 !cpu_has_vmx_invept_global())
7161 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7162 enable_ept_ad_bits = 0;
7164 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7165 enable_unrestricted_guest = 0;
7167 if (!cpu_has_vmx_flexpriority())
7168 flexpriority_enabled = 0;
7170 if (!cpu_has_virtual_nmis())
7174 * set_apic_access_page_addr() is used to reload apic access
7175 * page upon invalidation. No need to do anything if not
7176 * using the APIC_ACCESS_ADDR VMCS field.
7178 if (!flexpriority_enabled)
7179 kvm_x86_ops->set_apic_access_page_addr = NULL;
7181 if (!cpu_has_vmx_tpr_shadow())
7182 kvm_x86_ops->update_cr8_intercept = NULL;
7184 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7185 kvm_disable_largepages();
7187 #if IS_ENABLED(CONFIG_HYPERV)
7188 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7190 kvm_x86_ops->tlb_remote_flush = vmx_hv_remote_flush_tlb;
7193 if (!cpu_has_vmx_ple()) {
7196 ple_window_grow = 0;
7198 ple_window_shrink = 0;
7201 if (!cpu_has_vmx_apicv()) {
7203 kvm_x86_ops->sync_pir_to_irr = NULL;
7206 if (cpu_has_vmx_tsc_scaling()) {
7207 kvm_has_tsc_control = true;
7208 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7209 kvm_tsc_scaling_ratio_frac_bits = 48;
7212 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7220 * Only enable PML when hardware supports PML feature, and both EPT
7221 * and EPT A/D bit features are enabled -- PML depends on them to work.
7223 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7227 kvm_x86_ops->slot_enable_log_dirty = NULL;
7228 kvm_x86_ops->slot_disable_log_dirty = NULL;
7229 kvm_x86_ops->flush_log_dirty = NULL;
7230 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7233 if (!cpu_has_vmx_preemption_timer())
7234 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7236 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7239 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7240 cpu_preemption_timer_multi =
7241 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7243 kvm_x86_ops->set_hv_timer = NULL;
7244 kvm_x86_ops->cancel_hv_timer = NULL;
7247 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7249 kvm_mce_cap_supported |= MCG_LMCE_P;
7252 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7253 vmx_capability.ept, enable_apicv);
7255 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7260 r = alloc_kvm_area();
7262 nested_vmx_hardware_unsetup();
7266 static __exit void hardware_unsetup(void)
7269 nested_vmx_hardware_unsetup();
7274 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
7275 .cpu_has_kvm_support = cpu_has_kvm_support,
7276 .disabled_by_bios = vmx_disabled_by_bios,
7277 .hardware_setup = hardware_setup,
7278 .hardware_unsetup = hardware_unsetup,
7279 .check_processor_compatibility = vmx_check_processor_compat,
7280 .hardware_enable = hardware_enable,
7281 .hardware_disable = hardware_disable,
7282 .cpu_has_accelerated_tpr = report_flexpriority,
7283 .has_emulated_msr = vmx_has_emulated_msr,
7285 .vm_init = vmx_vm_init,
7286 .vm_alloc = vmx_vm_alloc,
7287 .vm_free = vmx_vm_free,
7289 .vcpu_create = vmx_create_vcpu,
7290 .vcpu_free = vmx_free_vcpu,
7291 .vcpu_reset = vmx_vcpu_reset,
7293 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7294 .vcpu_load = vmx_vcpu_load,
7295 .vcpu_put = vmx_vcpu_put,
7297 .update_bp_intercept = update_exception_bitmap,
7298 .get_msr_feature = vmx_get_msr_feature,
7299 .get_msr = vmx_get_msr,
7300 .set_msr = vmx_set_msr,
7301 .get_segment_base = vmx_get_segment_base,
7302 .get_segment = vmx_get_segment,
7303 .set_segment = vmx_set_segment,
7304 .get_cpl = vmx_get_cpl,
7305 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7306 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
7307 .decache_cr3 = vmx_decache_cr3,
7308 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
7309 .set_cr0 = vmx_set_cr0,
7310 .set_cr3 = vmx_set_cr3,
7311 .set_cr4 = vmx_set_cr4,
7312 .set_efer = vmx_set_efer,
7313 .get_idt = vmx_get_idt,
7314 .set_idt = vmx_set_idt,
7315 .get_gdt = vmx_get_gdt,
7316 .set_gdt = vmx_set_gdt,
7317 .get_dr6 = vmx_get_dr6,
7318 .set_dr6 = vmx_set_dr6,
7319 .set_dr7 = vmx_set_dr7,
7320 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7321 .cache_reg = vmx_cache_reg,
7322 .get_rflags = vmx_get_rflags,
7323 .set_rflags = vmx_set_rflags,
7325 .tlb_flush = vmx_flush_tlb,
7326 .tlb_flush_gva = vmx_flush_tlb_gva,
7328 .run = vmx_vcpu_run,
7329 .handle_exit = vmx_handle_exit,
7330 .skip_emulated_instruction = skip_emulated_instruction,
7331 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7332 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7333 .patch_hypercall = vmx_patch_hypercall,
7334 .set_irq = vmx_inject_irq,
7335 .set_nmi = vmx_inject_nmi,
7336 .queue_exception = vmx_queue_exception,
7337 .cancel_injection = vmx_cancel_injection,
7338 .interrupt_allowed = vmx_interrupt_allowed,
7339 .nmi_allowed = vmx_nmi_allowed,
7340 .get_nmi_mask = vmx_get_nmi_mask,
7341 .set_nmi_mask = vmx_set_nmi_mask,
7342 .enable_nmi_window = enable_nmi_window,
7343 .enable_irq_window = enable_irq_window,
7344 .update_cr8_intercept = update_cr8_intercept,
7345 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7346 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7347 .get_enable_apicv = vmx_get_enable_apicv,
7348 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7349 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7350 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7351 .hwapic_irr_update = vmx_hwapic_irr_update,
7352 .hwapic_isr_update = vmx_hwapic_isr_update,
7353 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7354 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7355 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7357 .set_tss_addr = vmx_set_tss_addr,
7358 .set_identity_map_addr = vmx_set_identity_map_addr,
7359 .get_tdp_level = get_ept_level,
7360 .get_mt_mask = vmx_get_mt_mask,
7362 .get_exit_info = vmx_get_exit_info,
7364 .get_lpage_level = vmx_get_lpage_level,
7366 .cpuid_update = vmx_cpuid_update,
7368 .rdtscp_supported = vmx_rdtscp_supported,
7369 .invpcid_supported = vmx_invpcid_supported,
7371 .set_supported_cpuid = vmx_set_supported_cpuid,
7373 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7375 .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
7376 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7378 .set_tdp_cr3 = vmx_set_cr3,
7380 .check_intercept = vmx_check_intercept,
7381 .handle_external_intr = vmx_handle_external_intr,
7382 .mpx_supported = vmx_mpx_supported,
7383 .xsaves_supported = vmx_xsaves_supported,
7384 .umip_emulated = vmx_umip_emulated,
7386 .request_immediate_exit = vmx_request_immediate_exit,
7388 .sched_in = vmx_sched_in,
7390 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7391 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7392 .flush_log_dirty = vmx_flush_log_dirty,
7393 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7394 .write_log_dirty = vmx_write_pml_buffer,
7396 .pre_block = vmx_pre_block,
7397 .post_block = vmx_post_block,
7399 .pmu_ops = &intel_pmu_ops,
7401 .update_pi_irte = vmx_update_pi_irte,
7403 #ifdef CONFIG_X86_64
7404 .set_hv_timer = vmx_set_hv_timer,
7405 .cancel_hv_timer = vmx_cancel_hv_timer,
7408 .setup_mce = vmx_setup_mce,
7410 .smi_allowed = vmx_smi_allowed,
7411 .pre_enter_smm = vmx_pre_enter_smm,
7412 .pre_leave_smm = vmx_pre_leave_smm,
7413 .enable_smi_window = enable_smi_window,
7415 .check_nested_events = NULL,
7416 .get_nested_state = NULL,
7417 .set_nested_state = NULL,
7418 .get_vmcs12_pages = NULL,
7419 .nested_enable_evmcs = NULL,
7422 static void vmx_cleanup_l1d_flush(void)
7424 if (vmx_l1d_flush_pages) {
7425 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7426 vmx_l1d_flush_pages = NULL;
7428 /* Restore state so sysfs ignores VMX */
7429 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
7432 static void vmx_exit(void)
7434 #ifdef CONFIG_KEXEC_CORE
7435 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
7441 #if IS_ENABLED(CONFIG_HYPERV)
7442 if (static_branch_unlikely(&enable_evmcs)) {
7444 struct hv_vp_assist_page *vp_ap;
7446 * Reset everything to support using non-enlightened VMCS
7447 * access later (e.g. when we reload the module with
7448 * enlightened_vmcs=0)
7450 for_each_online_cpu(cpu) {
7451 vp_ap = hv_get_vp_assist_page(cpu);
7456 vp_ap->current_nested_vmcs = 0;
7457 vp_ap->enlighten_vmentry = 0;
7460 static_branch_disable(&enable_evmcs);
7463 vmx_cleanup_l1d_flush();
7465 module_exit(vmx_exit);
7467 static int __init vmx_init(void)
7471 #if IS_ENABLED(CONFIG_HYPERV)
7473 * Enlightened VMCS usage should be recommended and the host needs
7474 * to support eVMCS v1 or above. We can also disable eVMCS support
7475 * with module parameter.
7477 if (enlightened_vmcs &&
7478 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
7479 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
7480 KVM_EVMCS_VERSION) {
7483 /* Check that we have assist pages on all online CPUs */
7484 for_each_online_cpu(cpu) {
7485 if (!hv_get_vp_assist_page(cpu)) {
7486 enlightened_vmcs = false;
7491 if (enlightened_vmcs) {
7492 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
7493 static_branch_enable(&enable_evmcs);
7496 enlightened_vmcs = false;
7500 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
7501 __alignof__(struct vcpu_vmx), THIS_MODULE);
7506 * Must be called after kvm_init() so enable_ept is properly set
7507 * up. Hand the parameter mitigation value in which was stored in
7508 * the pre module init parser. If no parameter was given, it will
7509 * contain 'auto' which will be turned into the default 'cond'
7512 if (boot_cpu_has(X86_BUG_L1TF)) {
7513 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
7520 #ifdef CONFIG_KEXEC_CORE
7521 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
7522 crash_vmclear_local_loaded_vmcss);
7524 vmx_check_vmcs12_offsets();
7528 module_init(vmx_init);