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/sched/smt.h>
30 #include <linux/slab.h>
31 #include <linux/tboot.h>
32 #include <linux/trace_events.h>
37 #include <asm/debugreg.h>
39 #include <asm/fpu/internal.h>
41 #include <asm/irq_remapping.h>
42 #include <asm/kexec.h>
43 #include <asm/perf_event.h>
45 #include <asm/mmu_context.h>
46 #include <asm/mshyperv.h>
47 #include <asm/spec-ctrl.h>
48 #include <asm/virtext.h>
51 #include "capabilities.h"
55 #include "kvm_cache_regs.h"
67 MODULE_AUTHOR("Qumranet");
68 MODULE_LICENSE("GPL");
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 static bool __read_mostly dump_invalid_vmcs = 0;
118 module_param(dump_invalid_vmcs, bool, 0644);
120 #define MSR_BITMAP_MODE_X2APIC 1
121 #define MSR_BITMAP_MODE_X2APIC_APICV 2
123 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
125 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
126 static int __read_mostly cpu_preemption_timer_multi;
127 static bool __read_mostly enable_preemption_timer = 1;
129 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
132 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
133 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
134 #define KVM_VM_CR0_ALWAYS_ON \
135 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
136 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
137 #define KVM_CR4_GUEST_OWNED_BITS \
138 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
139 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
141 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
142 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
143 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
145 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
147 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
148 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
149 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
150 RTIT_STATUS_BYTECNT))
152 #define MSR_IA32_RTIT_OUTPUT_BASE_MASK \
153 (~((1UL << cpuid_query_maxphyaddr(vcpu)) - 1) | 0x7f)
156 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
157 * ple_gap: upper bound on the amount of time between two successive
158 * executions of PAUSE in a loop. Also indicate if ple enabled.
159 * According to test, this time is usually smaller than 128 cycles.
160 * ple_window: upper bound on the amount of time a guest is allowed to execute
161 * in a PAUSE loop. Tests indicate that most spinlocks are held for
162 * less than 2^12 cycles
163 * Time is measured based on a counter that runs at the same rate as the TSC,
164 * refer SDM volume 3b section 21.6.13 & 22.1.3.
166 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
167 module_param(ple_gap, uint, 0444);
169 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
170 module_param(ple_window, uint, 0444);
172 /* Default doubles per-vcpu window every exit. */
173 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
174 module_param(ple_window_grow, uint, 0444);
176 /* Default resets per-vcpu window every exit to ple_window. */
177 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
178 module_param(ple_window_shrink, uint, 0444);
180 /* Default is to compute the maximum so we can never overflow. */
181 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
182 module_param(ple_window_max, uint, 0444);
184 /* Default is SYSTEM mode, 1 for host-guest mode */
185 int __read_mostly pt_mode = PT_MODE_SYSTEM;
186 module_param(pt_mode, int, S_IRUGO);
188 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
189 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
190 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
192 /* Storage for pre module init parameter parsing */
193 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
195 static const struct {
198 } vmentry_l1d_param[] = {
199 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
200 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
201 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
202 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
203 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
204 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
207 #define L1D_CACHE_ORDER 4
208 static void *vmx_l1d_flush_pages;
210 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
216 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
220 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
223 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
224 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
225 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
230 /* If set to auto use the default l1tf mitigation method */
231 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
232 switch (l1tf_mitigation) {
233 case L1TF_MITIGATION_OFF:
234 l1tf = VMENTER_L1D_FLUSH_NEVER;
236 case L1TF_MITIGATION_FLUSH_NOWARN:
237 case L1TF_MITIGATION_FLUSH:
238 case L1TF_MITIGATION_FLUSH_NOSMT:
239 l1tf = VMENTER_L1D_FLUSH_COND;
241 case L1TF_MITIGATION_FULL:
242 case L1TF_MITIGATION_FULL_FORCE:
243 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
246 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
247 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
250 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
251 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
253 * This allocation for vmx_l1d_flush_pages is not tied to a VM
254 * lifetime and so should not be charged to a memcg.
256 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
259 vmx_l1d_flush_pages = page_address(page);
262 * Initialize each page with a different pattern in
263 * order to protect against KSM in the nested
264 * virtualization case.
266 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
267 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
272 l1tf_vmx_mitigation = l1tf;
274 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
275 static_branch_enable(&vmx_l1d_should_flush);
277 static_branch_disable(&vmx_l1d_should_flush);
279 if (l1tf == VMENTER_L1D_FLUSH_COND)
280 static_branch_enable(&vmx_l1d_flush_cond);
282 static_branch_disable(&vmx_l1d_flush_cond);
286 static int vmentry_l1d_flush_parse(const char *s)
291 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
292 if (vmentry_l1d_param[i].for_parse &&
293 sysfs_streq(s, vmentry_l1d_param[i].option))
300 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
304 l1tf = vmentry_l1d_flush_parse(s);
308 if (!boot_cpu_has(X86_BUG_L1TF))
312 * Has vmx_init() run already? If not then this is the pre init
313 * parameter parsing. In that case just store the value and let
314 * vmx_init() do the proper setup after enable_ept has been
317 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
318 vmentry_l1d_flush_param = l1tf;
322 mutex_lock(&vmx_l1d_flush_mutex);
323 ret = vmx_setup_l1d_flush(l1tf);
324 mutex_unlock(&vmx_l1d_flush_mutex);
328 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
330 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
331 return sprintf(s, "???\n");
333 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
336 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
337 .set = vmentry_l1d_flush_set,
338 .get = vmentry_l1d_flush_get,
340 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
342 static bool guest_state_valid(struct kvm_vcpu *vcpu);
343 static u32 vmx_segment_access_rights(struct kvm_segment *var);
344 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
347 void vmx_vmexit(void);
349 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
350 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
352 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
353 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
355 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
358 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
359 * can find which vCPU should be waken up.
361 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
362 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
364 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
365 static DEFINE_SPINLOCK(vmx_vpid_lock);
367 struct vmcs_config vmcs_config;
368 struct vmx_capability vmx_capability;
370 #define VMX_SEGMENT_FIELD(seg) \
371 [VCPU_SREG_##seg] = { \
372 .selector = GUEST_##seg##_SELECTOR, \
373 .base = GUEST_##seg##_BASE, \
374 .limit = GUEST_##seg##_LIMIT, \
375 .ar_bytes = GUEST_##seg##_AR_BYTES, \
378 static const struct kvm_vmx_segment_field {
383 } kvm_vmx_segment_fields[] = {
384 VMX_SEGMENT_FIELD(CS),
385 VMX_SEGMENT_FIELD(DS),
386 VMX_SEGMENT_FIELD(ES),
387 VMX_SEGMENT_FIELD(FS),
388 VMX_SEGMENT_FIELD(GS),
389 VMX_SEGMENT_FIELD(SS),
390 VMX_SEGMENT_FIELD(TR),
391 VMX_SEGMENT_FIELD(LDTR),
397 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
398 * will emulate SYSCALL in legacy mode if the vendor string in guest
399 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
400 * support this emulation, IA32_STAR must always be included in
401 * vmx_msr_index[], even in i386 builds.
403 const u32 vmx_msr_index[] = {
405 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
407 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
410 #if IS_ENABLED(CONFIG_HYPERV)
411 static bool __read_mostly enlightened_vmcs = true;
412 module_param(enlightened_vmcs, bool, 0444);
414 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
415 static void check_ept_pointer_match(struct kvm *kvm)
417 struct kvm_vcpu *vcpu;
418 u64 tmp_eptp = INVALID_PAGE;
421 kvm_for_each_vcpu(i, vcpu, kvm) {
422 if (!VALID_PAGE(tmp_eptp)) {
423 tmp_eptp = to_vmx(vcpu)->ept_pointer;
424 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
425 to_kvm_vmx(kvm)->ept_pointers_match
426 = EPT_POINTERS_MISMATCH;
431 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
434 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
437 struct kvm_tlb_range *range = data;
439 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
443 static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
444 struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
446 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
449 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
450 * of the base of EPT PML4 table, strip off EPT configuration
454 return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
455 kvm_fill_hv_flush_list_func, (void *)range);
457 return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
460 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
461 struct kvm_tlb_range *range)
463 struct kvm_vcpu *vcpu;
466 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
468 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
469 check_ept_pointer_match(kvm);
471 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
472 kvm_for_each_vcpu(i, vcpu, kvm) {
473 /* If ept_pointer is invalid pointer, bypass flush request. */
474 if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
475 ret |= __hv_remote_flush_tlb_with_range(
479 ret = __hv_remote_flush_tlb_with_range(kvm,
480 kvm_get_vcpu(kvm, 0), range);
483 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
486 static int hv_remote_flush_tlb(struct kvm *kvm)
488 return hv_remote_flush_tlb_with_range(kvm, NULL);
491 #endif /* IS_ENABLED(CONFIG_HYPERV) */
494 * Comment's format: document - errata name - stepping - processor name.
496 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
498 static u32 vmx_preemption_cpu_tfms[] = {
499 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
501 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
502 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
503 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
505 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
507 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
508 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
510 * 320767.pdf - AAP86 - B1 -
511 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
514 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
516 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
518 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
520 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
521 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
522 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
524 /* Xeon E3-1220 V2 */
528 static inline bool cpu_has_broken_vmx_preemption_timer(void)
530 u32 eax = cpuid_eax(0x00000001), i;
532 /* Clear the reserved bits */
533 eax &= ~(0x3U << 14 | 0xfU << 28);
534 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
535 if (eax == vmx_preemption_cpu_tfms[i])
541 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
543 return flexpriority_enabled && lapic_in_kernel(vcpu);
546 static inline bool report_flexpriority(void)
548 return flexpriority_enabled;
551 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
555 for (i = 0; i < vmx->nmsrs; ++i)
556 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
561 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
565 i = __find_msr_index(vmx, msr);
567 return &vmx->guest_msrs[i];
571 void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
573 vmcs_clear(loaded_vmcs->vmcs);
574 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
575 vmcs_clear(loaded_vmcs->shadow_vmcs);
576 loaded_vmcs->cpu = -1;
577 loaded_vmcs->launched = 0;
580 #ifdef CONFIG_KEXEC_CORE
582 * This bitmap is used to indicate whether the vmclear
583 * operation is enabled on all cpus. All disabled by
586 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
588 static inline void crash_enable_local_vmclear(int cpu)
590 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
593 static inline void crash_disable_local_vmclear(int cpu)
595 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
598 static inline int crash_local_vmclear_enabled(int cpu)
600 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
603 static void crash_vmclear_local_loaded_vmcss(void)
605 int cpu = raw_smp_processor_id();
606 struct loaded_vmcs *v;
608 if (!crash_local_vmclear_enabled(cpu))
611 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
612 loaded_vmcss_on_cpu_link)
616 static inline void crash_enable_local_vmclear(int cpu) { }
617 static inline void crash_disable_local_vmclear(int cpu) { }
618 #endif /* CONFIG_KEXEC_CORE */
620 static void __loaded_vmcs_clear(void *arg)
622 struct loaded_vmcs *loaded_vmcs = arg;
623 int cpu = raw_smp_processor_id();
625 if (loaded_vmcs->cpu != cpu)
626 return; /* vcpu migration can race with cpu offline */
627 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
628 per_cpu(current_vmcs, cpu) = NULL;
629 crash_disable_local_vmclear(cpu);
630 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
633 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
634 * is before setting loaded_vmcs->vcpu to -1 which is done in
635 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
636 * then adds the vmcs into percpu list before it is deleted.
640 loaded_vmcs_init(loaded_vmcs);
641 crash_enable_local_vmclear(cpu);
644 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
646 int cpu = loaded_vmcs->cpu;
649 smp_call_function_single(cpu,
650 __loaded_vmcs_clear, loaded_vmcs, 1);
653 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
657 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
659 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
660 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
661 vmx->segment_cache.bitmask = 0;
663 ret = vmx->segment_cache.bitmask & mask;
664 vmx->segment_cache.bitmask |= mask;
668 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
670 u16 *p = &vmx->segment_cache.seg[seg].selector;
672 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
673 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
677 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
679 ulong *p = &vmx->segment_cache.seg[seg].base;
681 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
682 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
686 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
688 u32 *p = &vmx->segment_cache.seg[seg].limit;
690 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
691 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
695 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
697 u32 *p = &vmx->segment_cache.seg[seg].ar;
699 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
700 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
704 void update_exception_bitmap(struct kvm_vcpu *vcpu)
708 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
709 (1u << DB_VECTOR) | (1u << AC_VECTOR);
711 * Guest access to VMware backdoor ports could legitimately
712 * trigger #GP because of TSS I/O permission bitmap.
713 * We intercept those #GP and allow access to them anyway
716 if (enable_vmware_backdoor)
717 eb |= (1u << GP_VECTOR);
718 if ((vcpu->guest_debug &
719 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
720 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
721 eb |= 1u << BP_VECTOR;
722 if (to_vmx(vcpu)->rmode.vm86_active)
725 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
727 /* When we are running a nested L2 guest and L1 specified for it a
728 * certain exception bitmap, we must trap the same exceptions and pass
729 * them to L1. When running L2, we will only handle the exceptions
730 * specified above if L1 did not want them.
732 if (is_guest_mode(vcpu))
733 eb |= get_vmcs12(vcpu)->exception_bitmap;
735 vmcs_write32(EXCEPTION_BITMAP, eb);
739 * Check if MSR is intercepted for currently loaded MSR bitmap.
741 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
743 unsigned long *msr_bitmap;
744 int f = sizeof(unsigned long);
746 if (!cpu_has_vmx_msr_bitmap())
749 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
752 return !!test_bit(msr, msr_bitmap + 0x800 / f);
753 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
755 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
761 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
762 unsigned long entry, unsigned long exit)
764 vm_entry_controls_clearbit(vmx, entry);
765 vm_exit_controls_clearbit(vmx, exit);
768 static int find_msr(struct vmx_msrs *m, unsigned int msr)
772 for (i = 0; i < m->nr; ++i) {
773 if (m->val[i].index == msr)
779 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
782 struct msr_autoload *m = &vmx->msr_autoload;
786 if (cpu_has_load_ia32_efer()) {
787 clear_atomic_switch_msr_special(vmx,
788 VM_ENTRY_LOAD_IA32_EFER,
789 VM_EXIT_LOAD_IA32_EFER);
793 case MSR_CORE_PERF_GLOBAL_CTRL:
794 if (cpu_has_load_perf_global_ctrl()) {
795 clear_atomic_switch_msr_special(vmx,
796 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
797 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
802 i = find_msr(&m->guest, msr);
806 m->guest.val[i] = m->guest.val[m->guest.nr];
807 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
810 i = find_msr(&m->host, msr);
815 m->host.val[i] = m->host.val[m->host.nr];
816 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
819 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
820 unsigned long entry, unsigned long exit,
821 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
822 u64 guest_val, u64 host_val)
824 vmcs_write64(guest_val_vmcs, guest_val);
825 if (host_val_vmcs != HOST_IA32_EFER)
826 vmcs_write64(host_val_vmcs, host_val);
827 vm_entry_controls_setbit(vmx, entry);
828 vm_exit_controls_setbit(vmx, exit);
831 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
832 u64 guest_val, u64 host_val, bool entry_only)
835 struct msr_autoload *m = &vmx->msr_autoload;
839 if (cpu_has_load_ia32_efer()) {
840 add_atomic_switch_msr_special(vmx,
841 VM_ENTRY_LOAD_IA32_EFER,
842 VM_EXIT_LOAD_IA32_EFER,
845 guest_val, host_val);
849 case MSR_CORE_PERF_GLOBAL_CTRL:
850 if (cpu_has_load_perf_global_ctrl()) {
851 add_atomic_switch_msr_special(vmx,
852 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
853 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
854 GUEST_IA32_PERF_GLOBAL_CTRL,
855 HOST_IA32_PERF_GLOBAL_CTRL,
856 guest_val, host_val);
860 case MSR_IA32_PEBS_ENABLE:
861 /* PEBS needs a quiescent period after being disabled (to write
862 * a record). Disabling PEBS through VMX MSR swapping doesn't
863 * provide that period, so a CPU could write host's record into
866 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
869 i = find_msr(&m->guest, msr);
871 j = find_msr(&m->host, msr);
873 if ((i < 0 && m->guest.nr == NR_AUTOLOAD_MSRS) ||
874 (j < 0 && m->host.nr == NR_AUTOLOAD_MSRS)) {
875 printk_once(KERN_WARNING "Not enough msr switch entries. "
876 "Can't add msr %x\n", msr);
881 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
883 m->guest.val[i].index = msr;
884 m->guest.val[i].value = guest_val;
891 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
893 m->host.val[j].index = msr;
894 m->host.val[j].value = host_val;
897 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
899 u64 guest_efer = vmx->vcpu.arch.efer;
904 * NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
905 * host CPUID is more efficient than testing guest CPUID
906 * or CR4. Host SMEP is anyway a requirement for guest SMEP.
908 if (boot_cpu_has(X86_FEATURE_SMEP))
909 guest_efer |= EFER_NX;
910 else if (!(guest_efer & EFER_NX))
911 ignore_bits |= EFER_NX;
915 * LMA and LME handled by hardware; SCE meaningless outside long mode.
917 ignore_bits |= EFER_SCE;
919 ignore_bits |= EFER_LMA | EFER_LME;
920 /* SCE is meaningful only in long mode on Intel */
921 if (guest_efer & EFER_LMA)
922 ignore_bits &= ~(u64)EFER_SCE;
926 * On EPT, we can't emulate NX, so we must switch EFER atomically.
927 * On CPUs that support "load IA32_EFER", always switch EFER
928 * atomically, since it's faster than switching it manually.
930 if (cpu_has_load_ia32_efer() ||
931 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
932 if (!(guest_efer & EFER_LMA))
933 guest_efer &= ~EFER_LME;
934 if (guest_efer != host_efer)
935 add_atomic_switch_msr(vmx, MSR_EFER,
936 guest_efer, host_efer, false);
938 clear_atomic_switch_msr(vmx, MSR_EFER);
941 clear_atomic_switch_msr(vmx, MSR_EFER);
943 guest_efer &= ~ignore_bits;
944 guest_efer |= host_efer & ignore_bits;
946 vmx->guest_msrs[efer_offset].data = guest_efer;
947 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
955 * On 32-bit kernels, VM exits still load the FS and GS bases from the
956 * VMCS rather than the segment table. KVM uses this helper to figure
957 * out the current bases to poke them into the VMCS before entry.
959 static unsigned long segment_base(u16 selector)
961 struct desc_struct *table;
964 if (!(selector & ~SEGMENT_RPL_MASK))
967 table = get_current_gdt_ro();
969 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
970 u16 ldt_selector = kvm_read_ldt();
972 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
975 table = (struct desc_struct *)segment_base(ldt_selector);
977 v = get_desc_base(&table[selector >> 3]);
982 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
986 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
987 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
988 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
989 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
990 for (i = 0; i < addr_range; i++) {
991 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
992 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
996 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1000 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1001 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1002 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1003 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1004 for (i = 0; i < addr_range; i++) {
1005 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1006 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1010 static void pt_guest_enter(struct vcpu_vmx *vmx)
1012 if (pt_mode == PT_MODE_SYSTEM)
1016 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1017 * Save host state before VM entry.
1019 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1020 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1021 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1022 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1023 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1027 static void pt_guest_exit(struct vcpu_vmx *vmx)
1029 if (pt_mode == PT_MODE_SYSTEM)
1032 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1033 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1034 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1037 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1038 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1041 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1043 struct vcpu_vmx *vmx = to_vmx(vcpu);
1044 struct vmcs_host_state *host_state;
1045 #ifdef CONFIG_X86_64
1046 int cpu = raw_smp_processor_id();
1048 unsigned long fs_base, gs_base;
1052 vmx->req_immediate_exit = false;
1055 * Note that guest MSRs to be saved/restored can also be changed
1056 * when guest state is loaded. This happens when guest transitions
1057 * to/from long-mode by setting MSR_EFER.LMA.
1059 if (!vmx->loaded_cpu_state || vmx->guest_msrs_dirty) {
1060 vmx->guest_msrs_dirty = false;
1061 for (i = 0; i < vmx->save_nmsrs; ++i)
1062 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1063 vmx->guest_msrs[i].data,
1064 vmx->guest_msrs[i].mask);
1068 if (vmx->loaded_cpu_state)
1071 vmx->loaded_cpu_state = vmx->loaded_vmcs;
1072 host_state = &vmx->loaded_cpu_state->host_state;
1075 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1076 * allow segment selectors with cpl > 0 or ti == 1.
1078 host_state->ldt_sel = kvm_read_ldt();
1080 #ifdef CONFIG_X86_64
1081 savesegment(ds, host_state->ds_sel);
1082 savesegment(es, host_state->es_sel);
1084 gs_base = cpu_kernelmode_gs_base(cpu);
1085 if (likely(is_64bit_mm(current->mm))) {
1086 save_fsgs_for_kvm();
1087 fs_sel = current->thread.fsindex;
1088 gs_sel = current->thread.gsindex;
1089 fs_base = current->thread.fsbase;
1090 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1092 savesegment(fs, fs_sel);
1093 savesegment(gs, gs_sel);
1094 fs_base = read_msr(MSR_FS_BASE);
1095 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1098 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1100 savesegment(fs, fs_sel);
1101 savesegment(gs, gs_sel);
1102 fs_base = segment_base(fs_sel);
1103 gs_base = segment_base(gs_sel);
1106 if (unlikely(fs_sel != host_state->fs_sel)) {
1108 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1110 vmcs_write16(HOST_FS_SELECTOR, 0);
1111 host_state->fs_sel = fs_sel;
1113 if (unlikely(gs_sel != host_state->gs_sel)) {
1115 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1117 vmcs_write16(HOST_GS_SELECTOR, 0);
1118 host_state->gs_sel = gs_sel;
1120 if (unlikely(fs_base != host_state->fs_base)) {
1121 vmcs_writel(HOST_FS_BASE, fs_base);
1122 host_state->fs_base = fs_base;
1124 if (unlikely(gs_base != host_state->gs_base)) {
1125 vmcs_writel(HOST_GS_BASE, gs_base);
1126 host_state->gs_base = gs_base;
1130 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1132 struct vmcs_host_state *host_state;
1134 if (!vmx->loaded_cpu_state)
1137 WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
1138 host_state = &vmx->loaded_cpu_state->host_state;
1140 ++vmx->vcpu.stat.host_state_reload;
1141 vmx->loaded_cpu_state = NULL;
1143 #ifdef CONFIG_X86_64
1144 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1146 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1147 kvm_load_ldt(host_state->ldt_sel);
1148 #ifdef CONFIG_X86_64
1149 load_gs_index(host_state->gs_sel);
1151 loadsegment(gs, host_state->gs_sel);
1154 if (host_state->fs_sel & 7)
1155 loadsegment(fs, host_state->fs_sel);
1156 #ifdef CONFIG_X86_64
1157 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1158 loadsegment(ds, host_state->ds_sel);
1159 loadsegment(es, host_state->es_sel);
1162 invalidate_tss_limit();
1163 #ifdef CONFIG_X86_64
1164 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1166 load_fixmap_gdt(raw_smp_processor_id());
1169 #ifdef CONFIG_X86_64
1170 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1173 if (vmx->loaded_cpu_state)
1174 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1176 return vmx->msr_guest_kernel_gs_base;
1179 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1182 if (vmx->loaded_cpu_state)
1183 wrmsrl(MSR_KERNEL_GS_BASE, data);
1185 vmx->msr_guest_kernel_gs_base = data;
1189 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1191 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1192 struct pi_desc old, new;
1196 * In case of hot-plug or hot-unplug, we may have to undo
1197 * vmx_vcpu_pi_put even if there is no assigned device. And we
1198 * always keep PI.NDST up to date for simplicity: it makes the
1199 * code easier, and CPU migration is not a fast path.
1201 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1204 /* The full case. */
1206 old.control = new.control = pi_desc->control;
1208 dest = cpu_physical_id(cpu);
1210 if (x2apic_enabled())
1213 new.ndst = (dest << 8) & 0xFF00;
1216 } while (cmpxchg64(&pi_desc->control, old.control,
1217 new.control) != old.control);
1220 * Clear SN before reading the bitmap. The VT-d firmware
1221 * writes the bitmap and reads SN atomically (5.2.3 in the
1222 * spec), so it doesn't really have a memory barrier that
1223 * pairs with this, but we cannot do that and we need one.
1225 smp_mb__after_atomic();
1227 if (!bitmap_empty((unsigned long *)pi_desc->pir, NR_VECTORS))
1232 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1233 * vcpu mutex is already taken.
1235 void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1237 struct vcpu_vmx *vmx = to_vmx(vcpu);
1238 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1240 if (!already_loaded) {
1241 loaded_vmcs_clear(vmx->loaded_vmcs);
1242 local_irq_disable();
1243 crash_disable_local_vmclear(cpu);
1246 * Read loaded_vmcs->cpu should be before fetching
1247 * loaded_vmcs->loaded_vmcss_on_cpu_link.
1248 * See the comments in __loaded_vmcs_clear().
1252 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1253 &per_cpu(loaded_vmcss_on_cpu, cpu));
1254 crash_enable_local_vmclear(cpu);
1258 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1259 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1260 vmcs_load(vmx->loaded_vmcs->vmcs);
1261 indirect_branch_prediction_barrier();
1264 if (!already_loaded) {
1265 void *gdt = get_current_gdt_ro();
1266 unsigned long sysenter_esp;
1268 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1271 * Linux uses per-cpu TSS and GDT, so set these when switching
1272 * processors. See 22.2.4.
1274 vmcs_writel(HOST_TR_BASE,
1275 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1276 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1279 * VM exits change the host TR limit to 0x67 after a VM
1280 * exit. This is okay, since 0x67 covers everything except
1281 * the IO bitmap and have have code to handle the IO bitmap
1282 * being lost after a VM exit.
1284 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
1286 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1287 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1289 vmx->loaded_vmcs->cpu = cpu;
1292 /* Setup TSC multiplier */
1293 if (kvm_has_tsc_control &&
1294 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1295 decache_tsc_multiplier(vmx);
1297 vmx_vcpu_pi_load(vcpu, cpu);
1298 vmx->host_pkru = read_pkru();
1299 vmx->host_debugctlmsr = get_debugctlmsr();
1302 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1304 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1306 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1307 !irq_remapping_cap(IRQ_POSTING_CAP) ||
1308 !kvm_vcpu_apicv_active(vcpu))
1311 /* Set SN when the vCPU is preempted */
1312 if (vcpu->preempted)
1316 void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1318 vmx_vcpu_pi_put(vcpu);
1320 vmx_prepare_switch_to_host(to_vmx(vcpu));
1323 static bool emulation_required(struct kvm_vcpu *vcpu)
1325 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1328 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1330 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1332 unsigned long rflags, save_rflags;
1334 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1335 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1336 rflags = vmcs_readl(GUEST_RFLAGS);
1337 if (to_vmx(vcpu)->rmode.vm86_active) {
1338 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1339 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1340 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1342 to_vmx(vcpu)->rflags = rflags;
1344 return to_vmx(vcpu)->rflags;
1347 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1349 unsigned long old_rflags = vmx_get_rflags(vcpu);
1351 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1352 to_vmx(vcpu)->rflags = rflags;
1353 if (to_vmx(vcpu)->rmode.vm86_active) {
1354 to_vmx(vcpu)->rmode.save_rflags = rflags;
1355 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1357 vmcs_writel(GUEST_RFLAGS, rflags);
1359 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
1360 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
1363 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1365 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1368 if (interruptibility & GUEST_INTR_STATE_STI)
1369 ret |= KVM_X86_SHADOW_INT_STI;
1370 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1371 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1376 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1378 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1379 u32 interruptibility = interruptibility_old;
1381 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1383 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1384 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1385 else if (mask & KVM_X86_SHADOW_INT_STI)
1386 interruptibility |= GUEST_INTR_STATE_STI;
1388 if ((interruptibility != interruptibility_old))
1389 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1392 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1394 struct vcpu_vmx *vmx = to_vmx(vcpu);
1395 unsigned long value;
1398 * Any MSR write that attempts to change bits marked reserved will
1401 if (data & vmx->pt_desc.ctl_bitmask)
1405 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1406 * result in a #GP unless the same write also clears TraceEn.
1408 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1409 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1413 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1414 * and FabricEn would cause #GP, if
1415 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1417 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1418 !(data & RTIT_CTL_FABRIC_EN) &&
1419 !intel_pt_validate_cap(vmx->pt_desc.caps,
1420 PT_CAP_single_range_output))
1424 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1425 * utilize encodings marked reserved will casue a #GP fault.
1427 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1428 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1429 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1430 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1432 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1433 PT_CAP_cycle_thresholds);
1434 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1435 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1436 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1438 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1439 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1440 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1441 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1445 * If ADDRx_CFG is reserved or the encodings is >2 will
1446 * cause a #GP fault.
1448 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1449 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1451 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1452 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1454 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1455 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1457 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1458 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1465 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1469 rip = kvm_rip_read(vcpu);
1470 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1471 kvm_rip_write(vcpu, rip);
1473 /* skipping an emulated instruction also counts */
1474 vmx_set_interrupt_shadow(vcpu, 0);
1477 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1480 * Ensure that we clear the HLT state in the VMCS. We don't need to
1481 * explicitly skip the instruction because if the HLT state is set,
1482 * then the instruction is already executing and RIP has already been
1485 if (kvm_hlt_in_guest(vcpu->kvm) &&
1486 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1487 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1490 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1492 struct vcpu_vmx *vmx = to_vmx(vcpu);
1493 unsigned nr = vcpu->arch.exception.nr;
1494 bool has_error_code = vcpu->arch.exception.has_error_code;
1495 u32 error_code = vcpu->arch.exception.error_code;
1496 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1498 kvm_deliver_exception_payload(vcpu);
1500 if (has_error_code) {
1501 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1502 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1505 if (vmx->rmode.vm86_active) {
1507 if (kvm_exception_is_soft(nr))
1508 inc_eip = vcpu->arch.event_exit_inst_len;
1509 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1510 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1514 WARN_ON_ONCE(vmx->emulation_required);
1516 if (kvm_exception_is_soft(nr)) {
1517 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1518 vmx->vcpu.arch.event_exit_inst_len);
1519 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1521 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1523 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1525 vmx_clear_hlt(vcpu);
1528 static bool vmx_rdtscp_supported(void)
1530 return cpu_has_vmx_rdtscp();
1533 static bool vmx_invpcid_supported(void)
1535 return cpu_has_vmx_invpcid();
1539 * Swap MSR entry in host/guest MSR entry array.
1541 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1543 struct shared_msr_entry tmp;
1545 tmp = vmx->guest_msrs[to];
1546 vmx->guest_msrs[to] = vmx->guest_msrs[from];
1547 vmx->guest_msrs[from] = tmp;
1551 * Set up the vmcs to automatically save and restore system
1552 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1553 * mode, as fiddling with msrs is very expensive.
1555 static void setup_msrs(struct vcpu_vmx *vmx)
1557 int save_nmsrs, index;
1560 #ifdef CONFIG_X86_64
1562 * The SYSCALL MSRs are only needed on long mode guests, and only
1563 * when EFER.SCE is set.
1565 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1566 index = __find_msr_index(vmx, MSR_STAR);
1568 move_msr_up(vmx, index, save_nmsrs++);
1569 index = __find_msr_index(vmx, MSR_LSTAR);
1571 move_msr_up(vmx, index, save_nmsrs++);
1572 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1574 move_msr_up(vmx, index, save_nmsrs++);
1577 index = __find_msr_index(vmx, MSR_EFER);
1578 if (index >= 0 && update_transition_efer(vmx, index))
1579 move_msr_up(vmx, index, save_nmsrs++);
1580 index = __find_msr_index(vmx, MSR_TSC_AUX);
1581 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1582 move_msr_up(vmx, index, save_nmsrs++);
1584 vmx->save_nmsrs = save_nmsrs;
1585 vmx->guest_msrs_dirty = true;
1587 if (cpu_has_vmx_msr_bitmap())
1588 vmx_update_msr_bitmap(&vmx->vcpu);
1591 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1593 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1595 if (is_guest_mode(vcpu) &&
1596 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1597 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
1599 return vcpu->arch.tsc_offset;
1602 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1604 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1605 u64 g_tsc_offset = 0;
1608 * We're here if L1 chose not to trap WRMSR to TSC. According
1609 * to the spec, this should set L1's TSC; The offset that L1
1610 * set for L2 remains unchanged, and still needs to be added
1611 * to the newly set TSC to get L2's TSC.
1613 if (is_guest_mode(vcpu) &&
1614 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1615 g_tsc_offset = vmcs12->tsc_offset;
1617 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1618 vcpu->arch.tsc_offset - g_tsc_offset,
1620 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1621 return offset + g_tsc_offset;
1625 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1626 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1627 * all guests if the "nested" module option is off, and can also be disabled
1628 * for a single guest by disabling its VMX cpuid bit.
1630 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1632 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1635 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1638 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1640 return !(val & ~valid_bits);
1643 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1645 switch (msr->index) {
1646 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1649 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1658 * Reads an msr value (of 'msr_index') into 'pdata'.
1659 * Returns 0 on success, non-0 otherwise.
1660 * Assumes vcpu_load() was already called.
1662 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1664 struct vcpu_vmx *vmx = to_vmx(vcpu);
1665 struct shared_msr_entry *msr;
1668 switch (msr_info->index) {
1669 #ifdef CONFIG_X86_64
1671 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1674 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1676 case MSR_KERNEL_GS_BASE:
1677 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1681 return kvm_get_msr_common(vcpu, msr_info);
1682 case MSR_IA32_SPEC_CTRL:
1683 if (!msr_info->host_initiated &&
1684 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1687 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1689 case MSR_IA32_SYSENTER_CS:
1690 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1692 case MSR_IA32_SYSENTER_EIP:
1693 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1695 case MSR_IA32_SYSENTER_ESP:
1696 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1698 case MSR_IA32_POWER_CTL:
1699 msr_info->data = vmx->msr_ia32_power_ctl;
1701 case MSR_IA32_BNDCFGS:
1702 if (!kvm_mpx_supported() ||
1703 (!msr_info->host_initiated &&
1704 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1706 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1708 case MSR_IA32_MCG_EXT_CTL:
1709 if (!msr_info->host_initiated &&
1710 !(vmx->msr_ia32_feature_control &
1711 FEATURE_CONTROL_LMCE))
1713 msr_info->data = vcpu->arch.mcg_ext_ctl;
1715 case MSR_IA32_FEATURE_CONTROL:
1716 msr_info->data = vmx->msr_ia32_feature_control;
1718 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1719 if (!nested_vmx_allowed(vcpu))
1721 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1724 if (!vmx_xsaves_supported())
1726 msr_info->data = vcpu->arch.ia32_xss;
1728 case MSR_IA32_RTIT_CTL:
1729 if (pt_mode != PT_MODE_HOST_GUEST)
1731 msr_info->data = vmx->pt_desc.guest.ctl;
1733 case MSR_IA32_RTIT_STATUS:
1734 if (pt_mode != PT_MODE_HOST_GUEST)
1736 msr_info->data = vmx->pt_desc.guest.status;
1738 case MSR_IA32_RTIT_CR3_MATCH:
1739 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1740 !intel_pt_validate_cap(vmx->pt_desc.caps,
1741 PT_CAP_cr3_filtering))
1743 msr_info->data = vmx->pt_desc.guest.cr3_match;
1745 case MSR_IA32_RTIT_OUTPUT_BASE:
1746 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1747 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1748 PT_CAP_topa_output) &&
1749 !intel_pt_validate_cap(vmx->pt_desc.caps,
1750 PT_CAP_single_range_output)))
1752 msr_info->data = vmx->pt_desc.guest.output_base;
1754 case MSR_IA32_RTIT_OUTPUT_MASK:
1755 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1756 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1757 PT_CAP_topa_output) &&
1758 !intel_pt_validate_cap(vmx->pt_desc.caps,
1759 PT_CAP_single_range_output)))
1761 msr_info->data = vmx->pt_desc.guest.output_mask;
1763 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1764 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1765 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1766 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1767 PT_CAP_num_address_ranges)))
1770 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1772 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1775 if (!msr_info->host_initiated &&
1776 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1778 /* Else, falls through */
1780 msr = find_msr_entry(vmx, msr_info->index);
1782 msr_info->data = msr->data;
1785 return kvm_get_msr_common(vcpu, msr_info);
1792 * Writes msr value into into the appropriate "register".
1793 * Returns 0 on success, non-0 otherwise.
1794 * Assumes vcpu_load() was already called.
1796 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1798 struct vcpu_vmx *vmx = to_vmx(vcpu);
1799 struct shared_msr_entry *msr;
1801 u32 msr_index = msr_info->index;
1802 u64 data = msr_info->data;
1805 switch (msr_index) {
1807 ret = kvm_set_msr_common(vcpu, msr_info);
1809 #ifdef CONFIG_X86_64
1811 vmx_segment_cache_clear(vmx);
1812 vmcs_writel(GUEST_FS_BASE, data);
1815 vmx_segment_cache_clear(vmx);
1816 vmcs_writel(GUEST_GS_BASE, data);
1818 case MSR_KERNEL_GS_BASE:
1819 vmx_write_guest_kernel_gs_base(vmx, data);
1822 case MSR_IA32_SYSENTER_CS:
1823 vmcs_write32(GUEST_SYSENTER_CS, data);
1825 case MSR_IA32_SYSENTER_EIP:
1826 vmcs_writel(GUEST_SYSENTER_EIP, data);
1828 case MSR_IA32_SYSENTER_ESP:
1829 vmcs_writel(GUEST_SYSENTER_ESP, data);
1831 case MSR_IA32_POWER_CTL:
1832 vmx->msr_ia32_power_ctl = data;
1834 case MSR_IA32_BNDCFGS:
1835 if (!kvm_mpx_supported() ||
1836 (!msr_info->host_initiated &&
1837 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1839 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
1840 (data & MSR_IA32_BNDCFGS_RSVD))
1842 vmcs_write64(GUEST_BNDCFGS, data);
1844 case MSR_IA32_SPEC_CTRL:
1845 if (!msr_info->host_initiated &&
1846 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1849 /* The STIBP bit doesn't fault even if it's not advertised */
1850 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
1853 vmx->spec_ctrl = data;
1860 * When it's written (to non-zero) for the first time, pass
1864 * The handling of the MSR bitmap for L2 guests is done in
1865 * nested_vmx_merge_msr_bitmap. We should not touch the
1866 * vmcs02.msr_bitmap here since it gets completely overwritten
1867 * in the merging. We update the vmcs01 here for L1 as well
1868 * since it will end up touching the MSR anyway now.
1870 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
1874 case MSR_IA32_PRED_CMD:
1875 if (!msr_info->host_initiated &&
1876 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1879 if (data & ~PRED_CMD_IBPB)
1885 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
1889 * When it's written (to non-zero) for the first time, pass
1893 * The handling of the MSR bitmap for L2 guests is done in
1894 * nested_vmx_merge_msr_bitmap. We should not touch the
1895 * vmcs02.msr_bitmap here since it gets completely overwritten
1898 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
1901 case MSR_IA32_CR_PAT:
1902 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
1903 if (!kvm_pat_valid(data))
1905 vmcs_write64(GUEST_IA32_PAT, data);
1906 vcpu->arch.pat = data;
1909 ret = kvm_set_msr_common(vcpu, msr_info);
1911 case MSR_IA32_TSC_ADJUST:
1912 ret = kvm_set_msr_common(vcpu, msr_info);
1914 case MSR_IA32_MCG_EXT_CTL:
1915 if ((!msr_info->host_initiated &&
1916 !(to_vmx(vcpu)->msr_ia32_feature_control &
1917 FEATURE_CONTROL_LMCE)) ||
1918 (data & ~MCG_EXT_CTL_LMCE_EN))
1920 vcpu->arch.mcg_ext_ctl = data;
1922 case MSR_IA32_FEATURE_CONTROL:
1923 if (!vmx_feature_control_msr_valid(vcpu, data) ||
1924 (to_vmx(vcpu)->msr_ia32_feature_control &
1925 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
1927 vmx->msr_ia32_feature_control = data;
1928 if (msr_info->host_initiated && data == 0)
1929 vmx_leave_nested(vcpu);
1931 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1932 if (!msr_info->host_initiated)
1933 return 1; /* they are read-only */
1934 if (!nested_vmx_allowed(vcpu))
1936 return vmx_set_vmx_msr(vcpu, msr_index, data);
1938 if (!vmx_xsaves_supported())
1941 * The only supported bit as of Skylake is bit 8, but
1942 * it is not supported on KVM.
1946 vcpu->arch.ia32_xss = data;
1947 if (vcpu->arch.ia32_xss != host_xss)
1948 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
1949 vcpu->arch.ia32_xss, host_xss, false);
1951 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
1953 case MSR_IA32_RTIT_CTL:
1954 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1955 vmx_rtit_ctl_check(vcpu, data) ||
1958 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
1959 vmx->pt_desc.guest.ctl = data;
1960 pt_update_intercept_for_msr(vmx);
1962 case MSR_IA32_RTIT_STATUS:
1963 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1964 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1965 (data & MSR_IA32_RTIT_STATUS_MASK))
1967 vmx->pt_desc.guest.status = data;
1969 case MSR_IA32_RTIT_CR3_MATCH:
1970 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1971 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1972 !intel_pt_validate_cap(vmx->pt_desc.caps,
1973 PT_CAP_cr3_filtering))
1975 vmx->pt_desc.guest.cr3_match = data;
1977 case MSR_IA32_RTIT_OUTPUT_BASE:
1978 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1979 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1980 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1981 PT_CAP_topa_output) &&
1982 !intel_pt_validate_cap(vmx->pt_desc.caps,
1983 PT_CAP_single_range_output)) ||
1984 (data & MSR_IA32_RTIT_OUTPUT_BASE_MASK))
1986 vmx->pt_desc.guest.output_base = data;
1988 case MSR_IA32_RTIT_OUTPUT_MASK:
1989 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1990 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1991 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1992 PT_CAP_topa_output) &&
1993 !intel_pt_validate_cap(vmx->pt_desc.caps,
1994 PT_CAP_single_range_output)))
1996 vmx->pt_desc.guest.output_mask = data;
1998 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1999 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2000 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2001 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2002 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2003 PT_CAP_num_address_ranges)))
2006 vmx->pt_desc.guest.addr_b[index / 2] = data;
2008 vmx->pt_desc.guest.addr_a[index / 2] = data;
2011 if (!msr_info->host_initiated &&
2012 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2014 /* Check reserved bit, higher 32 bits should be zero */
2015 if ((data >> 32) != 0)
2017 /* Else, falls through */
2019 msr = find_msr_entry(vmx, msr_index);
2021 u64 old_msr_data = msr->data;
2023 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2025 ret = kvm_set_shared_msr(msr->index, msr->data,
2029 msr->data = old_msr_data;
2033 ret = kvm_set_msr_common(vcpu, msr_info);
2039 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2041 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2044 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2047 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2049 case VCPU_EXREG_PDPTR:
2051 ept_save_pdptrs(vcpu);
2058 static __init int cpu_has_kvm_support(void)
2060 return cpu_has_vmx();
2063 static __init int vmx_disabled_by_bios(void)
2067 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2068 if (msr & FEATURE_CONTROL_LOCKED) {
2069 /* launched w/ TXT and VMX disabled */
2070 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2073 /* launched w/o TXT and VMX only enabled w/ TXT */
2074 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2075 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2076 && !tboot_enabled()) {
2077 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2078 "activate TXT before enabling KVM\n");
2081 /* launched w/o TXT and VMX disabled */
2082 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2083 && !tboot_enabled())
2090 static void kvm_cpu_vmxon(u64 addr)
2092 cr4_set_bits(X86_CR4_VMXE);
2093 intel_pt_handle_vmx(1);
2095 asm volatile ("vmxon %0" : : "m"(addr));
2098 static int hardware_enable(void)
2100 int cpu = raw_smp_processor_id();
2101 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2104 if (cr4_read_shadow() & X86_CR4_VMXE)
2108 * This can happen if we hot-added a CPU but failed to allocate
2109 * VP assist page for it.
2111 if (static_branch_unlikely(&enable_evmcs) &&
2112 !hv_get_vp_assist_page(cpu))
2115 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2116 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
2117 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
2120 * Now we can enable the vmclear operation in kdump
2121 * since the loaded_vmcss_on_cpu list on this cpu
2122 * has been initialized.
2124 * Though the cpu is not in VMX operation now, there
2125 * is no problem to enable the vmclear operation
2126 * for the loaded_vmcss_on_cpu list is empty!
2128 crash_enable_local_vmclear(cpu);
2130 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2132 test_bits = FEATURE_CONTROL_LOCKED;
2133 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2134 if (tboot_enabled())
2135 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2137 if ((old & test_bits) != test_bits) {
2138 /* enable and lock */
2139 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2141 kvm_cpu_vmxon(phys_addr);
2148 static void vmclear_local_loaded_vmcss(void)
2150 int cpu = raw_smp_processor_id();
2151 struct loaded_vmcs *v, *n;
2153 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2154 loaded_vmcss_on_cpu_link)
2155 __loaded_vmcs_clear(v);
2159 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2162 static void kvm_cpu_vmxoff(void)
2164 asm volatile (__ex("vmxoff"));
2166 intel_pt_handle_vmx(0);
2167 cr4_clear_bits(X86_CR4_VMXE);
2170 static void hardware_disable(void)
2172 vmclear_local_loaded_vmcss();
2176 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2177 u32 msr, u32 *result)
2179 u32 vmx_msr_low, vmx_msr_high;
2180 u32 ctl = ctl_min | ctl_opt;
2182 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2184 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2185 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2187 /* Ensure minimum (required) set of control bits are supported. */
2195 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2196 struct vmx_capability *vmx_cap)
2198 u32 vmx_msr_low, vmx_msr_high;
2199 u32 min, opt, min2, opt2;
2200 u32 _pin_based_exec_control = 0;
2201 u32 _cpu_based_exec_control = 0;
2202 u32 _cpu_based_2nd_exec_control = 0;
2203 u32 _vmexit_control = 0;
2204 u32 _vmentry_control = 0;
2206 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2207 min = CPU_BASED_HLT_EXITING |
2208 #ifdef CONFIG_X86_64
2209 CPU_BASED_CR8_LOAD_EXITING |
2210 CPU_BASED_CR8_STORE_EXITING |
2212 CPU_BASED_CR3_LOAD_EXITING |
2213 CPU_BASED_CR3_STORE_EXITING |
2214 CPU_BASED_UNCOND_IO_EXITING |
2215 CPU_BASED_MOV_DR_EXITING |
2216 CPU_BASED_USE_TSC_OFFSETING |
2217 CPU_BASED_MWAIT_EXITING |
2218 CPU_BASED_MONITOR_EXITING |
2219 CPU_BASED_INVLPG_EXITING |
2220 CPU_BASED_RDPMC_EXITING;
2222 opt = CPU_BASED_TPR_SHADOW |
2223 CPU_BASED_USE_MSR_BITMAPS |
2224 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2225 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2226 &_cpu_based_exec_control) < 0)
2228 #ifdef CONFIG_X86_64
2229 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2230 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2231 ~CPU_BASED_CR8_STORE_EXITING;
2233 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2235 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2236 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2237 SECONDARY_EXEC_WBINVD_EXITING |
2238 SECONDARY_EXEC_ENABLE_VPID |
2239 SECONDARY_EXEC_ENABLE_EPT |
2240 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2241 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2242 SECONDARY_EXEC_DESC |
2243 SECONDARY_EXEC_RDTSCP |
2244 SECONDARY_EXEC_ENABLE_INVPCID |
2245 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2246 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2247 SECONDARY_EXEC_SHADOW_VMCS |
2248 SECONDARY_EXEC_XSAVES |
2249 SECONDARY_EXEC_RDSEED_EXITING |
2250 SECONDARY_EXEC_RDRAND_EXITING |
2251 SECONDARY_EXEC_ENABLE_PML |
2252 SECONDARY_EXEC_TSC_SCALING |
2253 SECONDARY_EXEC_PT_USE_GPA |
2254 SECONDARY_EXEC_PT_CONCEAL_VMX |
2255 SECONDARY_EXEC_ENABLE_VMFUNC |
2256 SECONDARY_EXEC_ENCLS_EXITING;
2257 if (adjust_vmx_controls(min2, opt2,
2258 MSR_IA32_VMX_PROCBASED_CTLS2,
2259 &_cpu_based_2nd_exec_control) < 0)
2262 #ifndef CONFIG_X86_64
2263 if (!(_cpu_based_2nd_exec_control &
2264 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2265 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2268 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2269 _cpu_based_2nd_exec_control &= ~(
2270 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2271 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2272 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2274 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2275 &vmx_cap->ept, &vmx_cap->vpid);
2277 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2278 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2280 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2281 CPU_BASED_CR3_STORE_EXITING |
2282 CPU_BASED_INVLPG_EXITING);
2283 } else if (vmx_cap->ept) {
2285 pr_warn_once("EPT CAP should not exist if not support "
2286 "1-setting enable EPT VM-execution control\n");
2288 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2291 pr_warn_once("VPID CAP should not exist if not support "
2292 "1-setting enable VPID VM-execution control\n");
2295 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2296 #ifdef CONFIG_X86_64
2297 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2299 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2300 VM_EXIT_LOAD_IA32_PAT |
2301 VM_EXIT_LOAD_IA32_EFER |
2302 VM_EXIT_CLEAR_BNDCFGS |
2303 VM_EXIT_PT_CONCEAL_PIP |
2304 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2305 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2306 &_vmexit_control) < 0)
2309 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2310 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2311 PIN_BASED_VMX_PREEMPTION_TIMER;
2312 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2313 &_pin_based_exec_control) < 0)
2316 if (cpu_has_broken_vmx_preemption_timer())
2317 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2318 if (!(_cpu_based_2nd_exec_control &
2319 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2320 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2322 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2323 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2324 VM_ENTRY_LOAD_IA32_PAT |
2325 VM_ENTRY_LOAD_IA32_EFER |
2326 VM_ENTRY_LOAD_BNDCFGS |
2327 VM_ENTRY_PT_CONCEAL_PIP |
2328 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2329 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2330 &_vmentry_control) < 0)
2334 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2335 * can't be used due to an errata where VM Exit may incorrectly clear
2336 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2337 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2339 if (boot_cpu_data.x86 == 0x6) {
2340 switch (boot_cpu_data.x86_model) {
2341 case 26: /* AAK155 */
2342 case 30: /* AAP115 */
2343 case 37: /* AAT100 */
2344 case 44: /* BC86,AAY89,BD102 */
2346 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2347 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2348 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2349 "does not work properly. Using workaround\n");
2357 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2359 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2360 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2363 #ifdef CONFIG_X86_64
2364 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2365 if (vmx_msr_high & (1u<<16))
2369 /* Require Write-Back (WB) memory type for VMCS accesses. */
2370 if (((vmx_msr_high >> 18) & 15) != 6)
2373 vmcs_conf->size = vmx_msr_high & 0x1fff;
2374 vmcs_conf->order = get_order(vmcs_conf->size);
2375 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2377 vmcs_conf->revision_id = vmx_msr_low;
2379 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2380 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2381 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2382 vmcs_conf->vmexit_ctrl = _vmexit_control;
2383 vmcs_conf->vmentry_ctrl = _vmentry_control;
2385 if (static_branch_unlikely(&enable_evmcs))
2386 evmcs_sanitize_exec_ctrls(vmcs_conf);
2391 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2393 int node = cpu_to_node(cpu);
2397 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2400 vmcs = page_address(pages);
2401 memset(vmcs, 0, vmcs_config.size);
2403 /* KVM supports Enlightened VMCS v1 only */
2404 if (static_branch_unlikely(&enable_evmcs))
2405 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2407 vmcs->hdr.revision_id = vmcs_config.revision_id;
2410 vmcs->hdr.shadow_vmcs = 1;
2414 void free_vmcs(struct vmcs *vmcs)
2416 free_pages((unsigned long)vmcs, vmcs_config.order);
2420 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2422 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2424 if (!loaded_vmcs->vmcs)
2426 loaded_vmcs_clear(loaded_vmcs);
2427 free_vmcs(loaded_vmcs->vmcs);
2428 loaded_vmcs->vmcs = NULL;
2429 if (loaded_vmcs->msr_bitmap)
2430 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2431 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2434 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2436 loaded_vmcs->vmcs = alloc_vmcs(false);
2437 if (!loaded_vmcs->vmcs)
2440 loaded_vmcs->shadow_vmcs = NULL;
2441 loaded_vmcs_init(loaded_vmcs);
2443 if (cpu_has_vmx_msr_bitmap()) {
2444 loaded_vmcs->msr_bitmap = (unsigned long *)
2445 __get_free_page(GFP_KERNEL_ACCOUNT);
2446 if (!loaded_vmcs->msr_bitmap)
2448 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2450 if (IS_ENABLED(CONFIG_HYPERV) &&
2451 static_branch_unlikely(&enable_evmcs) &&
2452 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2453 struct hv_enlightened_vmcs *evmcs =
2454 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2456 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2460 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2465 free_loaded_vmcs(loaded_vmcs);
2469 static void free_kvm_area(void)
2473 for_each_possible_cpu(cpu) {
2474 free_vmcs(per_cpu(vmxarea, cpu));
2475 per_cpu(vmxarea, cpu) = NULL;
2479 static __init int alloc_kvm_area(void)
2483 for_each_possible_cpu(cpu) {
2486 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2493 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2494 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2495 * revision_id reported by MSR_IA32_VMX_BASIC.
2497 * However, even though not explicitly documented by
2498 * TLFS, VMXArea passed as VMXON argument should
2499 * still be marked with revision_id reported by
2502 if (static_branch_unlikely(&enable_evmcs))
2503 vmcs->hdr.revision_id = vmcs_config.revision_id;
2505 per_cpu(vmxarea, cpu) = vmcs;
2510 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2511 struct kvm_segment *save)
2513 if (!emulate_invalid_guest_state) {
2515 * CS and SS RPL should be equal during guest entry according
2516 * to VMX spec, but in reality it is not always so. Since vcpu
2517 * is in the middle of the transition from real mode to
2518 * protected mode it is safe to assume that RPL 0 is a good
2521 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2522 save->selector &= ~SEGMENT_RPL_MASK;
2523 save->dpl = save->selector & SEGMENT_RPL_MASK;
2526 vmx_set_segment(vcpu, save, seg);
2529 static void enter_pmode(struct kvm_vcpu *vcpu)
2531 unsigned long flags;
2532 struct vcpu_vmx *vmx = to_vmx(vcpu);
2535 * Update real mode segment cache. It may be not up-to-date if sement
2536 * register was written while vcpu was in a guest mode.
2538 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2539 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2540 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2541 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2542 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2543 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2545 vmx->rmode.vm86_active = 0;
2547 vmx_segment_cache_clear(vmx);
2549 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2551 flags = vmcs_readl(GUEST_RFLAGS);
2552 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2553 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2554 vmcs_writel(GUEST_RFLAGS, flags);
2556 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2557 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2559 update_exception_bitmap(vcpu);
2561 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2562 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2563 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2564 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2565 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2566 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2569 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2571 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2572 struct kvm_segment var = *save;
2575 if (seg == VCPU_SREG_CS)
2578 if (!emulate_invalid_guest_state) {
2579 var.selector = var.base >> 4;
2580 var.base = var.base & 0xffff0;
2590 if (save->base & 0xf)
2591 printk_once(KERN_WARNING "kvm: segment base is not "
2592 "paragraph aligned when entering "
2593 "protected mode (seg=%d)", seg);
2596 vmcs_write16(sf->selector, var.selector);
2597 vmcs_writel(sf->base, var.base);
2598 vmcs_write32(sf->limit, var.limit);
2599 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2602 static void enter_rmode(struct kvm_vcpu *vcpu)
2604 unsigned long flags;
2605 struct vcpu_vmx *vmx = to_vmx(vcpu);
2606 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2608 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2609 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2610 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2611 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2612 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2613 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2614 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2616 vmx->rmode.vm86_active = 1;
2619 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2620 * vcpu. Warn the user that an update is overdue.
2622 if (!kvm_vmx->tss_addr)
2623 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2624 "called before entering vcpu\n");
2626 vmx_segment_cache_clear(vmx);
2628 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2629 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2630 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2632 flags = vmcs_readl(GUEST_RFLAGS);
2633 vmx->rmode.save_rflags = flags;
2635 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2637 vmcs_writel(GUEST_RFLAGS, flags);
2638 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2639 update_exception_bitmap(vcpu);
2641 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2642 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2643 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2644 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2645 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2646 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2648 kvm_mmu_reset_context(vcpu);
2651 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2653 struct vcpu_vmx *vmx = to_vmx(vcpu);
2654 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2659 vcpu->arch.efer = efer;
2660 if (efer & EFER_LMA) {
2661 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2664 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2666 msr->data = efer & ~EFER_LME;
2671 #ifdef CONFIG_X86_64
2673 static void enter_lmode(struct kvm_vcpu *vcpu)
2677 vmx_segment_cache_clear(to_vmx(vcpu));
2679 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2680 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2681 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2683 vmcs_write32(GUEST_TR_AR_BYTES,
2684 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2685 | VMX_AR_TYPE_BUSY_64_TSS);
2687 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2690 static void exit_lmode(struct kvm_vcpu *vcpu)
2692 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2693 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2698 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2700 int vpid = to_vmx(vcpu)->vpid;
2702 if (!vpid_sync_vcpu_addr(vpid, addr))
2703 vpid_sync_context(vpid);
2706 * If VPIDs are not supported or enabled, then the above is a no-op.
2707 * But we don't really need a TLB flush in that case anyway, because
2708 * each VM entry/exit includes an implicit flush when VPID is 0.
2712 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2714 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2716 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
2717 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
2720 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2722 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
2723 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2724 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2727 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2729 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2731 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2732 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2735 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2737 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2739 if (!test_bit(VCPU_EXREG_PDPTR,
2740 (unsigned long *)&vcpu->arch.regs_dirty))
2743 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2744 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2745 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2746 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2747 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2751 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2753 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2755 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2756 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2757 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2758 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2759 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2762 __set_bit(VCPU_EXREG_PDPTR,
2763 (unsigned long *)&vcpu->arch.regs_avail);
2764 __set_bit(VCPU_EXREG_PDPTR,
2765 (unsigned long *)&vcpu->arch.regs_dirty);
2768 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2770 struct kvm_vcpu *vcpu)
2772 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2773 vmx_decache_cr3(vcpu);
2774 if (!(cr0 & X86_CR0_PG)) {
2775 /* From paging/starting to nonpaging */
2776 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2777 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
2778 (CPU_BASED_CR3_LOAD_EXITING |
2779 CPU_BASED_CR3_STORE_EXITING));
2780 vcpu->arch.cr0 = cr0;
2781 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2782 } else if (!is_paging(vcpu)) {
2783 /* From nonpaging to paging */
2784 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2785 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
2786 ~(CPU_BASED_CR3_LOAD_EXITING |
2787 CPU_BASED_CR3_STORE_EXITING));
2788 vcpu->arch.cr0 = cr0;
2789 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2792 if (!(cr0 & X86_CR0_WP))
2793 *hw_cr0 &= ~X86_CR0_WP;
2796 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2798 struct vcpu_vmx *vmx = to_vmx(vcpu);
2799 unsigned long hw_cr0;
2801 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
2802 if (enable_unrestricted_guest)
2803 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
2805 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
2807 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
2810 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
2814 #ifdef CONFIG_X86_64
2815 if (vcpu->arch.efer & EFER_LME) {
2816 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
2818 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
2823 if (enable_ept && !enable_unrestricted_guest)
2824 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
2826 vmcs_writel(CR0_READ_SHADOW, cr0);
2827 vmcs_writel(GUEST_CR0, hw_cr0);
2828 vcpu->arch.cr0 = cr0;
2830 /* depends on vcpu->arch.cr0 to be set to a new value */
2831 vmx->emulation_required = emulation_required(vcpu);
2834 static int get_ept_level(struct kvm_vcpu *vcpu)
2836 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
2841 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
2843 u64 eptp = VMX_EPTP_MT_WB;
2845 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
2847 if (enable_ept_ad_bits &&
2848 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
2849 eptp |= VMX_EPTP_AD_ENABLE_BIT;
2850 eptp |= (root_hpa & PAGE_MASK);
2855 void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
2857 struct kvm *kvm = vcpu->kvm;
2858 unsigned long guest_cr3;
2863 eptp = construct_eptp(vcpu, cr3);
2864 vmcs_write64(EPT_POINTER, eptp);
2866 if (kvm_x86_ops->tlb_remote_flush) {
2867 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2868 to_vmx(vcpu)->ept_pointer = eptp;
2869 to_kvm_vmx(kvm)->ept_pointers_match
2870 = EPT_POINTERS_CHECK;
2871 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2874 if (enable_unrestricted_guest || is_paging(vcpu) ||
2875 is_guest_mode(vcpu))
2876 guest_cr3 = kvm_read_cr3(vcpu);
2878 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
2879 ept_load_pdptrs(vcpu);
2882 vmcs_writel(GUEST_CR3, guest_cr3);
2885 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2888 * Pass through host's Machine Check Enable value to hw_cr4, which
2889 * is in force while we are in guest mode. Do not let guests control
2890 * this bit, even if host CR4.MCE == 0.
2892 unsigned long hw_cr4;
2894 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
2895 if (enable_unrestricted_guest)
2896 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
2897 else if (to_vmx(vcpu)->rmode.vm86_active)
2898 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
2900 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
2902 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
2903 if (cr4 & X86_CR4_UMIP) {
2904 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
2905 SECONDARY_EXEC_DESC);
2906 hw_cr4 &= ~X86_CR4_UMIP;
2907 } else if (!is_guest_mode(vcpu) ||
2908 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
2909 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
2910 SECONDARY_EXEC_DESC);
2913 if (cr4 & X86_CR4_VMXE) {
2915 * To use VMXON (and later other VMX instructions), a guest
2916 * must first be able to turn on cr4.VMXE (see handle_vmon()).
2917 * So basically the check on whether to allow nested VMX
2918 * is here. We operate under the default treatment of SMM,
2919 * so VMX cannot be enabled under SMM.
2921 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
2925 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
2928 vcpu->arch.cr4 = cr4;
2930 if (!enable_unrestricted_guest) {
2932 if (!is_paging(vcpu)) {
2933 hw_cr4 &= ~X86_CR4_PAE;
2934 hw_cr4 |= X86_CR4_PSE;
2935 } else if (!(cr4 & X86_CR4_PAE)) {
2936 hw_cr4 &= ~X86_CR4_PAE;
2941 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
2942 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
2943 * to be manually disabled when guest switches to non-paging
2946 * If !enable_unrestricted_guest, the CPU is always running
2947 * with CR0.PG=1 and CR4 needs to be modified.
2948 * If enable_unrestricted_guest, the CPU automatically
2949 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
2951 if (!is_paging(vcpu))
2952 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
2955 vmcs_writel(CR4_READ_SHADOW, cr4);
2956 vmcs_writel(GUEST_CR4, hw_cr4);
2960 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
2962 struct vcpu_vmx *vmx = to_vmx(vcpu);
2965 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
2966 *var = vmx->rmode.segs[seg];
2967 if (seg == VCPU_SREG_TR
2968 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
2970 var->base = vmx_read_guest_seg_base(vmx, seg);
2971 var->selector = vmx_read_guest_seg_selector(vmx, seg);
2974 var->base = vmx_read_guest_seg_base(vmx, seg);
2975 var->limit = vmx_read_guest_seg_limit(vmx, seg);
2976 var->selector = vmx_read_guest_seg_selector(vmx, seg);
2977 ar = vmx_read_guest_seg_ar(vmx, seg);
2978 var->unusable = (ar >> 16) & 1;
2979 var->type = ar & 15;
2980 var->s = (ar >> 4) & 1;
2981 var->dpl = (ar >> 5) & 3;
2983 * Some userspaces do not preserve unusable property. Since usable
2984 * segment has to be present according to VMX spec we can use present
2985 * property to amend userspace bug by making unusable segment always
2986 * nonpresent. vmx_segment_access_rights() already marks nonpresent
2987 * segment as unusable.
2989 var->present = !var->unusable;
2990 var->avl = (ar >> 12) & 1;
2991 var->l = (ar >> 13) & 1;
2992 var->db = (ar >> 14) & 1;
2993 var->g = (ar >> 15) & 1;
2996 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2998 struct kvm_segment s;
3000 if (to_vmx(vcpu)->rmode.vm86_active) {
3001 vmx_get_segment(vcpu, &s, seg);
3004 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3007 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3009 struct vcpu_vmx *vmx = to_vmx(vcpu);
3011 if (unlikely(vmx->rmode.vm86_active))
3014 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3015 return VMX_AR_DPL(ar);
3019 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3023 if (var->unusable || !var->present)
3026 ar = var->type & 15;
3027 ar |= (var->s & 1) << 4;
3028 ar |= (var->dpl & 3) << 5;
3029 ar |= (var->present & 1) << 7;
3030 ar |= (var->avl & 1) << 12;
3031 ar |= (var->l & 1) << 13;
3032 ar |= (var->db & 1) << 14;
3033 ar |= (var->g & 1) << 15;
3039 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3041 struct vcpu_vmx *vmx = to_vmx(vcpu);
3042 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3044 vmx_segment_cache_clear(vmx);
3046 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3047 vmx->rmode.segs[seg] = *var;
3048 if (seg == VCPU_SREG_TR)
3049 vmcs_write16(sf->selector, var->selector);
3051 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3055 vmcs_writel(sf->base, var->base);
3056 vmcs_write32(sf->limit, var->limit);
3057 vmcs_write16(sf->selector, var->selector);
3060 * Fix the "Accessed" bit in AR field of segment registers for older
3062 * IA32 arch specifies that at the time of processor reset the
3063 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3064 * is setting it to 0 in the userland code. This causes invalid guest
3065 * state vmexit when "unrestricted guest" mode is turned on.
3066 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3067 * tree. Newer qemu binaries with that qemu fix would not need this
3070 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3071 var->type |= 0x1; /* Accessed */
3073 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3076 vmx->emulation_required = emulation_required(vcpu);
3079 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3081 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3083 *db = (ar >> 14) & 1;
3084 *l = (ar >> 13) & 1;
3087 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3089 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3090 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3093 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3095 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3096 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3099 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3101 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3102 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3105 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3107 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3108 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3111 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3113 struct kvm_segment var;
3116 vmx_get_segment(vcpu, &var, seg);
3118 if (seg == VCPU_SREG_CS)
3120 ar = vmx_segment_access_rights(&var);
3122 if (var.base != (var.selector << 4))
3124 if (var.limit != 0xffff)
3132 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3134 struct kvm_segment cs;
3135 unsigned int cs_rpl;
3137 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3138 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3142 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3146 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3147 if (cs.dpl > cs_rpl)
3150 if (cs.dpl != cs_rpl)
3156 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3160 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3162 struct kvm_segment ss;
3163 unsigned int ss_rpl;
3165 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3166 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3170 if (ss.type != 3 && ss.type != 7)
3174 if (ss.dpl != ss_rpl) /* DPL != RPL */
3182 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3184 struct kvm_segment var;
3187 vmx_get_segment(vcpu, &var, seg);
3188 rpl = var.selector & SEGMENT_RPL_MASK;
3196 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3197 if (var.dpl < rpl) /* DPL < RPL */
3201 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3207 static bool tr_valid(struct kvm_vcpu *vcpu)
3209 struct kvm_segment tr;
3211 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3215 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3217 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3225 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3227 struct kvm_segment ldtr;
3229 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3233 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3243 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3245 struct kvm_segment cs, ss;
3247 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3248 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3250 return ((cs.selector & SEGMENT_RPL_MASK) ==
3251 (ss.selector & SEGMENT_RPL_MASK));
3255 * Check if guest state is valid. Returns true if valid, false if
3257 * We assume that registers are always usable
3259 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3261 if (enable_unrestricted_guest)
3264 /* real mode guest state checks */
3265 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3266 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3268 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3270 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3272 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3274 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3276 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3279 /* protected mode guest state checks */
3280 if (!cs_ss_rpl_check(vcpu))
3282 if (!code_segment_valid(vcpu))
3284 if (!stack_segment_valid(vcpu))
3286 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3288 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3290 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3292 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3294 if (!tr_valid(vcpu))
3296 if (!ldtr_valid(vcpu))
3300 * - Add checks on RIP
3301 * - Add checks on RFLAGS
3307 static int init_rmode_tss(struct kvm *kvm)
3313 idx = srcu_read_lock(&kvm->srcu);
3314 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3315 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3318 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3319 r = kvm_write_guest_page(kvm, fn++, &data,
3320 TSS_IOPB_BASE_OFFSET, sizeof(u16));
3323 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3326 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3330 r = kvm_write_guest_page(kvm, fn, &data,
3331 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3334 srcu_read_unlock(&kvm->srcu, idx);
3338 static int init_rmode_identity_map(struct kvm *kvm)
3340 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3342 kvm_pfn_t identity_map_pfn;
3345 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3346 mutex_lock(&kvm->slots_lock);
3348 if (likely(kvm_vmx->ept_identity_pagetable_done))
3351 if (!kvm_vmx->ept_identity_map_addr)
3352 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3353 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3355 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3356 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3360 idx = srcu_read_lock(&kvm->srcu);
3361 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3364 /* Set up identity-mapping pagetable for EPT in real mode */
3365 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3366 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3367 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3368 r = kvm_write_guest_page(kvm, identity_map_pfn,
3369 &tmp, i * sizeof(tmp), sizeof(tmp));
3373 kvm_vmx->ept_identity_pagetable_done = true;
3376 srcu_read_unlock(&kvm->srcu, idx);
3379 mutex_unlock(&kvm->slots_lock);
3383 static void seg_setup(int seg)
3385 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3388 vmcs_write16(sf->selector, 0);
3389 vmcs_writel(sf->base, 0);
3390 vmcs_write32(sf->limit, 0xffff);
3392 if (seg == VCPU_SREG_CS)
3393 ar |= 0x08; /* code segment */
3395 vmcs_write32(sf->ar_bytes, ar);
3398 static int alloc_apic_access_page(struct kvm *kvm)
3403 mutex_lock(&kvm->slots_lock);
3404 if (kvm->arch.apic_access_page_done)
3406 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3407 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3411 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3412 if (is_error_page(page)) {
3418 * Do not pin the page in memory, so that memory hot-unplug
3419 * is able to migrate it.
3422 kvm->arch.apic_access_page_done = true;
3424 mutex_unlock(&kvm->slots_lock);
3428 int allocate_vpid(void)
3434 spin_lock(&vmx_vpid_lock);
3435 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3436 if (vpid < VMX_NR_VPIDS)
3437 __set_bit(vpid, vmx_vpid_bitmap);
3440 spin_unlock(&vmx_vpid_lock);
3444 void free_vpid(int vpid)
3446 if (!enable_vpid || vpid == 0)
3448 spin_lock(&vmx_vpid_lock);
3449 __clear_bit(vpid, vmx_vpid_bitmap);
3450 spin_unlock(&vmx_vpid_lock);
3453 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3456 int f = sizeof(unsigned long);
3458 if (!cpu_has_vmx_msr_bitmap())
3461 if (static_branch_unlikely(&enable_evmcs))
3462 evmcs_touch_msr_bitmap();
3465 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3466 * have the write-low and read-high bitmap offsets the wrong way round.
3467 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3469 if (msr <= 0x1fff) {
3470 if (type & MSR_TYPE_R)
3472 __clear_bit(msr, msr_bitmap + 0x000 / f);
3474 if (type & MSR_TYPE_W)
3476 __clear_bit(msr, msr_bitmap + 0x800 / f);
3478 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3480 if (type & MSR_TYPE_R)
3482 __clear_bit(msr, msr_bitmap + 0x400 / f);
3484 if (type & MSR_TYPE_W)
3486 __clear_bit(msr, msr_bitmap + 0xc00 / f);
3491 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3494 int f = sizeof(unsigned long);
3496 if (!cpu_has_vmx_msr_bitmap())
3499 if (static_branch_unlikely(&enable_evmcs))
3500 evmcs_touch_msr_bitmap();
3503 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3504 * have the write-low and read-high bitmap offsets the wrong way round.
3505 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3507 if (msr <= 0x1fff) {
3508 if (type & MSR_TYPE_R)
3510 __set_bit(msr, msr_bitmap + 0x000 / f);
3512 if (type & MSR_TYPE_W)
3514 __set_bit(msr, msr_bitmap + 0x800 / f);
3516 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3518 if (type & MSR_TYPE_R)
3520 __set_bit(msr, msr_bitmap + 0x400 / f);
3522 if (type & MSR_TYPE_W)
3524 __set_bit(msr, msr_bitmap + 0xc00 / f);
3529 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3530 u32 msr, int type, bool value)
3533 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3535 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3538 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3542 if (cpu_has_secondary_exec_ctrls() &&
3543 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
3544 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3545 mode |= MSR_BITMAP_MODE_X2APIC;
3546 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3547 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3553 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3558 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3559 unsigned word = msr / BITS_PER_LONG;
3560 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3561 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3564 if (mode & MSR_BITMAP_MODE_X2APIC) {
3566 * TPR reads and writes can be virtualized even if virtual interrupt
3567 * delivery is not in use.
3569 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3570 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3571 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3572 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3573 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3578 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3580 struct vcpu_vmx *vmx = to_vmx(vcpu);
3581 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3582 u8 mode = vmx_msr_bitmap_mode(vcpu);
3583 u8 changed = mode ^ vmx->msr_bitmap_mode;
3588 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3589 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3591 vmx->msr_bitmap_mode = mode;
3594 void pt_update_intercept_for_msr(struct vcpu_vmx *vmx)
3596 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3597 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3600 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_STATUS,
3602 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_BASE,
3604 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_MASK,
3606 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_CR3_MATCH,
3608 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3609 vmx_set_intercept_for_msr(msr_bitmap,
3610 MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3611 vmx_set_intercept_for_msr(msr_bitmap,
3612 MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3616 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
3618 return enable_apicv;
3621 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3623 struct vcpu_vmx *vmx = to_vmx(vcpu);
3628 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3629 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3630 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3633 rvi = vmx_get_rvi();
3635 vapic_page = vmx->nested.virtual_apic_map.hva;
3636 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3638 return ((rvi & 0xf0) > (vppr & 0xf0));
3641 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3645 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3647 if (vcpu->mode == IN_GUEST_MODE) {
3649 * The vector of interrupt to be delivered to vcpu had
3650 * been set in PIR before this function.
3652 * Following cases will be reached in this block, and
3653 * we always send a notification event in all cases as
3656 * Case 1: vcpu keeps in non-root mode. Sending a
3657 * notification event posts the interrupt to vcpu.
3659 * Case 2: vcpu exits to root mode and is still
3660 * runnable. PIR will be synced to vIRR before the
3661 * next vcpu entry. Sending a notification event in
3662 * this case has no effect, as vcpu is not in root
3665 * Case 3: vcpu exits to root mode and is blocked.
3666 * vcpu_block() has already synced PIR to vIRR and
3667 * never blocks vcpu if vIRR is not cleared. Therefore,
3668 * a blocked vcpu here does not wait for any requested
3669 * interrupts in PIR, and sending a notification event
3670 * which has no effect is safe here.
3673 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3680 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3683 struct vcpu_vmx *vmx = to_vmx(vcpu);
3685 if (is_guest_mode(vcpu) &&
3686 vector == vmx->nested.posted_intr_nv) {
3688 * If a posted intr is not recognized by hardware,
3689 * we will accomplish it in the next vmentry.
3691 vmx->nested.pi_pending = true;
3692 kvm_make_request(KVM_REQ_EVENT, vcpu);
3693 /* the PIR and ON have been set by L1. */
3694 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3695 kvm_vcpu_kick(vcpu);
3701 * Send interrupt to vcpu via posted interrupt way.
3702 * 1. If target vcpu is running(non-root mode), send posted interrupt
3703 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3704 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3705 * interrupt from PIR in next vmentry.
3707 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3709 struct vcpu_vmx *vmx = to_vmx(vcpu);
3712 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3716 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3719 /* If a previous notification has sent the IPI, nothing to do. */
3720 if (pi_test_and_set_on(&vmx->pi_desc))
3723 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3724 kvm_vcpu_kick(vcpu);
3728 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3729 * will not change in the lifetime of the guest.
3730 * Note that host-state that does change is set elsewhere. E.g., host-state
3731 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3733 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3738 unsigned long cr0, cr3, cr4;
3741 WARN_ON(cr0 & X86_CR0_TS);
3742 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
3745 * Save the most likely value for this task's CR3 in the VMCS.
3746 * We can't use __get_current_cr3_fast() because we're not atomic.
3749 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
3750 vmx->loaded_vmcs->host_state.cr3 = cr3;
3752 /* Save the most likely value for this task's CR4 in the VMCS. */
3753 cr4 = cr4_read_shadow();
3754 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
3755 vmx->loaded_vmcs->host_state.cr4 = cr4;
3757 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
3758 #ifdef CONFIG_X86_64
3760 * Load null selectors, so we can avoid reloading them in
3761 * vmx_prepare_switch_to_host(), in case userspace uses
3762 * the null selectors too (the expected case).
3764 vmcs_write16(HOST_DS_SELECTOR, 0);
3765 vmcs_write16(HOST_ES_SELECTOR, 0);
3767 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3768 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3770 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3771 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
3774 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
3775 vmx->host_idt_base = dt.address;
3777 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
3779 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3780 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3781 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
3782 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
3784 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
3785 rdmsr(MSR_IA32_CR_PAT, low32, high32);
3786 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
3789 if (cpu_has_load_ia32_efer())
3790 vmcs_write64(HOST_IA32_EFER, host_efer);
3793 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
3795 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
3797 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
3798 if (is_guest_mode(&vmx->vcpu))
3799 vmx->vcpu.arch.cr4_guest_owned_bits &=
3800 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
3801 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
3804 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
3806 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
3808 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
3809 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
3812 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
3814 /* Enable the preemption timer dynamically */
3815 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3816 return pin_based_exec_ctrl;
3819 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
3821 struct vcpu_vmx *vmx = to_vmx(vcpu);
3823 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
3824 if (cpu_has_secondary_exec_ctrls()) {
3825 if (kvm_vcpu_apicv_active(vcpu))
3826 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
3827 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3828 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3830 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
3831 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3832 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3835 if (cpu_has_vmx_msr_bitmap())
3836 vmx_update_msr_bitmap(vcpu);
3839 u32 vmx_exec_control(struct vcpu_vmx *vmx)
3841 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
3843 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
3844 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
3846 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
3847 exec_control &= ~CPU_BASED_TPR_SHADOW;
3848 #ifdef CONFIG_X86_64
3849 exec_control |= CPU_BASED_CR8_STORE_EXITING |
3850 CPU_BASED_CR8_LOAD_EXITING;
3854 exec_control |= CPU_BASED_CR3_STORE_EXITING |
3855 CPU_BASED_CR3_LOAD_EXITING |
3856 CPU_BASED_INVLPG_EXITING;
3857 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
3858 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
3859 CPU_BASED_MONITOR_EXITING);
3860 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
3861 exec_control &= ~CPU_BASED_HLT_EXITING;
3862 return exec_control;
3866 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
3868 struct kvm_vcpu *vcpu = &vmx->vcpu;
3870 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
3872 if (pt_mode == PT_MODE_SYSTEM)
3873 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
3874 if (!cpu_need_virtualize_apic_accesses(vcpu))
3875 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3877 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
3879 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
3880 enable_unrestricted_guest = 0;
3882 if (!enable_unrestricted_guest)
3883 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
3884 if (kvm_pause_in_guest(vmx->vcpu.kvm))
3885 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
3886 if (!kvm_vcpu_apicv_active(vcpu))
3887 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
3888 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3889 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
3891 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
3892 * in vmx_set_cr4. */
3893 exec_control &= ~SECONDARY_EXEC_DESC;
3895 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
3897 We can NOT enable shadow_vmcs here because we don't have yet
3900 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
3903 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
3905 if (vmx_xsaves_supported()) {
3906 /* Exposing XSAVES only when XSAVE is exposed */
3907 bool xsaves_enabled =
3908 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
3909 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
3911 if (!xsaves_enabled)
3912 exec_control &= ~SECONDARY_EXEC_XSAVES;
3916 vmx->nested.msrs.secondary_ctls_high |=
3917 SECONDARY_EXEC_XSAVES;
3919 vmx->nested.msrs.secondary_ctls_high &=
3920 ~SECONDARY_EXEC_XSAVES;
3924 if (vmx_rdtscp_supported()) {
3925 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
3926 if (!rdtscp_enabled)
3927 exec_control &= ~SECONDARY_EXEC_RDTSCP;
3931 vmx->nested.msrs.secondary_ctls_high |=
3932 SECONDARY_EXEC_RDTSCP;
3934 vmx->nested.msrs.secondary_ctls_high &=
3935 ~SECONDARY_EXEC_RDTSCP;
3939 if (vmx_invpcid_supported()) {
3940 /* Exposing INVPCID only when PCID is exposed */
3941 bool invpcid_enabled =
3942 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
3943 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
3945 if (!invpcid_enabled) {
3946 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
3947 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
3951 if (invpcid_enabled)
3952 vmx->nested.msrs.secondary_ctls_high |=
3953 SECONDARY_EXEC_ENABLE_INVPCID;
3955 vmx->nested.msrs.secondary_ctls_high &=
3956 ~SECONDARY_EXEC_ENABLE_INVPCID;
3960 if (vmx_rdrand_supported()) {
3961 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
3963 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
3967 vmx->nested.msrs.secondary_ctls_high |=
3968 SECONDARY_EXEC_RDRAND_EXITING;
3970 vmx->nested.msrs.secondary_ctls_high &=
3971 ~SECONDARY_EXEC_RDRAND_EXITING;
3975 if (vmx_rdseed_supported()) {
3976 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
3978 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
3982 vmx->nested.msrs.secondary_ctls_high |=
3983 SECONDARY_EXEC_RDSEED_EXITING;
3985 vmx->nested.msrs.secondary_ctls_high &=
3986 ~SECONDARY_EXEC_RDSEED_EXITING;
3990 vmx->secondary_exec_control = exec_control;
3993 static void ept_set_mmio_spte_mask(void)
3996 * EPT Misconfigurations can be generated if the value of bits 2:0
3997 * of an EPT paging-structure entry is 110b (write/execute).
3999 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
4000 VMX_EPT_MISCONFIG_WX_VALUE);
4003 #define VMX_XSS_EXIT_BITMAP 0
4006 * Sets up the vmcs for emulated real mode.
4008 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
4013 nested_vmx_vcpu_setup();
4015 if (cpu_has_vmx_msr_bitmap())
4016 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4018 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4021 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
4022 vmx->hv_deadline_tsc = -1;
4024 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
4026 if (cpu_has_secondary_exec_ctrls()) {
4027 vmx_compute_secondary_exec_control(vmx);
4028 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4029 vmx->secondary_exec_control);
4032 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4033 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4034 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4035 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4036 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4038 vmcs_write16(GUEST_INTR_STATUS, 0);
4040 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4041 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4044 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4045 vmcs_write32(PLE_GAP, ple_gap);
4046 vmx->ple_window = ple_window;
4047 vmx->ple_window_dirty = true;
4050 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4051 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4052 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4054 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4055 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4056 vmx_set_constant_host_state(vmx);
4057 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4058 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4060 if (cpu_has_vmx_vmfunc())
4061 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4063 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4064 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4065 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4066 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4067 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4069 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4070 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4072 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
4073 u32 index = vmx_msr_index[i];
4074 u32 data_low, data_high;
4077 if (rdmsr_safe(index, &data_low, &data_high) < 0)
4079 if (wrmsr_safe(index, data_low, data_high) < 0)
4081 vmx->guest_msrs[j].index = i;
4082 vmx->guest_msrs[j].data = 0;
4083 vmx->guest_msrs[j].mask = -1ull;
4087 vm_exit_controls_init(vmx, vmx_vmexit_ctrl());
4089 /* 22.2.1, 20.8.1 */
4090 vm_entry_controls_init(vmx, vmx_vmentry_ctrl());
4092 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
4093 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
4095 set_cr4_guest_host_mask(vmx);
4097 if (vmx_xsaves_supported())
4098 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4101 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4102 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4105 if (cpu_has_vmx_encls_vmexit())
4106 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
4108 if (pt_mode == PT_MODE_HOST_GUEST) {
4109 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4110 /* Bit[6~0] are forced to 1, writes are ignored. */
4111 vmx->pt_desc.guest.output_mask = 0x7F;
4112 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4116 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4118 struct vcpu_vmx *vmx = to_vmx(vcpu);
4119 struct msr_data apic_base_msr;
4122 vmx->rmode.vm86_active = 0;
4125 vcpu->arch.microcode_version = 0x100000000ULL;
4126 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4127 kvm_set_cr8(vcpu, 0);
4130 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4131 MSR_IA32_APICBASE_ENABLE;
4132 if (kvm_vcpu_is_reset_bsp(vcpu))
4133 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4134 apic_base_msr.host_initiated = true;
4135 kvm_set_apic_base(vcpu, &apic_base_msr);
4138 vmx_segment_cache_clear(vmx);
4140 seg_setup(VCPU_SREG_CS);
4141 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4142 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4144 seg_setup(VCPU_SREG_DS);
4145 seg_setup(VCPU_SREG_ES);
4146 seg_setup(VCPU_SREG_FS);
4147 seg_setup(VCPU_SREG_GS);
4148 seg_setup(VCPU_SREG_SS);
4150 vmcs_write16(GUEST_TR_SELECTOR, 0);
4151 vmcs_writel(GUEST_TR_BASE, 0);
4152 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4153 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4155 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4156 vmcs_writel(GUEST_LDTR_BASE, 0);
4157 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4158 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4161 vmcs_write32(GUEST_SYSENTER_CS, 0);
4162 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4163 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4164 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4167 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4168 kvm_rip_write(vcpu, 0xfff0);
4170 vmcs_writel(GUEST_GDTR_BASE, 0);
4171 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4173 vmcs_writel(GUEST_IDTR_BASE, 0);
4174 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4176 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4177 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4178 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4179 if (kvm_mpx_supported())
4180 vmcs_write64(GUEST_BNDCFGS, 0);
4184 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4186 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4187 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4188 if (cpu_need_tpr_shadow(vcpu))
4189 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4190 __pa(vcpu->arch.apic->regs));
4191 vmcs_write32(TPR_THRESHOLD, 0);
4194 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4197 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4199 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4200 vmx->vcpu.arch.cr0 = cr0;
4201 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4202 vmx_set_cr4(vcpu, 0);
4203 vmx_set_efer(vcpu, 0);
4205 update_exception_bitmap(vcpu);
4207 vpid_sync_context(vmx->vpid);
4209 vmx_clear_hlt(vcpu);
4212 static void enable_irq_window(struct kvm_vcpu *vcpu)
4214 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
4215 CPU_BASED_VIRTUAL_INTR_PENDING);
4218 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4221 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4222 enable_irq_window(vcpu);
4226 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
4227 CPU_BASED_VIRTUAL_NMI_PENDING);
4230 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4232 struct vcpu_vmx *vmx = to_vmx(vcpu);
4234 int irq = vcpu->arch.interrupt.nr;
4236 trace_kvm_inj_virq(irq);
4238 ++vcpu->stat.irq_injections;
4239 if (vmx->rmode.vm86_active) {
4241 if (vcpu->arch.interrupt.soft)
4242 inc_eip = vcpu->arch.event_exit_inst_len;
4243 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
4244 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4247 intr = irq | INTR_INFO_VALID_MASK;
4248 if (vcpu->arch.interrupt.soft) {
4249 intr |= INTR_TYPE_SOFT_INTR;
4250 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4251 vmx->vcpu.arch.event_exit_inst_len);
4253 intr |= INTR_TYPE_EXT_INTR;
4254 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4256 vmx_clear_hlt(vcpu);
4259 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4261 struct vcpu_vmx *vmx = to_vmx(vcpu);
4265 * Tracking the NMI-blocked state in software is built upon
4266 * finding the next open IRQ window. This, in turn, depends on
4267 * well-behaving guests: They have to keep IRQs disabled at
4268 * least as long as the NMI handler runs. Otherwise we may
4269 * cause NMI nesting, maybe breaking the guest. But as this is
4270 * highly unlikely, we can live with the residual risk.
4272 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4273 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4276 ++vcpu->stat.nmi_injections;
4277 vmx->loaded_vmcs->nmi_known_unmasked = false;
4279 if (vmx->rmode.vm86_active) {
4280 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
4281 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4285 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4286 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4288 vmx_clear_hlt(vcpu);
4291 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4293 struct vcpu_vmx *vmx = to_vmx(vcpu);
4297 return vmx->loaded_vmcs->soft_vnmi_blocked;
4298 if (vmx->loaded_vmcs->nmi_known_unmasked)
4300 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4301 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4305 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4307 struct vcpu_vmx *vmx = to_vmx(vcpu);
4310 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4311 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4312 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4315 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4317 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4318 GUEST_INTR_STATE_NMI);
4320 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4321 GUEST_INTR_STATE_NMI);
4325 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4327 if (to_vmx(vcpu)->nested.nested_run_pending)
4331 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4334 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4335 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4336 | GUEST_INTR_STATE_NMI));
4339 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4341 return (!to_vmx(vcpu)->nested.nested_run_pending &&
4342 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4343 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4344 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4347 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4351 if (enable_unrestricted_guest)
4354 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4358 to_kvm_vmx(kvm)->tss_addr = addr;
4359 return init_rmode_tss(kvm);
4362 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4364 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4368 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4373 * Update instruction length as we may reinject the exception
4374 * from user space while in guest debugging mode.
4376 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4377 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4378 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4382 if (vcpu->guest_debug &
4383 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4400 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4401 int vec, u32 err_code)
4404 * Instruction with address size override prefix opcode 0x67
4405 * Cause the #SS fault with 0 error code in VM86 mode.
4407 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4408 if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
4409 if (vcpu->arch.halt_request) {
4410 vcpu->arch.halt_request = 0;
4411 return kvm_vcpu_halt(vcpu);
4419 * Forward all other exceptions that are valid in real mode.
4420 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4421 * the required debugging infrastructure rework.
4423 kvm_queue_exception(vcpu, vec);
4428 * Trigger machine check on the host. We assume all the MSRs are already set up
4429 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4430 * We pass a fake environment to the machine check handler because we want
4431 * the guest to be always treated like user space, no matter what context
4432 * it used internally.
4434 static void kvm_machine_check(void)
4436 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4437 struct pt_regs regs = {
4438 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4439 .flags = X86_EFLAGS_IF,
4442 do_machine_check(®s, 0);
4446 static int handle_machine_check(struct kvm_vcpu *vcpu)
4448 /* already handled by vcpu_run */
4452 static int handle_exception(struct kvm_vcpu *vcpu)
4454 struct vcpu_vmx *vmx = to_vmx(vcpu);
4455 struct kvm_run *kvm_run = vcpu->run;
4456 u32 intr_info, ex_no, error_code;
4457 unsigned long cr2, rip, dr6;
4459 enum emulation_result er;
4461 vect_info = vmx->idt_vectoring_info;
4462 intr_info = vmx->exit_intr_info;
4464 if (is_machine_check(intr_info))
4465 return handle_machine_check(vcpu);
4467 if (is_nmi(intr_info))
4468 return 1; /* already handled by vmx_vcpu_run() */
4470 if (is_invalid_opcode(intr_info))
4471 return handle_ud(vcpu);
4474 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4475 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4477 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4478 WARN_ON_ONCE(!enable_vmware_backdoor);
4479 er = kvm_emulate_instruction(vcpu,
4480 EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
4481 if (er == EMULATE_USER_EXIT)
4483 else if (er != EMULATE_DONE)
4484 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4489 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4490 * MMIO, it is better to report an internal error.
4491 * See the comments in vmx_handle_exit.
4493 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4494 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4495 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4496 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4497 vcpu->run->internal.ndata = 3;
4498 vcpu->run->internal.data[0] = vect_info;
4499 vcpu->run->internal.data[1] = intr_info;
4500 vcpu->run->internal.data[2] = error_code;
4504 if (is_page_fault(intr_info)) {
4505 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4506 /* EPT won't cause page fault directly */
4507 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
4508 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4511 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4513 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4514 return handle_rmode_exception(vcpu, ex_no, error_code);
4518 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4521 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4522 if (!(vcpu->guest_debug &
4523 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4524 vcpu->arch.dr6 &= ~15;
4525 vcpu->arch.dr6 |= dr6 | DR6_RTM;
4526 if (is_icebp(intr_info))
4527 skip_emulated_instruction(vcpu);
4529 kvm_queue_exception(vcpu, DB_VECTOR);
4532 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4533 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4537 * Update instruction length as we may reinject #BP from
4538 * user space while in guest debugging mode. Reading it for
4539 * #DB as well causes no harm, it is not used in that case.
4541 vmx->vcpu.arch.event_exit_inst_len =
4542 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4543 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4544 rip = kvm_rip_read(vcpu);
4545 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4546 kvm_run->debug.arch.exception = ex_no;
4549 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4550 kvm_run->ex.exception = ex_no;
4551 kvm_run->ex.error_code = error_code;
4557 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4559 ++vcpu->stat.irq_exits;
4563 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4565 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4566 vcpu->mmio_needed = 0;
4570 static int handle_io(struct kvm_vcpu *vcpu)
4572 unsigned long exit_qualification;
4573 int size, in, string;
4576 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4577 string = (exit_qualification & 16) != 0;
4579 ++vcpu->stat.io_exits;
4582 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4584 port = exit_qualification >> 16;
4585 size = (exit_qualification & 7) + 1;
4586 in = (exit_qualification & 8) != 0;
4588 return kvm_fast_pio(vcpu, size, port, in);
4592 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4595 * Patch in the VMCALL instruction:
4597 hypercall[0] = 0x0f;
4598 hypercall[1] = 0x01;
4599 hypercall[2] = 0xc1;
4602 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4603 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4605 if (is_guest_mode(vcpu)) {
4606 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4607 unsigned long orig_val = val;
4610 * We get here when L2 changed cr0 in a way that did not change
4611 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4612 * but did change L0 shadowed bits. So we first calculate the
4613 * effective cr0 value that L1 would like to write into the
4614 * hardware. It consists of the L2-owned bits from the new
4615 * value combined with the L1-owned bits from L1's guest_cr0.
4617 val = (val & ~vmcs12->cr0_guest_host_mask) |
4618 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4620 if (!nested_guest_cr0_valid(vcpu, val))
4623 if (kvm_set_cr0(vcpu, val))
4625 vmcs_writel(CR0_READ_SHADOW, orig_val);
4628 if (to_vmx(vcpu)->nested.vmxon &&
4629 !nested_host_cr0_valid(vcpu, val))
4632 return kvm_set_cr0(vcpu, val);
4636 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4638 if (is_guest_mode(vcpu)) {
4639 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4640 unsigned long orig_val = val;
4642 /* analogously to handle_set_cr0 */
4643 val = (val & ~vmcs12->cr4_guest_host_mask) |
4644 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4645 if (kvm_set_cr4(vcpu, val))
4647 vmcs_writel(CR4_READ_SHADOW, orig_val);
4650 return kvm_set_cr4(vcpu, val);
4653 static int handle_desc(struct kvm_vcpu *vcpu)
4655 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4656 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4659 static int handle_cr(struct kvm_vcpu *vcpu)
4661 unsigned long exit_qualification, val;
4667 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4668 cr = exit_qualification & 15;
4669 reg = (exit_qualification >> 8) & 15;
4670 switch ((exit_qualification >> 4) & 3) {
4671 case 0: /* mov to cr */
4672 val = kvm_register_readl(vcpu, reg);
4673 trace_kvm_cr_write(cr, val);
4676 err = handle_set_cr0(vcpu, val);
4677 return kvm_complete_insn_gp(vcpu, err);
4679 WARN_ON_ONCE(enable_unrestricted_guest);
4680 err = kvm_set_cr3(vcpu, val);
4681 return kvm_complete_insn_gp(vcpu, err);
4683 err = handle_set_cr4(vcpu, val);
4684 return kvm_complete_insn_gp(vcpu, err);
4686 u8 cr8_prev = kvm_get_cr8(vcpu);
4688 err = kvm_set_cr8(vcpu, cr8);
4689 ret = kvm_complete_insn_gp(vcpu, err);
4690 if (lapic_in_kernel(vcpu))
4692 if (cr8_prev <= cr8)
4695 * TODO: we might be squashing a
4696 * KVM_GUESTDBG_SINGLESTEP-triggered
4697 * KVM_EXIT_DEBUG here.
4699 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4705 WARN_ONCE(1, "Guest should always own CR0.TS");
4706 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4707 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4708 return kvm_skip_emulated_instruction(vcpu);
4709 case 1: /*mov from cr*/
4712 WARN_ON_ONCE(enable_unrestricted_guest);
4713 val = kvm_read_cr3(vcpu);
4714 kvm_register_write(vcpu, reg, val);
4715 trace_kvm_cr_read(cr, val);
4716 return kvm_skip_emulated_instruction(vcpu);
4718 val = kvm_get_cr8(vcpu);
4719 kvm_register_write(vcpu, reg, val);
4720 trace_kvm_cr_read(cr, val);
4721 return kvm_skip_emulated_instruction(vcpu);
4725 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4726 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4727 kvm_lmsw(vcpu, val);
4729 return kvm_skip_emulated_instruction(vcpu);
4733 vcpu->run->exit_reason = 0;
4734 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4735 (int)(exit_qualification >> 4) & 3, cr);
4739 static int handle_dr(struct kvm_vcpu *vcpu)
4741 unsigned long exit_qualification;
4744 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4745 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
4747 /* First, if DR does not exist, trigger UD */
4748 if (!kvm_require_dr(vcpu, dr))
4751 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
4752 if (!kvm_require_cpl(vcpu, 0))
4754 dr7 = vmcs_readl(GUEST_DR7);
4757 * As the vm-exit takes precedence over the debug trap, we
4758 * need to emulate the latter, either for the host or the
4759 * guest debugging itself.
4761 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
4762 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
4763 vcpu->run->debug.arch.dr7 = dr7;
4764 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
4765 vcpu->run->debug.arch.exception = DB_VECTOR;
4766 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
4769 vcpu->arch.dr6 &= ~15;
4770 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
4771 kvm_queue_exception(vcpu, DB_VECTOR);
4776 if (vcpu->guest_debug == 0) {
4777 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4778 CPU_BASED_MOV_DR_EXITING);
4781 * No more DR vmexits; force a reload of the debug registers
4782 * and reenter on this instruction. The next vmexit will
4783 * retrieve the full state of the debug registers.
4785 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4789 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
4790 if (exit_qualification & TYPE_MOV_FROM_DR) {
4793 if (kvm_get_dr(vcpu, dr, &val))
4795 kvm_register_write(vcpu, reg, val);
4797 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
4800 return kvm_skip_emulated_instruction(vcpu);
4803 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
4805 return vcpu->arch.dr6;
4808 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
4812 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
4814 get_debugreg(vcpu->arch.db[0], 0);
4815 get_debugreg(vcpu->arch.db[1], 1);
4816 get_debugreg(vcpu->arch.db[2], 2);
4817 get_debugreg(vcpu->arch.db[3], 3);
4818 get_debugreg(vcpu->arch.dr6, 6);
4819 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
4821 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
4822 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
4825 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
4827 vmcs_writel(GUEST_DR7, val);
4830 static int handle_cpuid(struct kvm_vcpu *vcpu)
4832 return kvm_emulate_cpuid(vcpu);
4835 static int handle_rdmsr(struct kvm_vcpu *vcpu)
4837 u32 ecx = kvm_rcx_read(vcpu);
4838 struct msr_data msr_info;
4840 msr_info.index = ecx;
4841 msr_info.host_initiated = false;
4842 if (vmx_get_msr(vcpu, &msr_info)) {
4843 trace_kvm_msr_read_ex(ecx);
4844 kvm_inject_gp(vcpu, 0);
4848 trace_kvm_msr_read(ecx, msr_info.data);
4850 kvm_rax_write(vcpu, msr_info.data & -1u);
4851 kvm_rdx_write(vcpu, (msr_info.data >> 32) & -1u);
4852 return kvm_skip_emulated_instruction(vcpu);
4855 static int handle_wrmsr(struct kvm_vcpu *vcpu)
4857 struct msr_data msr;
4858 u32 ecx = kvm_rcx_read(vcpu);
4859 u64 data = kvm_read_edx_eax(vcpu);
4863 msr.host_initiated = false;
4864 if (kvm_set_msr(vcpu, &msr) != 0) {
4865 trace_kvm_msr_write_ex(ecx, data);
4866 kvm_inject_gp(vcpu, 0);
4870 trace_kvm_msr_write(ecx, data);
4871 return kvm_skip_emulated_instruction(vcpu);
4874 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
4876 kvm_apic_update_ppr(vcpu);
4880 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
4882 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4883 CPU_BASED_VIRTUAL_INTR_PENDING);
4885 kvm_make_request(KVM_REQ_EVENT, vcpu);
4887 ++vcpu->stat.irq_window_exits;
4891 static int handle_halt(struct kvm_vcpu *vcpu)
4893 return kvm_emulate_halt(vcpu);
4896 static int handle_vmcall(struct kvm_vcpu *vcpu)
4898 return kvm_emulate_hypercall(vcpu);
4901 static int handle_invd(struct kvm_vcpu *vcpu)
4903 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4906 static int handle_invlpg(struct kvm_vcpu *vcpu)
4908 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4910 kvm_mmu_invlpg(vcpu, exit_qualification);
4911 return kvm_skip_emulated_instruction(vcpu);
4914 static int handle_rdpmc(struct kvm_vcpu *vcpu)
4918 err = kvm_rdpmc(vcpu);
4919 return kvm_complete_insn_gp(vcpu, err);
4922 static int handle_wbinvd(struct kvm_vcpu *vcpu)
4924 return kvm_emulate_wbinvd(vcpu);
4927 static int handle_xsetbv(struct kvm_vcpu *vcpu)
4929 u64 new_bv = kvm_read_edx_eax(vcpu);
4930 u32 index = kvm_rcx_read(vcpu);
4932 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
4933 return kvm_skip_emulated_instruction(vcpu);
4937 static int handle_xsaves(struct kvm_vcpu *vcpu)
4939 kvm_skip_emulated_instruction(vcpu);
4940 WARN(1, "this should never happen\n");
4944 static int handle_xrstors(struct kvm_vcpu *vcpu)
4946 kvm_skip_emulated_instruction(vcpu);
4947 WARN(1, "this should never happen\n");
4951 static int handle_apic_access(struct kvm_vcpu *vcpu)
4953 if (likely(fasteoi)) {
4954 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4955 int access_type, offset;
4957 access_type = exit_qualification & APIC_ACCESS_TYPE;
4958 offset = exit_qualification & APIC_ACCESS_OFFSET;
4960 * Sane guest uses MOV to write EOI, with written value
4961 * not cared. So make a short-circuit here by avoiding
4962 * heavy instruction emulation.
4964 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
4965 (offset == APIC_EOI)) {
4966 kvm_lapic_set_eoi(vcpu);
4967 return kvm_skip_emulated_instruction(vcpu);
4970 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4973 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
4975 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4976 int vector = exit_qualification & 0xff;
4978 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
4979 kvm_apic_set_eoi_accelerated(vcpu, vector);
4983 static int handle_apic_write(struct kvm_vcpu *vcpu)
4985 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4986 u32 offset = exit_qualification & 0xfff;
4988 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
4989 kvm_apic_write_nodecode(vcpu, offset);
4993 static int handle_task_switch(struct kvm_vcpu *vcpu)
4995 struct vcpu_vmx *vmx = to_vmx(vcpu);
4996 unsigned long exit_qualification;
4997 bool has_error_code = false;
5000 int reason, type, idt_v, idt_index;
5002 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5003 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5004 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5006 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5008 reason = (u32)exit_qualification >> 30;
5009 if (reason == TASK_SWITCH_GATE && idt_v) {
5011 case INTR_TYPE_NMI_INTR:
5012 vcpu->arch.nmi_injected = false;
5013 vmx_set_nmi_mask(vcpu, true);
5015 case INTR_TYPE_EXT_INTR:
5016 case INTR_TYPE_SOFT_INTR:
5017 kvm_clear_interrupt_queue(vcpu);
5019 case INTR_TYPE_HARD_EXCEPTION:
5020 if (vmx->idt_vectoring_info &
5021 VECTORING_INFO_DELIVER_CODE_MASK) {
5022 has_error_code = true;
5024 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5027 case INTR_TYPE_SOFT_EXCEPTION:
5028 kvm_clear_exception_queue(vcpu);
5034 tss_selector = exit_qualification;
5036 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5037 type != INTR_TYPE_EXT_INTR &&
5038 type != INTR_TYPE_NMI_INTR))
5039 skip_emulated_instruction(vcpu);
5041 if (kvm_task_switch(vcpu, tss_selector,
5042 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
5043 has_error_code, error_code) == EMULATE_FAIL) {
5044 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5045 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5046 vcpu->run->internal.ndata = 0;
5051 * TODO: What about debug traps on tss switch?
5052 * Are we supposed to inject them and update dr6?
5058 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5060 unsigned long exit_qualification;
5064 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5067 * EPT violation happened while executing iret from NMI,
5068 * "blocked by NMI" bit has to be set before next VM entry.
5069 * There are errata that may cause this bit to not be set:
5072 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5074 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5075 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5077 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5078 trace_kvm_page_fault(gpa, exit_qualification);
5080 /* Is it a read fault? */
5081 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5082 ? PFERR_USER_MASK : 0;
5083 /* Is it a write fault? */
5084 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5085 ? PFERR_WRITE_MASK : 0;
5086 /* Is it a fetch fault? */
5087 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5088 ? PFERR_FETCH_MASK : 0;
5089 /* ept page table entry is present? */
5090 error_code |= (exit_qualification &
5091 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5092 EPT_VIOLATION_EXECUTABLE))
5093 ? PFERR_PRESENT_MASK : 0;
5095 error_code |= (exit_qualification & 0x100) != 0 ?
5096 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5098 vcpu->arch.exit_qualification = exit_qualification;
5099 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5102 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5107 * A nested guest cannot optimize MMIO vmexits, because we have an
5108 * nGPA here instead of the required GPA.
5110 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5111 if (!is_guest_mode(vcpu) &&
5112 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5113 trace_kvm_fast_mmio(gpa);
5115 * Doing kvm_skip_emulated_instruction() depends on undefined
5116 * behavior: Intel's manual doesn't mandate
5117 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
5118 * occurs and while on real hardware it was observed to be set,
5119 * other hypervisors (namely Hyper-V) don't set it, we end up
5120 * advancing IP with some random value. Disable fast mmio when
5121 * running nested and keep it for real hardware in hope that
5122 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
5124 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
5125 return kvm_skip_emulated_instruction(vcpu);
5127 return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
5131 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5134 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5136 WARN_ON_ONCE(!enable_vnmi);
5137 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
5138 CPU_BASED_VIRTUAL_NMI_PENDING);
5139 ++vcpu->stat.nmi_window_exits;
5140 kvm_make_request(KVM_REQ_EVENT, vcpu);
5145 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5147 struct vcpu_vmx *vmx = to_vmx(vcpu);
5148 enum emulation_result err = EMULATE_DONE;
5151 bool intr_window_requested;
5152 unsigned count = 130;
5155 * We should never reach the point where we are emulating L2
5156 * due to invalid guest state as that means we incorrectly
5157 * allowed a nested VMEntry with an invalid vmcs12.
5159 WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
5161 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5162 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
5164 while (vmx->emulation_required && count-- != 0) {
5165 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5166 return handle_interrupt_window(&vmx->vcpu);
5168 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5171 err = kvm_emulate_instruction(vcpu, 0);
5173 if (err == EMULATE_USER_EXIT) {
5174 ++vcpu->stat.mmio_exits;
5179 if (err != EMULATE_DONE)
5180 goto emulation_error;
5182 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5183 vcpu->arch.exception.pending)
5184 goto emulation_error;
5186 if (vcpu->arch.halt_request) {
5187 vcpu->arch.halt_request = 0;
5188 ret = kvm_vcpu_halt(vcpu);
5192 if (signal_pending(current))
5202 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5203 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5204 vcpu->run->internal.ndata = 0;
5208 static void grow_ple_window(struct kvm_vcpu *vcpu)
5210 struct vcpu_vmx *vmx = to_vmx(vcpu);
5211 int old = vmx->ple_window;
5213 vmx->ple_window = __grow_ple_window(old, ple_window,
5217 if (vmx->ple_window != old)
5218 vmx->ple_window_dirty = true;
5220 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
5223 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5225 struct vcpu_vmx *vmx = to_vmx(vcpu);
5226 int old = vmx->ple_window;
5228 vmx->ple_window = __shrink_ple_window(old, ple_window,
5232 if (vmx->ple_window != old)
5233 vmx->ple_window_dirty = true;
5235 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
5239 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5241 static void wakeup_handler(void)
5243 struct kvm_vcpu *vcpu;
5244 int cpu = smp_processor_id();
5246 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5247 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5248 blocked_vcpu_list) {
5249 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5251 if (pi_test_on(pi_desc) == 1)
5252 kvm_vcpu_kick(vcpu);
5254 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5257 static void vmx_enable_tdp(void)
5259 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5260 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5261 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5262 0ull, VMX_EPT_EXECUTABLE_MASK,
5263 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5264 VMX_EPT_RWX_MASK, 0ull);
5266 ept_set_mmio_spte_mask();
5271 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5272 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5274 static int handle_pause(struct kvm_vcpu *vcpu)
5276 if (!kvm_pause_in_guest(vcpu->kvm))
5277 grow_ple_window(vcpu);
5280 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5281 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5282 * never set PAUSE_EXITING and just set PLE if supported,
5283 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5285 kvm_vcpu_on_spin(vcpu, true);
5286 return kvm_skip_emulated_instruction(vcpu);
5289 static int handle_nop(struct kvm_vcpu *vcpu)
5291 return kvm_skip_emulated_instruction(vcpu);
5294 static int handle_mwait(struct kvm_vcpu *vcpu)
5296 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5297 return handle_nop(vcpu);
5300 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5302 kvm_queue_exception(vcpu, UD_VECTOR);
5306 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5311 static int handle_monitor(struct kvm_vcpu *vcpu)
5313 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5314 return handle_nop(vcpu);
5317 static int handle_invpcid(struct kvm_vcpu *vcpu)
5319 u32 vmx_instruction_info;
5323 struct x86_exception e;
5325 unsigned long roots_to_free = 0;
5331 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5332 kvm_queue_exception(vcpu, UD_VECTOR);
5336 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5337 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5340 kvm_inject_gp(vcpu, 0);
5344 /* According to the Intel instruction reference, the memory operand
5345 * is read even if it isn't needed (e.g., for type==all)
5347 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5348 vmx_instruction_info, false, &gva))
5351 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5352 kvm_inject_page_fault(vcpu, &e);
5356 if (operand.pcid >> 12 != 0) {
5357 kvm_inject_gp(vcpu, 0);
5361 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5364 case INVPCID_TYPE_INDIV_ADDR:
5365 if ((!pcid_enabled && (operand.pcid != 0)) ||
5366 is_noncanonical_address(operand.gla, vcpu)) {
5367 kvm_inject_gp(vcpu, 0);
5370 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5371 return kvm_skip_emulated_instruction(vcpu);
5373 case INVPCID_TYPE_SINGLE_CTXT:
5374 if (!pcid_enabled && (operand.pcid != 0)) {
5375 kvm_inject_gp(vcpu, 0);
5379 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5380 kvm_mmu_sync_roots(vcpu);
5381 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5384 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5385 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
5387 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5389 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5391 * If neither the current cr3 nor any of the prev_roots use the
5392 * given PCID, then nothing needs to be done here because a
5393 * resync will happen anyway before switching to any other CR3.
5396 return kvm_skip_emulated_instruction(vcpu);
5398 case INVPCID_TYPE_ALL_NON_GLOBAL:
5400 * Currently, KVM doesn't mark global entries in the shadow
5401 * page tables, so a non-global flush just degenerates to a
5402 * global flush. If needed, we could optimize this later by
5403 * keeping track of global entries in shadow page tables.
5407 case INVPCID_TYPE_ALL_INCL_GLOBAL:
5408 kvm_mmu_unload(vcpu);
5409 return kvm_skip_emulated_instruction(vcpu);
5412 BUG(); /* We have already checked above that type <= 3 */
5416 static int handle_pml_full(struct kvm_vcpu *vcpu)
5418 unsigned long exit_qualification;
5420 trace_kvm_pml_full(vcpu->vcpu_id);
5422 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5425 * PML buffer FULL happened while executing iret from NMI,
5426 * "blocked by NMI" bit has to be set before next VM entry.
5428 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5430 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5431 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5432 GUEST_INTR_STATE_NMI);
5435 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5436 * here.., and there's no userspace involvement needed for PML.
5441 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5443 if (!to_vmx(vcpu)->req_immediate_exit)
5444 kvm_lapic_expired_hv_timer(vcpu);
5449 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5450 * are overwritten by nested_vmx_setup() when nested=1.
5452 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5454 kvm_queue_exception(vcpu, UD_VECTOR);
5458 static int handle_encls(struct kvm_vcpu *vcpu)
5461 * SGX virtualization is not yet supported. There is no software
5462 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5463 * to prevent the guest from executing ENCLS.
5465 kvm_queue_exception(vcpu, UD_VECTOR);
5470 * The exit handlers return 1 if the exit was handled fully and guest execution
5471 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5472 * to be done to userspace and return 0.
5474 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5475 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
5476 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5477 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5478 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5479 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5480 [EXIT_REASON_CR_ACCESS] = handle_cr,
5481 [EXIT_REASON_DR_ACCESS] = handle_dr,
5482 [EXIT_REASON_CPUID] = handle_cpuid,
5483 [EXIT_REASON_MSR_READ] = handle_rdmsr,
5484 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
5485 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
5486 [EXIT_REASON_HLT] = handle_halt,
5487 [EXIT_REASON_INVD] = handle_invd,
5488 [EXIT_REASON_INVLPG] = handle_invlpg,
5489 [EXIT_REASON_RDPMC] = handle_rdpmc,
5490 [EXIT_REASON_VMCALL] = handle_vmcall,
5491 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5492 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5493 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5494 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5495 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5496 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5497 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5498 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5499 [EXIT_REASON_VMON] = handle_vmx_instruction,
5500 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5501 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5502 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5503 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5504 [EXIT_REASON_WBINVD] = handle_wbinvd,
5505 [EXIT_REASON_XSETBV] = handle_xsetbv,
5506 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5507 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5508 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5509 [EXIT_REASON_LDTR_TR] = handle_desc,
5510 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5511 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5512 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5513 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5514 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5515 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5516 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5517 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5518 [EXIT_REASON_RDRAND] = handle_invalid_op,
5519 [EXIT_REASON_RDSEED] = handle_invalid_op,
5520 [EXIT_REASON_XSAVES] = handle_xsaves,
5521 [EXIT_REASON_XRSTORS] = handle_xrstors,
5522 [EXIT_REASON_PML_FULL] = handle_pml_full,
5523 [EXIT_REASON_INVPCID] = handle_invpcid,
5524 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5525 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5526 [EXIT_REASON_ENCLS] = handle_encls,
5529 static const int kvm_vmx_max_exit_handlers =
5530 ARRAY_SIZE(kvm_vmx_exit_handlers);
5532 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5534 *info1 = vmcs_readl(EXIT_QUALIFICATION);
5535 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
5538 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5541 __free_page(vmx->pml_pg);
5546 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5548 struct vcpu_vmx *vmx = to_vmx(vcpu);
5552 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5554 /* Do nothing if PML buffer is empty */
5555 if (pml_idx == (PML_ENTITY_NUM - 1))
5558 /* PML index always points to next available PML buffer entity */
5559 if (pml_idx >= PML_ENTITY_NUM)
5564 pml_buf = page_address(vmx->pml_pg);
5565 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5568 gpa = pml_buf[pml_idx];
5569 WARN_ON(gpa & (PAGE_SIZE - 1));
5570 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5573 /* reset PML index */
5574 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5578 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5579 * Called before reporting dirty_bitmap to userspace.
5581 static void kvm_flush_pml_buffers(struct kvm *kvm)
5584 struct kvm_vcpu *vcpu;
5586 * We only need to kick vcpu out of guest mode here, as PML buffer
5587 * is flushed at beginning of all VMEXITs, and it's obvious that only
5588 * vcpus running in guest are possible to have unflushed GPAs in PML
5591 kvm_for_each_vcpu(i, vcpu, kvm)
5592 kvm_vcpu_kick(vcpu);
5595 static void vmx_dump_sel(char *name, uint32_t sel)
5597 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5598 name, vmcs_read16(sel),
5599 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5600 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5601 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5604 static void vmx_dump_dtsel(char *name, uint32_t limit)
5606 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5607 name, vmcs_read32(limit),
5608 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5611 void dump_vmcs(void)
5613 u32 vmentry_ctl, vmexit_ctl;
5614 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5619 if (!dump_invalid_vmcs) {
5620 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5624 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5625 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5626 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5627 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5628 cr4 = vmcs_readl(GUEST_CR4);
5629 efer = vmcs_read64(GUEST_IA32_EFER);
5630 secondary_exec_control = 0;
5631 if (cpu_has_secondary_exec_ctrls())
5632 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5634 pr_err("*** Guest State ***\n");
5635 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5636 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5637 vmcs_readl(CR0_GUEST_HOST_MASK));
5638 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5639 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5640 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5641 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5642 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5644 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5645 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5646 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5647 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5649 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5650 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5651 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5652 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5653 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5654 vmcs_readl(GUEST_SYSENTER_ESP),
5655 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5656 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5657 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5658 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5659 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5660 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5661 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5662 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5663 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5664 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5665 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5666 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5667 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5668 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5669 efer, vmcs_read64(GUEST_IA32_PAT));
5670 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5671 vmcs_read64(GUEST_IA32_DEBUGCTL),
5672 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5673 if (cpu_has_load_perf_global_ctrl() &&
5674 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5675 pr_err("PerfGlobCtl = 0x%016llx\n",
5676 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5677 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5678 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5679 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5680 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5681 vmcs_read32(GUEST_ACTIVITY_STATE));
5682 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5683 pr_err("InterruptStatus = %04x\n",
5684 vmcs_read16(GUEST_INTR_STATUS));
5686 pr_err("*** Host State ***\n");
5687 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5688 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5689 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5690 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5691 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5692 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5693 vmcs_read16(HOST_TR_SELECTOR));
5694 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5695 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5696 vmcs_readl(HOST_TR_BASE));
5697 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5698 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5699 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5700 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5701 vmcs_readl(HOST_CR4));
5702 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5703 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5704 vmcs_read32(HOST_IA32_SYSENTER_CS),
5705 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5706 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5707 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5708 vmcs_read64(HOST_IA32_EFER),
5709 vmcs_read64(HOST_IA32_PAT));
5710 if (cpu_has_load_perf_global_ctrl() &&
5711 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5712 pr_err("PerfGlobCtl = 0x%016llx\n",
5713 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5715 pr_err("*** Control State ***\n");
5716 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5717 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5718 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5719 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5720 vmcs_read32(EXCEPTION_BITMAP),
5721 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5722 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5723 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5724 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5725 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5726 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5727 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5728 vmcs_read32(VM_EXIT_INTR_INFO),
5729 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5730 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5731 pr_err(" reason=%08x qualification=%016lx\n",
5732 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5733 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5734 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5735 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5736 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5737 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5738 pr_err("TSC Multiplier = 0x%016llx\n",
5739 vmcs_read64(TSC_MULTIPLIER));
5740 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5741 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5742 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5743 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5745 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5746 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5747 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5748 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5750 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5751 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5752 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5753 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5754 n = vmcs_read32(CR3_TARGET_COUNT);
5755 for (i = 0; i + 1 < n; i += 4)
5756 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
5757 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
5758 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
5760 pr_err("CR3 target%u=%016lx\n",
5761 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
5762 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5763 pr_err("PLE Gap=%08x Window=%08x\n",
5764 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5765 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5766 pr_err("Virtual processor ID = 0x%04x\n",
5767 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5771 * The guest has exited. See if we can fix it or if we need userspace
5774 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
5776 struct vcpu_vmx *vmx = to_vmx(vcpu);
5777 u32 exit_reason = vmx->exit_reason;
5778 u32 vectoring_info = vmx->idt_vectoring_info;
5780 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
5783 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5784 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5785 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5786 * mode as if vcpus is in root mode, the PML buffer must has been
5790 vmx_flush_pml_buffer(vcpu);
5792 /* If guest state is invalid, start emulating */
5793 if (vmx->emulation_required)
5794 return handle_invalid_guest_state(vcpu);
5796 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
5797 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
5799 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5801 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5802 vcpu->run->fail_entry.hardware_entry_failure_reason
5807 if (unlikely(vmx->fail)) {
5808 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5809 vcpu->run->fail_entry.hardware_entry_failure_reason
5810 = vmcs_read32(VM_INSTRUCTION_ERROR);
5816 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5817 * delivery event since it indicates guest is accessing MMIO.
5818 * The vm-exit can be triggered again after return to guest that
5819 * will cause infinite loop.
5821 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5822 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5823 exit_reason != EXIT_REASON_EPT_VIOLATION &&
5824 exit_reason != EXIT_REASON_PML_FULL &&
5825 exit_reason != EXIT_REASON_TASK_SWITCH)) {
5826 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5827 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
5828 vcpu->run->internal.ndata = 3;
5829 vcpu->run->internal.data[0] = vectoring_info;
5830 vcpu->run->internal.data[1] = exit_reason;
5831 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
5832 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
5833 vcpu->run->internal.ndata++;
5834 vcpu->run->internal.data[3] =
5835 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5840 if (unlikely(!enable_vnmi &&
5841 vmx->loaded_vmcs->soft_vnmi_blocked)) {
5842 if (vmx_interrupt_allowed(vcpu)) {
5843 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5844 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
5845 vcpu->arch.nmi_pending) {
5847 * This CPU don't support us in finding the end of an
5848 * NMI-blocked window if the guest runs with IRQs
5849 * disabled. So we pull the trigger after 1 s of
5850 * futile waiting, but inform the user about this.
5852 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
5853 "state on VCPU %d after 1 s timeout\n",
5854 __func__, vcpu->vcpu_id);
5855 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5859 if (exit_reason < kvm_vmx_max_exit_handlers
5860 && kvm_vmx_exit_handlers[exit_reason])
5861 return kvm_vmx_exit_handlers[exit_reason](vcpu);
5863 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
5865 kvm_queue_exception(vcpu, UD_VECTOR);
5871 * Software based L1D cache flush which is used when microcode providing
5872 * the cache control MSR is not loaded.
5874 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
5875 * flush it is required to read in 64 KiB because the replacement algorithm
5876 * is not exactly LRU. This could be sized at runtime via topology
5877 * information but as all relevant affected CPUs have 32KiB L1D cache size
5878 * there is no point in doing so.
5880 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
5882 int size = PAGE_SIZE << L1D_CACHE_ORDER;
5885 * This code is only executed when the the flush mode is 'cond' or
5888 if (static_branch_likely(&vmx_l1d_flush_cond)) {
5892 * Clear the per-vcpu flush bit, it gets set again
5893 * either from vcpu_run() or from one of the unsafe
5896 flush_l1d = vcpu->arch.l1tf_flush_l1d;
5897 vcpu->arch.l1tf_flush_l1d = false;
5900 * Clear the per-cpu flush bit, it gets set again from
5901 * the interrupt handlers.
5903 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
5904 kvm_clear_cpu_l1tf_flush_l1d();
5910 vcpu->stat.l1d_flush++;
5912 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
5913 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
5918 /* First ensure the pages are in the TLB */
5919 "xorl %%eax, %%eax\n"
5920 ".Lpopulate_tlb:\n\t"
5921 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5922 "addl $4096, %%eax\n\t"
5923 "cmpl %%eax, %[size]\n\t"
5924 "jne .Lpopulate_tlb\n\t"
5925 "xorl %%eax, %%eax\n\t"
5927 /* Now fill the cache */
5928 "xorl %%eax, %%eax\n"
5930 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5931 "addl $64, %%eax\n\t"
5932 "cmpl %%eax, %[size]\n\t"
5933 "jne .Lfill_cache\n\t"
5935 :: [flush_pages] "r" (vmx_l1d_flush_pages),
5937 : "eax", "ebx", "ecx", "edx");
5940 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5942 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5944 if (is_guest_mode(vcpu) &&
5945 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
5948 if (irr == -1 || tpr < irr) {
5949 vmcs_write32(TPR_THRESHOLD, 0);
5953 vmcs_write32(TPR_THRESHOLD, irr);
5956 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5958 u32 sec_exec_control;
5960 if (!lapic_in_kernel(vcpu))
5963 if (!flexpriority_enabled &&
5964 !cpu_has_vmx_virtualize_x2apic_mode())
5967 /* Postpone execution until vmcs01 is the current VMCS. */
5968 if (is_guest_mode(vcpu)) {
5969 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
5973 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5974 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
5975 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
5977 switch (kvm_get_apic_mode(vcpu)) {
5978 case LAPIC_MODE_INVALID:
5979 WARN_ONCE(true, "Invalid local APIC state");
5980 case LAPIC_MODE_DISABLED:
5982 case LAPIC_MODE_XAPIC:
5983 if (flexpriority_enabled) {
5985 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5986 vmx_flush_tlb(vcpu, true);
5989 case LAPIC_MODE_X2APIC:
5990 if (cpu_has_vmx_virtualize_x2apic_mode())
5992 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5995 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
5997 vmx_update_msr_bitmap(vcpu);
6000 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
6002 if (!is_guest_mode(vcpu)) {
6003 vmcs_write64(APIC_ACCESS_ADDR, hpa);
6004 vmx_flush_tlb(vcpu, true);
6008 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6016 status = vmcs_read16(GUEST_INTR_STATUS);
6018 if (max_isr != old) {
6020 status |= max_isr << 8;
6021 vmcs_write16(GUEST_INTR_STATUS, status);
6025 static void vmx_set_rvi(int vector)
6033 status = vmcs_read16(GUEST_INTR_STATUS);
6034 old = (u8)status & 0xff;
6035 if ((u8)vector != old) {
6037 status |= (u8)vector;
6038 vmcs_write16(GUEST_INTR_STATUS, status);
6042 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6045 * When running L2, updating RVI is only relevant when
6046 * vmcs12 virtual-interrupt-delivery enabled.
6047 * However, it can be enabled only when L1 also
6048 * intercepts external-interrupts and in that case
6049 * we should not update vmcs02 RVI but instead intercept
6050 * interrupt. Therefore, do nothing when running L2.
6052 if (!is_guest_mode(vcpu))
6053 vmx_set_rvi(max_irr);
6056 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6058 struct vcpu_vmx *vmx = to_vmx(vcpu);
6060 bool max_irr_updated;
6062 WARN_ON(!vcpu->arch.apicv_active);
6063 if (pi_test_on(&vmx->pi_desc)) {
6064 pi_clear_on(&vmx->pi_desc);
6066 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
6067 * But on x86 this is just a compiler barrier anyway.
6069 smp_mb__after_atomic();
6071 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6074 * If we are running L2 and L1 has a new pending interrupt
6075 * which can be injected, we should re-evaluate
6076 * what should be done with this new L1 interrupt.
6077 * If L1 intercepts external-interrupts, we should
6078 * exit from L2 to L1. Otherwise, interrupt should be
6079 * delivered directly to L2.
6081 if (is_guest_mode(vcpu) && max_irr_updated) {
6082 if (nested_exit_on_intr(vcpu))
6083 kvm_vcpu_exiting_guest_mode(vcpu);
6085 kvm_make_request(KVM_REQ_EVENT, vcpu);
6088 max_irr = kvm_lapic_find_highest_irr(vcpu);
6090 vmx_hwapic_irr_update(vcpu, max_irr);
6094 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6096 if (!kvm_vcpu_apicv_active(vcpu))
6099 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6100 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6101 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6102 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6105 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6107 struct vcpu_vmx *vmx = to_vmx(vcpu);
6109 pi_clear_on(&vmx->pi_desc);
6110 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6113 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
6115 u32 exit_intr_info = 0;
6116 u16 basic_exit_reason = (u16)vmx->exit_reason;
6118 if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
6119 || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
6122 if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6123 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6124 vmx->exit_intr_info = exit_intr_info;
6126 /* if exit due to PF check for async PF */
6127 if (is_page_fault(exit_intr_info))
6128 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
6130 /* Handle machine checks before interrupts are enabled */
6131 if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
6132 is_machine_check(exit_intr_info))
6133 kvm_machine_check();
6135 /* We need to handle NMIs before interrupts are enabled */
6136 if (is_nmi(exit_intr_info)) {
6137 kvm_before_interrupt(&vmx->vcpu);
6139 kvm_after_interrupt(&vmx->vcpu);
6143 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
6145 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6147 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
6148 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
6149 unsigned int vector;
6150 unsigned long entry;
6152 struct vcpu_vmx *vmx = to_vmx(vcpu);
6153 #ifdef CONFIG_X86_64
6157 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6158 desc = (gate_desc *)vmx->host_idt_base + vector;
6159 entry = gate_offset(desc);
6161 #ifdef CONFIG_X86_64
6162 "mov %%" _ASM_SP ", %[sp]\n\t"
6163 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
6168 __ASM_SIZE(push) " $%c[cs]\n\t"
6171 #ifdef CONFIG_X86_64
6176 THUNK_TARGET(entry),
6177 [ss]"i"(__KERNEL_DS),
6178 [cs]"i"(__KERNEL_CS)
6182 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
6184 static bool vmx_has_emulated_msr(int index)
6187 case MSR_IA32_SMBASE:
6189 * We cannot do SMM unless we can run the guest in big
6192 return enable_unrestricted_guest || emulate_invalid_guest_state;
6193 case MSR_AMD64_VIRT_SPEC_CTRL:
6194 /* This is AMD only. */
6201 static bool vmx_pt_supported(void)
6203 return pt_mode == PT_MODE_HOST_GUEST;
6206 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6211 bool idtv_info_valid;
6213 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6216 if (vmx->loaded_vmcs->nmi_known_unmasked)
6219 * Can't use vmx->exit_intr_info since we're not sure what
6220 * the exit reason is.
6222 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6223 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6224 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6226 * SDM 3: 27.7.1.2 (September 2008)
6227 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6228 * a guest IRET fault.
6229 * SDM 3: 23.2.2 (September 2008)
6230 * Bit 12 is undefined in any of the following cases:
6231 * If the VM exit sets the valid bit in the IDT-vectoring
6232 * information field.
6233 * If the VM exit is due to a double fault.
6235 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6236 vector != DF_VECTOR && !idtv_info_valid)
6237 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6238 GUEST_INTR_STATE_NMI);
6240 vmx->loaded_vmcs->nmi_known_unmasked =
6241 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6242 & GUEST_INTR_STATE_NMI);
6243 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6244 vmx->loaded_vmcs->vnmi_blocked_time +=
6245 ktime_to_ns(ktime_sub(ktime_get(),
6246 vmx->loaded_vmcs->entry_time));
6249 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6250 u32 idt_vectoring_info,
6251 int instr_len_field,
6252 int error_code_field)
6256 bool idtv_info_valid;
6258 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6260 vcpu->arch.nmi_injected = false;
6261 kvm_clear_exception_queue(vcpu);
6262 kvm_clear_interrupt_queue(vcpu);
6264 if (!idtv_info_valid)
6267 kvm_make_request(KVM_REQ_EVENT, vcpu);
6269 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6270 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6273 case INTR_TYPE_NMI_INTR:
6274 vcpu->arch.nmi_injected = true;
6276 * SDM 3: 27.7.1.2 (September 2008)
6277 * Clear bit "block by NMI" before VM entry if a NMI
6280 vmx_set_nmi_mask(vcpu, false);
6282 case INTR_TYPE_SOFT_EXCEPTION:
6283 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6285 case INTR_TYPE_HARD_EXCEPTION:
6286 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6287 u32 err = vmcs_read32(error_code_field);
6288 kvm_requeue_exception_e(vcpu, vector, err);
6290 kvm_requeue_exception(vcpu, vector);
6292 case INTR_TYPE_SOFT_INTR:
6293 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6295 case INTR_TYPE_EXT_INTR:
6296 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6303 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6305 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6306 VM_EXIT_INSTRUCTION_LEN,
6307 IDT_VECTORING_ERROR_CODE);
6310 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6312 __vmx_complete_interrupts(vcpu,
6313 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6314 VM_ENTRY_INSTRUCTION_LEN,
6315 VM_ENTRY_EXCEPTION_ERROR_CODE);
6317 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6320 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6323 struct perf_guest_switch_msr *msrs;
6325 msrs = perf_guest_get_msrs(&nr_msrs);
6330 for (i = 0; i < nr_msrs; i++)
6331 if (msrs[i].host == msrs[i].guest)
6332 clear_atomic_switch_msr(vmx, msrs[i].msr);
6334 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6335 msrs[i].host, false);
6338 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
6340 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
6341 if (!vmx->loaded_vmcs->hv_timer_armed)
6342 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
6343 PIN_BASED_VMX_PREEMPTION_TIMER);
6344 vmx->loaded_vmcs->hv_timer_armed = true;
6347 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6349 struct vcpu_vmx *vmx = to_vmx(vcpu);
6353 if (vmx->req_immediate_exit) {
6354 vmx_arm_hv_timer(vmx, 0);
6358 if (vmx->hv_deadline_tsc != -1) {
6360 if (vmx->hv_deadline_tsc > tscl)
6361 /* set_hv_timer ensures the delta fits in 32-bits */
6362 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6363 cpu_preemption_timer_multi);
6367 vmx_arm_hv_timer(vmx, delta_tsc);
6371 if (vmx->loaded_vmcs->hv_timer_armed)
6372 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
6373 PIN_BASED_VMX_PREEMPTION_TIMER);
6374 vmx->loaded_vmcs->hv_timer_armed = false;
6377 void vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6379 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6380 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6381 vmcs_writel(HOST_RSP, host_rsp);
6385 bool __vmx_vcpu_run(struct vcpu_vmx *vmx, unsigned long *regs, bool launched);
6387 static void vmx_vcpu_run(struct kvm_vcpu *vcpu)
6389 struct vcpu_vmx *vmx = to_vmx(vcpu);
6390 unsigned long cr3, cr4;
6392 /* Record the guest's net vcpu time for enforced NMI injections. */
6393 if (unlikely(!enable_vnmi &&
6394 vmx->loaded_vmcs->soft_vnmi_blocked))
6395 vmx->loaded_vmcs->entry_time = ktime_get();
6397 /* Don't enter VMX if guest state is invalid, let the exit handler
6398 start emulation until we arrive back to a valid state */
6399 if (vmx->emulation_required)
6402 if (vmx->ple_window_dirty) {
6403 vmx->ple_window_dirty = false;
6404 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6407 if (vmx->nested.need_vmcs12_sync)
6408 nested_sync_from_vmcs12(vcpu);
6410 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
6411 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6412 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
6413 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6415 cr3 = __get_current_cr3_fast();
6416 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6417 vmcs_writel(HOST_CR3, cr3);
6418 vmx->loaded_vmcs->host_state.cr3 = cr3;
6421 cr4 = cr4_read_shadow();
6422 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6423 vmcs_writel(HOST_CR4, cr4);
6424 vmx->loaded_vmcs->host_state.cr4 = cr4;
6427 /* When single-stepping over STI and MOV SS, we must clear the
6428 * corresponding interruptibility bits in the guest state. Otherwise
6429 * vmentry fails as it then expects bit 14 (BS) in pending debug
6430 * exceptions being set, but that's not correct for the guest debugging
6432 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6433 vmx_set_interrupt_shadow(vcpu, 0);
6435 kvm_load_guest_xcr0(vcpu);
6437 if (static_cpu_has(X86_FEATURE_PKU) &&
6438 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
6439 vcpu->arch.pkru != vmx->host_pkru)
6440 __write_pkru(vcpu->arch.pkru);
6442 pt_guest_enter(vmx);
6444 atomic_switch_perf_msrs(vmx);
6446 vmx_update_hv_timer(vcpu);
6449 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6450 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6451 * is no need to worry about the conditional branch over the wrmsr
6452 * being speculatively taken.
6454 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6456 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6457 if (static_branch_unlikely(&vmx_l1d_should_flush))
6458 vmx_l1d_flush(vcpu);
6459 else if (static_branch_unlikely(&mds_user_clear))
6460 mds_clear_cpu_buffers();
6462 if (vcpu->arch.cr2 != read_cr2())
6463 write_cr2(vcpu->arch.cr2);
6465 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6466 vmx->loaded_vmcs->launched);
6468 vcpu->arch.cr2 = read_cr2();
6471 * We do not use IBRS in the kernel. If this vCPU has used the
6472 * SPEC_CTRL MSR it may have left it on; save the value and
6473 * turn it off. This is much more efficient than blindly adding
6474 * it to the atomic save/restore list. Especially as the former
6475 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6477 * For non-nested case:
6478 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6482 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6485 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6486 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6488 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6490 /* All fields are clean at this point */
6491 if (static_branch_unlikely(&enable_evmcs))
6492 current_evmcs->hv_clean_fields |=
6493 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6495 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6496 if (vmx->host_debugctlmsr)
6497 update_debugctlmsr(vmx->host_debugctlmsr);
6499 #ifndef CONFIG_X86_64
6501 * The sysexit path does not restore ds/es, so we must set them to
6502 * a reasonable value ourselves.
6504 * We can't defer this to vmx_prepare_switch_to_host() since that
6505 * function may be executed in interrupt context, which saves and
6506 * restore segments around it, nullifying its effect.
6508 loadsegment(ds, __USER_DS);
6509 loadsegment(es, __USER_DS);
6512 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
6513 | (1 << VCPU_EXREG_RFLAGS)
6514 | (1 << VCPU_EXREG_PDPTR)
6515 | (1 << VCPU_EXREG_SEGMENTS)
6516 | (1 << VCPU_EXREG_CR3));
6517 vcpu->arch.regs_dirty = 0;
6522 * eager fpu is enabled if PKEY is supported and CR4 is switched
6523 * back on host, so it is safe to read guest PKRU from current
6526 if (static_cpu_has(X86_FEATURE_PKU) &&
6527 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
6528 vcpu->arch.pkru = rdpkru();
6529 if (vcpu->arch.pkru != vmx->host_pkru)
6530 __write_pkru(vmx->host_pkru);
6533 kvm_put_guest_xcr0(vcpu);
6535 vmx->nested.nested_run_pending = 0;
6536 vmx->idt_vectoring_info = 0;
6538 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
6539 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6542 vmx->loaded_vmcs->launched = 1;
6543 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6545 vmx_complete_atomic_exit(vmx);
6546 vmx_recover_nmi_blocking(vmx);
6547 vmx_complete_interrupts(vmx);
6550 static struct kvm *vmx_vm_alloc(void)
6552 struct kvm_vmx *kvm_vmx = __vmalloc(sizeof(struct kvm_vmx),
6553 GFP_KERNEL_ACCOUNT | __GFP_ZERO,
6555 return &kvm_vmx->kvm;
6558 static void vmx_vm_free(struct kvm *kvm)
6560 vfree(to_kvm_vmx(kvm));
6563 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6565 struct vcpu_vmx *vmx = to_vmx(vcpu);
6568 vmx_destroy_pml_buffer(vmx);
6569 free_vpid(vmx->vpid);
6570 nested_vmx_free_vcpu(vcpu);
6571 free_loaded_vmcs(vmx->loaded_vmcs);
6572 kfree(vmx->guest_msrs);
6573 kvm_vcpu_uninit(vcpu);
6574 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6575 kmem_cache_free(kvm_vcpu_cache, vmx);
6578 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
6581 struct vcpu_vmx *vmx;
6582 unsigned long *msr_bitmap;
6585 vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
6587 return ERR_PTR(-ENOMEM);
6589 vmx->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
6590 GFP_KERNEL_ACCOUNT);
6591 if (!vmx->vcpu.arch.guest_fpu) {
6592 printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
6594 goto free_partial_vcpu;
6597 vmx->vpid = allocate_vpid();
6599 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
6606 * If PML is turned on, failure on enabling PML just results in failure
6607 * of creating the vcpu, therefore we can simplify PML logic (by
6608 * avoiding dealing with cases, such as enabling PML partially on vcpus
6609 * for the guest, etc.
6612 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6617 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
6618 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
6621 if (!vmx->guest_msrs)
6624 err = alloc_loaded_vmcs(&vmx->vmcs01);
6628 msr_bitmap = vmx->vmcs01.msr_bitmap;
6629 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6630 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6631 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6632 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6633 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6634 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6635 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6636 vmx->msr_bitmap_mode = 0;
6638 vmx->loaded_vmcs = &vmx->vmcs01;
6640 vmx_vcpu_load(&vmx->vcpu, cpu);
6641 vmx->vcpu.cpu = cpu;
6642 vmx_vcpu_setup(vmx);
6643 vmx_vcpu_put(&vmx->vcpu);
6645 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
6646 err = alloc_apic_access_page(kvm);
6651 if (enable_ept && !enable_unrestricted_guest) {
6652 err = init_rmode_identity_map(kvm);
6658 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
6660 kvm_vcpu_apicv_active(&vmx->vcpu));
6662 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6664 vmx->nested.posted_intr_nv = -1;
6665 vmx->nested.current_vmptr = -1ull;
6667 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
6670 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6671 * or POSTED_INTR_WAKEUP_VECTOR.
6673 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6674 vmx->pi_desc.sn = 1;
6676 vmx->ept_pointer = INVALID_PAGE;
6681 free_loaded_vmcs(vmx->loaded_vmcs);
6683 kfree(vmx->guest_msrs);
6685 vmx_destroy_pml_buffer(vmx);
6687 kvm_vcpu_uninit(&vmx->vcpu);
6689 free_vpid(vmx->vpid);
6690 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6692 kmem_cache_free(kvm_vcpu_cache, vmx);
6693 return ERR_PTR(err);
6696 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
6697 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
6699 static int vmx_vm_init(struct kvm *kvm)
6701 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
6704 kvm->arch.pause_in_guest = true;
6706 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6707 switch (l1tf_mitigation) {
6708 case L1TF_MITIGATION_OFF:
6709 case L1TF_MITIGATION_FLUSH_NOWARN:
6710 /* 'I explicitly don't care' is set */
6712 case L1TF_MITIGATION_FLUSH:
6713 case L1TF_MITIGATION_FLUSH_NOSMT:
6714 case L1TF_MITIGATION_FULL:
6716 * Warn upon starting the first VM in a potentially
6717 * insecure environment.
6719 if (sched_smt_active())
6720 pr_warn_once(L1TF_MSG_SMT);
6721 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6722 pr_warn_once(L1TF_MSG_L1D);
6724 case L1TF_MITIGATION_FULL_FORCE:
6725 /* Flush is enforced */
6732 static void __init vmx_check_processor_compat(void *rtn)
6734 struct vmcs_config vmcs_conf;
6735 struct vmx_capability vmx_cap;
6738 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
6741 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept,
6743 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6744 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6745 smp_processor_id());
6750 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6755 /* For VT-d and EPT combination
6756 * 1. MMIO: always map as UC
6758 * a. VT-d without snooping control feature: can't guarantee the
6759 * result, try to trust guest.
6760 * b. VT-d with snooping control feature: snooping control feature of
6761 * VT-d engine can guarantee the cache correctness. Just set it
6762 * to WB to keep consistent with host. So the same as item 3.
6763 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
6764 * consistent with host MTRR
6767 cache = MTRR_TYPE_UNCACHABLE;
6771 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
6772 ipat = VMX_EPT_IPAT_BIT;
6773 cache = MTRR_TYPE_WRBACK;
6777 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
6778 ipat = VMX_EPT_IPAT_BIT;
6779 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
6780 cache = MTRR_TYPE_WRBACK;
6782 cache = MTRR_TYPE_UNCACHABLE;
6786 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
6789 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
6792 static int vmx_get_lpage_level(void)
6794 if (enable_ept && !cpu_has_vmx_ept_1g_page())
6795 return PT_DIRECTORY_LEVEL;
6797 /* For shadow and EPT supported 1GB page */
6798 return PT_PDPE_LEVEL;
6801 static void vmcs_set_secondary_exec_control(u32 new_ctl)
6804 * These bits in the secondary execution controls field
6805 * are dynamic, the others are mostly based on the hypervisor
6806 * architecture and the guest's CPUID. Do not touch the
6810 SECONDARY_EXEC_SHADOW_VMCS |
6811 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
6812 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6813 SECONDARY_EXEC_DESC;
6815 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6817 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6818 (new_ctl & ~mask) | (cur_ctl & mask));
6822 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
6823 * (indicating "allowed-1") if they are supported in the guest's CPUID.
6825 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
6827 struct vcpu_vmx *vmx = to_vmx(vcpu);
6828 struct kvm_cpuid_entry2 *entry;
6830 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
6831 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
6833 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
6834 if (entry && (entry->_reg & (_cpuid_mask))) \
6835 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
6838 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
6839 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
6840 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
6841 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
6842 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
6843 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
6844 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
6845 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
6846 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
6847 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
6848 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
6849 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
6850 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
6851 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
6852 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
6854 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
6855 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
6856 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
6857 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
6858 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
6859 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
6861 #undef cr4_fixed1_update
6864 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
6866 struct vcpu_vmx *vmx = to_vmx(vcpu);
6868 if (kvm_mpx_supported()) {
6869 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
6872 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
6873 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
6875 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
6876 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
6881 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
6883 struct vcpu_vmx *vmx = to_vmx(vcpu);
6884 struct kvm_cpuid_entry2 *best = NULL;
6887 for (i = 0; i < PT_CPUID_LEAVES; i++) {
6888 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
6891 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
6892 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
6893 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
6894 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
6897 /* Get the number of configurable Address Ranges for filtering */
6898 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
6899 PT_CAP_num_address_ranges);
6901 /* Initialize and clear the no dependency bits */
6902 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
6903 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
6906 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
6907 * will inject an #GP
6909 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
6910 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
6913 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
6914 * PSBFreq can be set
6916 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
6917 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
6918 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
6921 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
6922 * MTCFreq can be set
6924 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
6925 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
6926 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
6928 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
6929 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
6930 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
6933 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
6934 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
6935 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
6937 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
6938 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
6939 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
6941 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
6942 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
6943 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
6945 /* unmask address range configure area */
6946 for (i = 0; i < vmx->pt_desc.addr_range; i++)
6947 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
6950 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
6952 struct vcpu_vmx *vmx = to_vmx(vcpu);
6954 if (cpu_has_secondary_exec_ctrls()) {
6955 vmx_compute_secondary_exec_control(vmx);
6956 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
6959 if (nested_vmx_allowed(vcpu))
6960 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
6961 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
6963 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
6964 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
6966 if (nested_vmx_allowed(vcpu)) {
6967 nested_vmx_cr_fixed1_bits_update(vcpu);
6968 nested_vmx_entry_exit_ctls_update(vcpu);
6971 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
6972 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
6973 update_intel_pt_cfg(vcpu);
6976 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
6978 if (func == 1 && nested)
6979 entry->ecx |= bit(X86_FEATURE_VMX);
6982 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
6984 to_vmx(vcpu)->req_immediate_exit = true;
6987 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
6988 struct x86_instruction_info *info,
6989 enum x86_intercept_stage stage)
6991 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6992 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
6995 * RDPID causes #UD if disabled through secondary execution controls.
6996 * Because it is marked as EmulateOnUD, we need to intercept it here.
6998 if (info->intercept == x86_intercept_rdtscp &&
6999 !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
7000 ctxt->exception.vector = UD_VECTOR;
7001 ctxt->exception.error_code_valid = false;
7002 return X86EMUL_PROPAGATE_FAULT;
7005 /* TODO: check more intercepts... */
7006 return X86EMUL_CONTINUE;
7009 #ifdef CONFIG_X86_64
7010 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7011 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7012 u64 divisor, u64 *result)
7014 u64 low = a << shift, high = a >> (64 - shift);
7016 /* To avoid the overflow on divq */
7017 if (high >= divisor)
7020 /* Low hold the result, high hold rem which is discarded */
7021 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7022 "rm" (divisor), "0" (low), "1" (high));
7028 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7031 struct vcpu_vmx *vmx;
7032 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7033 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7035 if (kvm_mwait_in_guest(vcpu->kvm))
7040 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7041 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7042 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7043 ktimer->timer_advance_ns);
7045 if (delta_tsc > lapic_timer_advance_cycles)
7046 delta_tsc -= lapic_timer_advance_cycles;
7050 /* Convert to host delta tsc if tsc scaling is enabled */
7051 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7052 delta_tsc && u64_shl_div_u64(delta_tsc,
7053 kvm_tsc_scaling_ratio_frac_bits,
7054 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7058 * If the delta tsc can't fit in the 32 bit after the multi shift,
7059 * we can't use the preemption timer.
7060 * It's possible that it fits on later vmentries, but checking
7061 * on every vmentry is costly so we just use an hrtimer.
7063 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7066 vmx->hv_deadline_tsc = tscl + delta_tsc;
7067 *expired = !delta_tsc;
7071 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7073 to_vmx(vcpu)->hv_deadline_tsc = -1;
7077 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7079 if (!kvm_pause_in_guest(vcpu->kvm))
7080 shrink_ple_window(vcpu);
7083 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7084 struct kvm_memory_slot *slot)
7086 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7087 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7090 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7091 struct kvm_memory_slot *slot)
7093 kvm_mmu_slot_set_dirty(kvm, slot);
7096 static void vmx_flush_log_dirty(struct kvm *kvm)
7098 kvm_flush_pml_buffers(kvm);
7101 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
7103 struct vmcs12 *vmcs12;
7104 struct vcpu_vmx *vmx = to_vmx(vcpu);
7107 if (is_guest_mode(vcpu)) {
7108 WARN_ON_ONCE(vmx->nested.pml_full);
7111 * Check if PML is enabled for the nested guest.
7112 * Whether eptp bit 6 is set is already checked
7113 * as part of A/D emulation.
7115 vmcs12 = get_vmcs12(vcpu);
7116 if (!nested_cpu_has_pml(vmcs12))
7119 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
7120 vmx->nested.pml_full = true;
7124 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
7125 dst = vmcs12->pml_address + sizeof(u64) * vmcs12->guest_pml_index;
7127 if (kvm_write_guest_page(vcpu->kvm, gpa_to_gfn(dst), &gpa,
7128 offset_in_page(dst), sizeof(gpa)))
7131 vmcs12->guest_pml_index--;
7137 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7138 struct kvm_memory_slot *memslot,
7139 gfn_t offset, unsigned long mask)
7141 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7144 static void __pi_post_block(struct kvm_vcpu *vcpu)
7146 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7147 struct pi_desc old, new;
7151 old.control = new.control = pi_desc->control;
7152 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
7153 "Wakeup handler not enabled while the VCPU is blocked\n");
7155 dest = cpu_physical_id(vcpu->cpu);
7157 if (x2apic_enabled())
7160 new.ndst = (dest << 8) & 0xFF00;
7162 /* set 'NV' to 'notification vector' */
7163 new.nv = POSTED_INTR_VECTOR;
7164 } while (cmpxchg64(&pi_desc->control, old.control,
7165 new.control) != old.control);
7167 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
7168 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7169 list_del(&vcpu->blocked_vcpu_list);
7170 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7171 vcpu->pre_pcpu = -1;
7176 * This routine does the following things for vCPU which is going
7177 * to be blocked if VT-d PI is enabled.
7178 * - Store the vCPU to the wakeup list, so when interrupts happen
7179 * we can find the right vCPU to wake up.
7180 * - Change the Posted-interrupt descriptor as below:
7181 * 'NDST' <-- vcpu->pre_pcpu
7182 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
7183 * - If 'ON' is set during this process, which means at least one
7184 * interrupt is posted for this vCPU, we cannot block it, in
7185 * this case, return 1, otherwise, return 0.
7188 static int pi_pre_block(struct kvm_vcpu *vcpu)
7191 struct pi_desc old, new;
7192 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7194 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
7195 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7196 !kvm_vcpu_apicv_active(vcpu))
7199 WARN_ON(irqs_disabled());
7200 local_irq_disable();
7201 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
7202 vcpu->pre_pcpu = vcpu->cpu;
7203 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7204 list_add_tail(&vcpu->blocked_vcpu_list,
7205 &per_cpu(blocked_vcpu_on_cpu,
7207 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7211 old.control = new.control = pi_desc->control;
7213 WARN((pi_desc->sn == 1),
7214 "Warning: SN field of posted-interrupts "
7215 "is set before blocking\n");
7218 * Since vCPU can be preempted during this process,
7219 * vcpu->cpu could be different with pre_pcpu, we
7220 * need to set pre_pcpu as the destination of wakeup
7221 * notification event, then we can find the right vCPU
7222 * to wakeup in wakeup handler if interrupts happen
7223 * when the vCPU is in blocked state.
7225 dest = cpu_physical_id(vcpu->pre_pcpu);
7227 if (x2apic_enabled())
7230 new.ndst = (dest << 8) & 0xFF00;
7232 /* set 'NV' to 'wakeup vector' */
7233 new.nv = POSTED_INTR_WAKEUP_VECTOR;
7234 } while (cmpxchg64(&pi_desc->control, old.control,
7235 new.control) != old.control);
7237 /* We should not block the vCPU if an interrupt is posted for it. */
7238 if (pi_test_on(pi_desc) == 1)
7239 __pi_post_block(vcpu);
7242 return (vcpu->pre_pcpu == -1);
7245 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7247 if (pi_pre_block(vcpu))
7250 if (kvm_lapic_hv_timer_in_use(vcpu))
7251 kvm_lapic_switch_to_sw_timer(vcpu);
7256 static void pi_post_block(struct kvm_vcpu *vcpu)
7258 if (vcpu->pre_pcpu == -1)
7261 WARN_ON(irqs_disabled());
7262 local_irq_disable();
7263 __pi_post_block(vcpu);
7267 static void vmx_post_block(struct kvm_vcpu *vcpu)
7269 if (kvm_x86_ops->set_hv_timer)
7270 kvm_lapic_switch_to_hv_timer(vcpu);
7272 pi_post_block(vcpu);
7276 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
7279 * @host_irq: host irq of the interrupt
7280 * @guest_irq: gsi of the interrupt
7281 * @set: set or unset PI
7282 * returns 0 on success, < 0 on failure
7284 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7285 uint32_t guest_irq, bool set)
7287 struct kvm_kernel_irq_routing_entry *e;
7288 struct kvm_irq_routing_table *irq_rt;
7289 struct kvm_lapic_irq irq;
7290 struct kvm_vcpu *vcpu;
7291 struct vcpu_data vcpu_info;
7294 if (!kvm_arch_has_assigned_device(kvm) ||
7295 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7296 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7299 idx = srcu_read_lock(&kvm->irq_srcu);
7300 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7301 if (guest_irq >= irq_rt->nr_rt_entries ||
7302 hlist_empty(&irq_rt->map[guest_irq])) {
7303 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7304 guest_irq, irq_rt->nr_rt_entries);
7308 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7309 if (e->type != KVM_IRQ_ROUTING_MSI)
7312 * VT-d PI cannot support posting multicast/broadcast
7313 * interrupts to a vCPU, we still use interrupt remapping
7314 * for these kind of interrupts.
7316 * For lowest-priority interrupts, we only support
7317 * those with single CPU as the destination, e.g. user
7318 * configures the interrupts via /proc/irq or uses
7319 * irqbalance to make the interrupts single-CPU.
7321 * We will support full lowest-priority interrupt later.
7324 kvm_set_msi_irq(kvm, e, &irq);
7325 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
7327 * Make sure the IRTE is in remapped mode if
7328 * we don't handle it in posted mode.
7330 ret = irq_set_vcpu_affinity(host_irq, NULL);
7333 "failed to back to remapped mode, irq: %u\n",
7341 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7342 vcpu_info.vector = irq.vector;
7344 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7345 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7348 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7350 ret = irq_set_vcpu_affinity(host_irq, NULL);
7353 printk(KERN_INFO "%s: failed to update PI IRTE\n",
7361 srcu_read_unlock(&kvm->irq_srcu, idx);
7365 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7367 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7368 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7369 FEATURE_CONTROL_LMCE;
7371 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7372 ~FEATURE_CONTROL_LMCE;
7375 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
7377 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7378 if (to_vmx(vcpu)->nested.nested_run_pending)
7383 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7385 struct vcpu_vmx *vmx = to_vmx(vcpu);
7387 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7388 if (vmx->nested.smm.guest_mode)
7389 nested_vmx_vmexit(vcpu, -1, 0, 0);
7391 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7392 vmx->nested.vmxon = false;
7393 vmx_clear_hlt(vcpu);
7397 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7399 struct vcpu_vmx *vmx = to_vmx(vcpu);
7402 if (vmx->nested.smm.vmxon) {
7403 vmx->nested.vmxon = true;
7404 vmx->nested.smm.vmxon = false;
7407 if (vmx->nested.smm.guest_mode) {
7408 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7412 vmx->nested.smm.guest_mode = false;
7417 static int enable_smi_window(struct kvm_vcpu *vcpu)
7422 static bool vmx_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7427 static __init int hardware_setup(void)
7429 unsigned long host_bndcfgs;
7432 rdmsrl_safe(MSR_EFER, &host_efer);
7434 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7435 kvm_define_shared_msr(i, vmx_msr_index[i]);
7437 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7440 if (boot_cpu_has(X86_FEATURE_NX))
7441 kvm_enable_efer_bits(EFER_NX);
7443 if (boot_cpu_has(X86_FEATURE_MPX)) {
7444 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7445 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7448 if (boot_cpu_has(X86_FEATURE_XSAVES))
7449 rdmsrl(MSR_IA32_XSS, host_xss);
7451 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7452 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7455 if (!cpu_has_vmx_ept() ||
7456 !cpu_has_vmx_ept_4levels() ||
7457 !cpu_has_vmx_ept_mt_wb() ||
7458 !cpu_has_vmx_invept_global())
7461 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7462 enable_ept_ad_bits = 0;
7464 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7465 enable_unrestricted_guest = 0;
7467 if (!cpu_has_vmx_flexpriority())
7468 flexpriority_enabled = 0;
7470 if (!cpu_has_virtual_nmis())
7474 * set_apic_access_page_addr() is used to reload apic access
7475 * page upon invalidation. No need to do anything if not
7476 * using the APIC_ACCESS_ADDR VMCS field.
7478 if (!flexpriority_enabled)
7479 kvm_x86_ops->set_apic_access_page_addr = NULL;
7481 if (!cpu_has_vmx_tpr_shadow())
7482 kvm_x86_ops->update_cr8_intercept = NULL;
7484 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7485 kvm_disable_largepages();
7487 #if IS_ENABLED(CONFIG_HYPERV)
7488 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7490 kvm_x86_ops->tlb_remote_flush = hv_remote_flush_tlb;
7491 kvm_x86_ops->tlb_remote_flush_with_range =
7492 hv_remote_flush_tlb_with_range;
7496 if (!cpu_has_vmx_ple()) {
7499 ple_window_grow = 0;
7501 ple_window_shrink = 0;
7504 if (!cpu_has_vmx_apicv()) {
7506 kvm_x86_ops->sync_pir_to_irr = NULL;
7509 if (cpu_has_vmx_tsc_scaling()) {
7510 kvm_has_tsc_control = true;
7511 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7512 kvm_tsc_scaling_ratio_frac_bits = 48;
7515 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7523 * Only enable PML when hardware supports PML feature, and both EPT
7524 * and EPT A/D bit features are enabled -- PML depends on them to work.
7526 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7530 kvm_x86_ops->slot_enable_log_dirty = NULL;
7531 kvm_x86_ops->slot_disable_log_dirty = NULL;
7532 kvm_x86_ops->flush_log_dirty = NULL;
7533 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7536 if (!cpu_has_vmx_preemption_timer())
7537 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7539 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7542 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7543 cpu_preemption_timer_multi =
7544 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7546 kvm_x86_ops->set_hv_timer = NULL;
7547 kvm_x86_ops->cancel_hv_timer = NULL;
7550 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7552 kvm_mce_cap_supported |= MCG_LMCE_P;
7554 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7556 if (!enable_ept || !cpu_has_vmx_intel_pt())
7557 pt_mode = PT_MODE_SYSTEM;
7560 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7561 vmx_capability.ept, enable_apicv);
7563 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7568 r = alloc_kvm_area();
7570 nested_vmx_hardware_unsetup();
7574 static __exit void hardware_unsetup(void)
7577 nested_vmx_hardware_unsetup();
7582 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
7583 .cpu_has_kvm_support = cpu_has_kvm_support,
7584 .disabled_by_bios = vmx_disabled_by_bios,
7585 .hardware_setup = hardware_setup,
7586 .hardware_unsetup = hardware_unsetup,
7587 .check_processor_compatibility = vmx_check_processor_compat,
7588 .hardware_enable = hardware_enable,
7589 .hardware_disable = hardware_disable,
7590 .cpu_has_accelerated_tpr = report_flexpriority,
7591 .has_emulated_msr = vmx_has_emulated_msr,
7593 .vm_init = vmx_vm_init,
7594 .vm_alloc = vmx_vm_alloc,
7595 .vm_free = vmx_vm_free,
7597 .vcpu_create = vmx_create_vcpu,
7598 .vcpu_free = vmx_free_vcpu,
7599 .vcpu_reset = vmx_vcpu_reset,
7601 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7602 .vcpu_load = vmx_vcpu_load,
7603 .vcpu_put = vmx_vcpu_put,
7605 .update_bp_intercept = update_exception_bitmap,
7606 .get_msr_feature = vmx_get_msr_feature,
7607 .get_msr = vmx_get_msr,
7608 .set_msr = vmx_set_msr,
7609 .get_segment_base = vmx_get_segment_base,
7610 .get_segment = vmx_get_segment,
7611 .set_segment = vmx_set_segment,
7612 .get_cpl = vmx_get_cpl,
7613 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7614 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
7615 .decache_cr3 = vmx_decache_cr3,
7616 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
7617 .set_cr0 = vmx_set_cr0,
7618 .set_cr3 = vmx_set_cr3,
7619 .set_cr4 = vmx_set_cr4,
7620 .set_efer = vmx_set_efer,
7621 .get_idt = vmx_get_idt,
7622 .set_idt = vmx_set_idt,
7623 .get_gdt = vmx_get_gdt,
7624 .set_gdt = vmx_set_gdt,
7625 .get_dr6 = vmx_get_dr6,
7626 .set_dr6 = vmx_set_dr6,
7627 .set_dr7 = vmx_set_dr7,
7628 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7629 .cache_reg = vmx_cache_reg,
7630 .get_rflags = vmx_get_rflags,
7631 .set_rflags = vmx_set_rflags,
7633 .tlb_flush = vmx_flush_tlb,
7634 .tlb_flush_gva = vmx_flush_tlb_gva,
7636 .run = vmx_vcpu_run,
7637 .handle_exit = vmx_handle_exit,
7638 .skip_emulated_instruction = skip_emulated_instruction,
7639 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7640 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7641 .patch_hypercall = vmx_patch_hypercall,
7642 .set_irq = vmx_inject_irq,
7643 .set_nmi = vmx_inject_nmi,
7644 .queue_exception = vmx_queue_exception,
7645 .cancel_injection = vmx_cancel_injection,
7646 .interrupt_allowed = vmx_interrupt_allowed,
7647 .nmi_allowed = vmx_nmi_allowed,
7648 .get_nmi_mask = vmx_get_nmi_mask,
7649 .set_nmi_mask = vmx_set_nmi_mask,
7650 .enable_nmi_window = enable_nmi_window,
7651 .enable_irq_window = enable_irq_window,
7652 .update_cr8_intercept = update_cr8_intercept,
7653 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7654 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7655 .get_enable_apicv = vmx_get_enable_apicv,
7656 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7657 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7658 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7659 .hwapic_irr_update = vmx_hwapic_irr_update,
7660 .hwapic_isr_update = vmx_hwapic_isr_update,
7661 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7662 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7663 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7665 .set_tss_addr = vmx_set_tss_addr,
7666 .set_identity_map_addr = vmx_set_identity_map_addr,
7667 .get_tdp_level = get_ept_level,
7668 .get_mt_mask = vmx_get_mt_mask,
7670 .get_exit_info = vmx_get_exit_info,
7672 .get_lpage_level = vmx_get_lpage_level,
7674 .cpuid_update = vmx_cpuid_update,
7676 .rdtscp_supported = vmx_rdtscp_supported,
7677 .invpcid_supported = vmx_invpcid_supported,
7679 .set_supported_cpuid = vmx_set_supported_cpuid,
7681 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7683 .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
7684 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7686 .set_tdp_cr3 = vmx_set_cr3,
7688 .check_intercept = vmx_check_intercept,
7689 .handle_external_intr = vmx_handle_external_intr,
7690 .mpx_supported = vmx_mpx_supported,
7691 .xsaves_supported = vmx_xsaves_supported,
7692 .umip_emulated = vmx_umip_emulated,
7693 .pt_supported = vmx_pt_supported,
7695 .request_immediate_exit = vmx_request_immediate_exit,
7697 .sched_in = vmx_sched_in,
7699 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7700 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7701 .flush_log_dirty = vmx_flush_log_dirty,
7702 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7703 .write_log_dirty = vmx_write_pml_buffer,
7705 .pre_block = vmx_pre_block,
7706 .post_block = vmx_post_block,
7708 .pmu_ops = &intel_pmu_ops,
7710 .update_pi_irte = vmx_update_pi_irte,
7712 #ifdef CONFIG_X86_64
7713 .set_hv_timer = vmx_set_hv_timer,
7714 .cancel_hv_timer = vmx_cancel_hv_timer,
7717 .setup_mce = vmx_setup_mce,
7719 .smi_allowed = vmx_smi_allowed,
7720 .pre_enter_smm = vmx_pre_enter_smm,
7721 .pre_leave_smm = vmx_pre_leave_smm,
7722 .enable_smi_window = enable_smi_window,
7724 .check_nested_events = NULL,
7725 .get_nested_state = NULL,
7726 .set_nested_state = NULL,
7727 .get_vmcs12_pages = NULL,
7728 .nested_enable_evmcs = NULL,
7729 .need_emulation_on_page_fault = vmx_need_emulation_on_page_fault,
7732 static void vmx_cleanup_l1d_flush(void)
7734 if (vmx_l1d_flush_pages) {
7735 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7736 vmx_l1d_flush_pages = NULL;
7738 /* Restore state so sysfs ignores VMX */
7739 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
7742 static void vmx_exit(void)
7744 #ifdef CONFIG_KEXEC_CORE
7745 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
7751 #if IS_ENABLED(CONFIG_HYPERV)
7752 if (static_branch_unlikely(&enable_evmcs)) {
7754 struct hv_vp_assist_page *vp_ap;
7756 * Reset everything to support using non-enlightened VMCS
7757 * access later (e.g. when we reload the module with
7758 * enlightened_vmcs=0)
7760 for_each_online_cpu(cpu) {
7761 vp_ap = hv_get_vp_assist_page(cpu);
7766 vp_ap->current_nested_vmcs = 0;
7767 vp_ap->enlighten_vmentry = 0;
7770 static_branch_disable(&enable_evmcs);
7773 vmx_cleanup_l1d_flush();
7775 module_exit(vmx_exit);
7777 static int __init vmx_init(void)
7781 #if IS_ENABLED(CONFIG_HYPERV)
7783 * Enlightened VMCS usage should be recommended and the host needs
7784 * to support eVMCS v1 or above. We can also disable eVMCS support
7785 * with module parameter.
7787 if (enlightened_vmcs &&
7788 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
7789 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
7790 KVM_EVMCS_VERSION) {
7793 /* Check that we have assist pages on all online CPUs */
7794 for_each_online_cpu(cpu) {
7795 if (!hv_get_vp_assist_page(cpu)) {
7796 enlightened_vmcs = false;
7801 if (enlightened_vmcs) {
7802 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
7803 static_branch_enable(&enable_evmcs);
7806 enlightened_vmcs = false;
7810 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
7811 __alignof__(struct vcpu_vmx), THIS_MODULE);
7816 * Must be called after kvm_init() so enable_ept is properly set
7817 * up. Hand the parameter mitigation value in which was stored in
7818 * the pre module init parser. If no parameter was given, it will
7819 * contain 'auto' which will be turned into the default 'cond'
7822 if (boot_cpu_has(X86_BUG_L1TF)) {
7823 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
7830 #ifdef CONFIG_KEXEC_CORE
7831 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
7832 crash_vmclear_local_loaded_vmcss);
7834 vmx_check_vmcs12_offsets();
7838 module_init(vmx_init);