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 #define MSR_BITMAP_MODE_X2APIC 1
118 #define MSR_BITMAP_MODE_X2APIC_APICV 2
120 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
122 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
123 static int __read_mostly cpu_preemption_timer_multi;
124 static bool __read_mostly enable_preemption_timer = 1;
126 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
129 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
130 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
131 #define KVM_VM_CR0_ALWAYS_ON \
132 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
133 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
134 #define KVM_CR4_GUEST_OWNED_BITS \
135 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
136 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
138 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
139 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
140 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
142 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
144 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
145 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
146 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
147 RTIT_STATUS_BYTECNT))
149 #define MSR_IA32_RTIT_OUTPUT_BASE_MASK \
150 (~((1UL << cpuid_query_maxphyaddr(vcpu)) - 1) | 0x7f)
153 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
154 * ple_gap: upper bound on the amount of time between two successive
155 * executions of PAUSE in a loop. Also indicate if ple enabled.
156 * According to test, this time is usually smaller than 128 cycles.
157 * ple_window: upper bound on the amount of time a guest is allowed to execute
158 * in a PAUSE loop. Tests indicate that most spinlocks are held for
159 * less than 2^12 cycles
160 * Time is measured based on a counter that runs at the same rate as the TSC,
161 * refer SDM volume 3b section 21.6.13 & 22.1.3.
163 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
164 module_param(ple_gap, uint, 0444);
166 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
167 module_param(ple_window, uint, 0444);
169 /* Default doubles per-vcpu window every exit. */
170 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
171 module_param(ple_window_grow, uint, 0444);
173 /* Default resets per-vcpu window every exit to ple_window. */
174 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
175 module_param(ple_window_shrink, uint, 0444);
177 /* Default is to compute the maximum so we can never overflow. */
178 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
179 module_param(ple_window_max, uint, 0444);
181 /* Default is SYSTEM mode, 1 for host-guest mode */
182 int __read_mostly pt_mode = PT_MODE_SYSTEM;
183 module_param(pt_mode, int, S_IRUGO);
185 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
186 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
187 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
189 /* Storage for pre module init parameter parsing */
190 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
192 static const struct {
195 } vmentry_l1d_param[] = {
196 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
197 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
198 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
199 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
200 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
201 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
204 #define L1D_CACHE_ORDER 4
205 static void *vmx_l1d_flush_pages;
207 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
213 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
217 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
220 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
221 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
222 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
227 /* If set to auto use the default l1tf mitigation method */
228 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
229 switch (l1tf_mitigation) {
230 case L1TF_MITIGATION_OFF:
231 l1tf = VMENTER_L1D_FLUSH_NEVER;
233 case L1TF_MITIGATION_FLUSH_NOWARN:
234 case L1TF_MITIGATION_FLUSH:
235 case L1TF_MITIGATION_FLUSH_NOSMT:
236 l1tf = VMENTER_L1D_FLUSH_COND;
238 case L1TF_MITIGATION_FULL:
239 case L1TF_MITIGATION_FULL_FORCE:
240 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
243 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
244 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
247 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
248 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
249 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
252 vmx_l1d_flush_pages = page_address(page);
255 * Initialize each page with a different pattern in
256 * order to protect against KSM in the nested
257 * virtualization case.
259 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
260 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
265 l1tf_vmx_mitigation = l1tf;
267 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
268 static_branch_enable(&vmx_l1d_should_flush);
270 static_branch_disable(&vmx_l1d_should_flush);
272 if (l1tf == VMENTER_L1D_FLUSH_COND)
273 static_branch_enable(&vmx_l1d_flush_cond);
275 static_branch_disable(&vmx_l1d_flush_cond);
279 static int vmentry_l1d_flush_parse(const char *s)
284 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
285 if (vmentry_l1d_param[i].for_parse &&
286 sysfs_streq(s, vmentry_l1d_param[i].option))
293 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
297 l1tf = vmentry_l1d_flush_parse(s);
301 if (!boot_cpu_has(X86_BUG_L1TF))
305 * Has vmx_init() run already? If not then this is the pre init
306 * parameter parsing. In that case just store the value and let
307 * vmx_init() do the proper setup after enable_ept has been
310 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
311 vmentry_l1d_flush_param = l1tf;
315 mutex_lock(&vmx_l1d_flush_mutex);
316 ret = vmx_setup_l1d_flush(l1tf);
317 mutex_unlock(&vmx_l1d_flush_mutex);
321 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
323 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
324 return sprintf(s, "???\n");
326 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
329 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
330 .set = vmentry_l1d_flush_set,
331 .get = vmentry_l1d_flush_get,
333 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
335 static bool guest_state_valid(struct kvm_vcpu *vcpu);
336 static u32 vmx_segment_access_rights(struct kvm_segment *var);
337 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
340 void vmx_vmexit(void);
342 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
343 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
345 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
346 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
348 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
351 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
352 * can find which vCPU should be waken up.
354 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
355 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
357 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
358 static DEFINE_SPINLOCK(vmx_vpid_lock);
360 struct vmcs_config vmcs_config;
361 struct vmx_capability vmx_capability;
363 #define VMX_SEGMENT_FIELD(seg) \
364 [VCPU_SREG_##seg] = { \
365 .selector = GUEST_##seg##_SELECTOR, \
366 .base = GUEST_##seg##_BASE, \
367 .limit = GUEST_##seg##_LIMIT, \
368 .ar_bytes = GUEST_##seg##_AR_BYTES, \
371 static const struct kvm_vmx_segment_field {
376 } kvm_vmx_segment_fields[] = {
377 VMX_SEGMENT_FIELD(CS),
378 VMX_SEGMENT_FIELD(DS),
379 VMX_SEGMENT_FIELD(ES),
380 VMX_SEGMENT_FIELD(FS),
381 VMX_SEGMENT_FIELD(GS),
382 VMX_SEGMENT_FIELD(SS),
383 VMX_SEGMENT_FIELD(TR),
384 VMX_SEGMENT_FIELD(LDTR),
390 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
391 * will emulate SYSCALL in legacy mode if the vendor string in guest
392 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
393 * support this emulation, IA32_STAR must always be included in
394 * vmx_msr_index[], even in i386 builds.
396 const u32 vmx_msr_index[] = {
398 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
400 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
403 #if IS_ENABLED(CONFIG_HYPERV)
404 static bool __read_mostly enlightened_vmcs = true;
405 module_param(enlightened_vmcs, bool, 0444);
407 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
408 static void check_ept_pointer_match(struct kvm *kvm)
410 struct kvm_vcpu *vcpu;
411 u64 tmp_eptp = INVALID_PAGE;
414 kvm_for_each_vcpu(i, vcpu, kvm) {
415 if (!VALID_PAGE(tmp_eptp)) {
416 tmp_eptp = to_vmx(vcpu)->ept_pointer;
417 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
418 to_kvm_vmx(kvm)->ept_pointers_match
419 = EPT_POINTERS_MISMATCH;
424 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
427 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
430 struct kvm_tlb_range *range = data;
432 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
436 static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
437 struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
439 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
442 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
443 * of the base of EPT PML4 table, strip off EPT configuration
447 return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
448 kvm_fill_hv_flush_list_func, (void *)range);
450 return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
453 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
454 struct kvm_tlb_range *range)
456 struct kvm_vcpu *vcpu;
459 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
461 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
462 check_ept_pointer_match(kvm);
464 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
465 kvm_for_each_vcpu(i, vcpu, kvm) {
466 /* If ept_pointer is invalid pointer, bypass flush request. */
467 if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
468 ret |= __hv_remote_flush_tlb_with_range(
472 ret = __hv_remote_flush_tlb_with_range(kvm,
473 kvm_get_vcpu(kvm, 0), range);
476 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
479 static int hv_remote_flush_tlb(struct kvm *kvm)
481 return hv_remote_flush_tlb_with_range(kvm, NULL);
484 #endif /* IS_ENABLED(CONFIG_HYPERV) */
487 * Comment's format: document - errata name - stepping - processor name.
489 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
491 static u32 vmx_preemption_cpu_tfms[] = {
492 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
494 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
495 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
496 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
498 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
500 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
501 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
503 * 320767.pdf - AAP86 - B1 -
504 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
507 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
509 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
511 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
513 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
514 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
515 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
517 /* Xeon E3-1220 V2 */
521 static inline bool cpu_has_broken_vmx_preemption_timer(void)
523 u32 eax = cpuid_eax(0x00000001), i;
525 /* Clear the reserved bits */
526 eax &= ~(0x3U << 14 | 0xfU << 28);
527 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
528 if (eax == vmx_preemption_cpu_tfms[i])
534 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
536 return flexpriority_enabled && lapic_in_kernel(vcpu);
539 static inline bool report_flexpriority(void)
541 return flexpriority_enabled;
544 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
548 for (i = 0; i < vmx->nmsrs; ++i)
549 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
554 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
558 i = __find_msr_index(vmx, msr);
560 return &vmx->guest_msrs[i];
564 void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
566 vmcs_clear(loaded_vmcs->vmcs);
567 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
568 vmcs_clear(loaded_vmcs->shadow_vmcs);
569 loaded_vmcs->cpu = -1;
570 loaded_vmcs->launched = 0;
573 #ifdef CONFIG_KEXEC_CORE
575 * This bitmap is used to indicate whether the vmclear
576 * operation is enabled on all cpus. All disabled by
579 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
581 static inline void crash_enable_local_vmclear(int cpu)
583 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
586 static inline void crash_disable_local_vmclear(int cpu)
588 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
591 static inline int crash_local_vmclear_enabled(int cpu)
593 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
596 static void crash_vmclear_local_loaded_vmcss(void)
598 int cpu = raw_smp_processor_id();
599 struct loaded_vmcs *v;
601 if (!crash_local_vmclear_enabled(cpu))
604 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
605 loaded_vmcss_on_cpu_link)
609 static inline void crash_enable_local_vmclear(int cpu) { }
610 static inline void crash_disable_local_vmclear(int cpu) { }
611 #endif /* CONFIG_KEXEC_CORE */
613 static void __loaded_vmcs_clear(void *arg)
615 struct loaded_vmcs *loaded_vmcs = arg;
616 int cpu = raw_smp_processor_id();
618 if (loaded_vmcs->cpu != cpu)
619 return; /* vcpu migration can race with cpu offline */
620 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
621 per_cpu(current_vmcs, cpu) = NULL;
622 crash_disable_local_vmclear(cpu);
623 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
626 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
627 * is before setting loaded_vmcs->vcpu to -1 which is done in
628 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
629 * then adds the vmcs into percpu list before it is deleted.
633 loaded_vmcs_init(loaded_vmcs);
634 crash_enable_local_vmclear(cpu);
637 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
639 int cpu = loaded_vmcs->cpu;
642 smp_call_function_single(cpu,
643 __loaded_vmcs_clear, loaded_vmcs, 1);
646 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
650 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
652 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
653 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
654 vmx->segment_cache.bitmask = 0;
656 ret = vmx->segment_cache.bitmask & mask;
657 vmx->segment_cache.bitmask |= mask;
661 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
663 u16 *p = &vmx->segment_cache.seg[seg].selector;
665 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
666 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
670 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
672 ulong *p = &vmx->segment_cache.seg[seg].base;
674 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
675 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
679 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
681 u32 *p = &vmx->segment_cache.seg[seg].limit;
683 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
684 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
688 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
690 u32 *p = &vmx->segment_cache.seg[seg].ar;
692 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
693 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
697 void update_exception_bitmap(struct kvm_vcpu *vcpu)
701 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
702 (1u << DB_VECTOR) | (1u << AC_VECTOR);
704 * Guest access to VMware backdoor ports could legitimately
705 * trigger #GP because of TSS I/O permission bitmap.
706 * We intercept those #GP and allow access to them anyway
709 if (enable_vmware_backdoor)
710 eb |= (1u << GP_VECTOR);
711 if ((vcpu->guest_debug &
712 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
713 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
714 eb |= 1u << BP_VECTOR;
715 if (to_vmx(vcpu)->rmode.vm86_active)
718 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
720 /* When we are running a nested L2 guest and L1 specified for it a
721 * certain exception bitmap, we must trap the same exceptions and pass
722 * them to L1. When running L2, we will only handle the exceptions
723 * specified above if L1 did not want them.
725 if (is_guest_mode(vcpu))
726 eb |= get_vmcs12(vcpu)->exception_bitmap;
728 vmcs_write32(EXCEPTION_BITMAP, eb);
732 * Check if MSR is intercepted for currently loaded MSR bitmap.
734 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
736 unsigned long *msr_bitmap;
737 int f = sizeof(unsigned long);
739 if (!cpu_has_vmx_msr_bitmap())
742 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
745 return !!test_bit(msr, msr_bitmap + 0x800 / f);
746 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
748 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
754 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
755 unsigned long entry, unsigned long exit)
757 vm_entry_controls_clearbit(vmx, entry);
758 vm_exit_controls_clearbit(vmx, exit);
761 static int find_msr(struct vmx_msrs *m, unsigned int msr)
765 for (i = 0; i < m->nr; ++i) {
766 if (m->val[i].index == msr)
772 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
775 struct msr_autoload *m = &vmx->msr_autoload;
779 if (cpu_has_load_ia32_efer()) {
780 clear_atomic_switch_msr_special(vmx,
781 VM_ENTRY_LOAD_IA32_EFER,
782 VM_EXIT_LOAD_IA32_EFER);
786 case MSR_CORE_PERF_GLOBAL_CTRL:
787 if (cpu_has_load_perf_global_ctrl()) {
788 clear_atomic_switch_msr_special(vmx,
789 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
790 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
795 i = find_msr(&m->guest, msr);
799 m->guest.val[i] = m->guest.val[m->guest.nr];
800 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
803 i = find_msr(&m->host, msr);
808 m->host.val[i] = m->host.val[m->host.nr];
809 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
812 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
813 unsigned long entry, unsigned long exit,
814 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
815 u64 guest_val, u64 host_val)
817 vmcs_write64(guest_val_vmcs, guest_val);
818 if (host_val_vmcs != HOST_IA32_EFER)
819 vmcs_write64(host_val_vmcs, host_val);
820 vm_entry_controls_setbit(vmx, entry);
821 vm_exit_controls_setbit(vmx, exit);
824 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
825 u64 guest_val, u64 host_val, bool entry_only)
828 struct msr_autoload *m = &vmx->msr_autoload;
832 if (cpu_has_load_ia32_efer()) {
833 add_atomic_switch_msr_special(vmx,
834 VM_ENTRY_LOAD_IA32_EFER,
835 VM_EXIT_LOAD_IA32_EFER,
838 guest_val, host_val);
842 case MSR_CORE_PERF_GLOBAL_CTRL:
843 if (cpu_has_load_perf_global_ctrl()) {
844 add_atomic_switch_msr_special(vmx,
845 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
846 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
847 GUEST_IA32_PERF_GLOBAL_CTRL,
848 HOST_IA32_PERF_GLOBAL_CTRL,
849 guest_val, host_val);
853 case MSR_IA32_PEBS_ENABLE:
854 /* PEBS needs a quiescent period after being disabled (to write
855 * a record). Disabling PEBS through VMX MSR swapping doesn't
856 * provide that period, so a CPU could write host's record into
859 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
862 i = find_msr(&m->guest, msr);
864 j = find_msr(&m->host, msr);
866 if (i == NR_AUTOLOAD_MSRS || j == NR_AUTOLOAD_MSRS) {
867 printk_once(KERN_WARNING "Not enough msr switch entries. "
868 "Can't add msr %x\n", msr);
873 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
875 m->guest.val[i].index = msr;
876 m->guest.val[i].value = guest_val;
883 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
885 m->host.val[j].index = msr;
886 m->host.val[j].value = host_val;
889 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
891 u64 guest_efer = vmx->vcpu.arch.efer;
896 * NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
897 * host CPUID is more efficient than testing guest CPUID
898 * or CR4. Host SMEP is anyway a requirement for guest SMEP.
900 if (boot_cpu_has(X86_FEATURE_SMEP))
901 guest_efer |= EFER_NX;
902 else if (!(guest_efer & EFER_NX))
903 ignore_bits |= EFER_NX;
907 * LMA and LME handled by hardware; SCE meaningless outside long mode.
909 ignore_bits |= EFER_SCE;
911 ignore_bits |= EFER_LMA | EFER_LME;
912 /* SCE is meaningful only in long mode on Intel */
913 if (guest_efer & EFER_LMA)
914 ignore_bits &= ~(u64)EFER_SCE;
918 * On EPT, we can't emulate NX, so we must switch EFER atomically.
919 * On CPUs that support "load IA32_EFER", always switch EFER
920 * atomically, since it's faster than switching it manually.
922 if (cpu_has_load_ia32_efer() ||
923 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
924 if (!(guest_efer & EFER_LMA))
925 guest_efer &= ~EFER_LME;
926 if (guest_efer != host_efer)
927 add_atomic_switch_msr(vmx, MSR_EFER,
928 guest_efer, host_efer, false);
930 clear_atomic_switch_msr(vmx, MSR_EFER);
933 clear_atomic_switch_msr(vmx, MSR_EFER);
935 guest_efer &= ~ignore_bits;
936 guest_efer |= host_efer & ignore_bits;
938 vmx->guest_msrs[efer_offset].data = guest_efer;
939 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
947 * On 32-bit kernels, VM exits still load the FS and GS bases from the
948 * VMCS rather than the segment table. KVM uses this helper to figure
949 * out the current bases to poke them into the VMCS before entry.
951 static unsigned long segment_base(u16 selector)
953 struct desc_struct *table;
956 if (!(selector & ~SEGMENT_RPL_MASK))
959 table = get_current_gdt_ro();
961 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
962 u16 ldt_selector = kvm_read_ldt();
964 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
967 table = (struct desc_struct *)segment_base(ldt_selector);
969 v = get_desc_base(&table[selector >> 3]);
974 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
978 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
979 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
980 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
981 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
982 for (i = 0; i < addr_range; i++) {
983 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
984 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
988 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
992 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
993 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
994 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
995 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
996 for (i = 0; i < addr_range; i++) {
997 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
998 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1002 static void pt_guest_enter(struct vcpu_vmx *vmx)
1004 if (pt_mode == PT_MODE_SYSTEM)
1008 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1009 * Save host state before VM entry.
1011 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1012 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1013 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1014 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1015 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1019 static void pt_guest_exit(struct vcpu_vmx *vmx)
1021 if (pt_mode == PT_MODE_SYSTEM)
1024 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1025 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1026 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1029 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1030 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1033 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1035 struct vcpu_vmx *vmx = to_vmx(vcpu);
1036 struct vmcs_host_state *host_state;
1037 #ifdef CONFIG_X86_64
1038 int cpu = raw_smp_processor_id();
1040 unsigned long fs_base, gs_base;
1044 vmx->req_immediate_exit = false;
1047 * Note that guest MSRs to be saved/restored can also be changed
1048 * when guest state is loaded. This happens when guest transitions
1049 * to/from long-mode by setting MSR_EFER.LMA.
1051 if (!vmx->loaded_cpu_state || vmx->guest_msrs_dirty) {
1052 vmx->guest_msrs_dirty = false;
1053 for (i = 0; i < vmx->save_nmsrs; ++i)
1054 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1055 vmx->guest_msrs[i].data,
1056 vmx->guest_msrs[i].mask);
1060 if (vmx->loaded_cpu_state)
1063 vmx->loaded_cpu_state = vmx->loaded_vmcs;
1064 host_state = &vmx->loaded_cpu_state->host_state;
1067 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1068 * allow segment selectors with cpl > 0 or ti == 1.
1070 host_state->ldt_sel = kvm_read_ldt();
1072 #ifdef CONFIG_X86_64
1073 savesegment(ds, host_state->ds_sel);
1074 savesegment(es, host_state->es_sel);
1076 gs_base = cpu_kernelmode_gs_base(cpu);
1077 if (likely(is_64bit_mm(current->mm))) {
1078 save_fsgs_for_kvm();
1079 fs_sel = current->thread.fsindex;
1080 gs_sel = current->thread.gsindex;
1081 fs_base = current->thread.fsbase;
1082 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1084 savesegment(fs, fs_sel);
1085 savesegment(gs, gs_sel);
1086 fs_base = read_msr(MSR_FS_BASE);
1087 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1090 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1092 savesegment(fs, fs_sel);
1093 savesegment(gs, gs_sel);
1094 fs_base = segment_base(fs_sel);
1095 gs_base = segment_base(gs_sel);
1098 if (unlikely(fs_sel != host_state->fs_sel)) {
1100 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1102 vmcs_write16(HOST_FS_SELECTOR, 0);
1103 host_state->fs_sel = fs_sel;
1105 if (unlikely(gs_sel != host_state->gs_sel)) {
1107 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1109 vmcs_write16(HOST_GS_SELECTOR, 0);
1110 host_state->gs_sel = gs_sel;
1112 if (unlikely(fs_base != host_state->fs_base)) {
1113 vmcs_writel(HOST_FS_BASE, fs_base);
1114 host_state->fs_base = fs_base;
1116 if (unlikely(gs_base != host_state->gs_base)) {
1117 vmcs_writel(HOST_GS_BASE, gs_base);
1118 host_state->gs_base = gs_base;
1122 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1124 struct vmcs_host_state *host_state;
1126 if (!vmx->loaded_cpu_state)
1129 WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
1130 host_state = &vmx->loaded_cpu_state->host_state;
1132 ++vmx->vcpu.stat.host_state_reload;
1133 vmx->loaded_cpu_state = NULL;
1135 #ifdef CONFIG_X86_64
1136 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1138 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1139 kvm_load_ldt(host_state->ldt_sel);
1140 #ifdef CONFIG_X86_64
1141 load_gs_index(host_state->gs_sel);
1143 loadsegment(gs, host_state->gs_sel);
1146 if (host_state->fs_sel & 7)
1147 loadsegment(fs, host_state->fs_sel);
1148 #ifdef CONFIG_X86_64
1149 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1150 loadsegment(ds, host_state->ds_sel);
1151 loadsegment(es, host_state->es_sel);
1154 invalidate_tss_limit();
1155 #ifdef CONFIG_X86_64
1156 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1158 load_fixmap_gdt(raw_smp_processor_id());
1161 #ifdef CONFIG_X86_64
1162 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1165 if (vmx->loaded_cpu_state)
1166 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1168 return vmx->msr_guest_kernel_gs_base;
1171 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1174 if (vmx->loaded_cpu_state)
1175 wrmsrl(MSR_KERNEL_GS_BASE, data);
1177 vmx->msr_guest_kernel_gs_base = data;
1181 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1183 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1184 struct pi_desc old, new;
1188 * In case of hot-plug or hot-unplug, we may have to undo
1189 * vmx_vcpu_pi_put even if there is no assigned device. And we
1190 * always keep PI.NDST up to date for simplicity: it makes the
1191 * code easier, and CPU migration is not a fast path.
1193 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1197 * First handle the simple case where no cmpxchg is necessary; just
1198 * allow posting non-urgent interrupts.
1200 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
1201 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
1202 * expects the VCPU to be on the blocked_vcpu_list that matches
1205 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
1207 pi_clear_sn(pi_desc);
1211 /* The full case. */
1213 old.control = new.control = pi_desc->control;
1215 dest = cpu_physical_id(cpu);
1217 if (x2apic_enabled())
1220 new.ndst = (dest << 8) & 0xFF00;
1223 } while (cmpxchg64(&pi_desc->control, old.control,
1224 new.control) != old.control);
1228 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1229 * vcpu mutex is already taken.
1231 void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1233 struct vcpu_vmx *vmx = to_vmx(vcpu);
1234 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1236 if (!already_loaded) {
1237 loaded_vmcs_clear(vmx->loaded_vmcs);
1238 local_irq_disable();
1239 crash_disable_local_vmclear(cpu);
1242 * Read loaded_vmcs->cpu should be before fetching
1243 * loaded_vmcs->loaded_vmcss_on_cpu_link.
1244 * See the comments in __loaded_vmcs_clear().
1248 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1249 &per_cpu(loaded_vmcss_on_cpu, cpu));
1250 crash_enable_local_vmclear(cpu);
1254 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1255 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1256 vmcs_load(vmx->loaded_vmcs->vmcs);
1257 indirect_branch_prediction_barrier();
1260 if (!already_loaded) {
1261 void *gdt = get_current_gdt_ro();
1262 unsigned long sysenter_esp;
1264 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1267 * Linux uses per-cpu TSS and GDT, so set these when switching
1268 * processors. See 22.2.4.
1270 vmcs_writel(HOST_TR_BASE,
1271 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1272 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1275 * VM exits change the host TR limit to 0x67 after a VM
1276 * exit. This is okay, since 0x67 covers everything except
1277 * the IO bitmap and have have code to handle the IO bitmap
1278 * being lost after a VM exit.
1280 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
1282 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1283 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1285 vmx->loaded_vmcs->cpu = cpu;
1288 /* Setup TSC multiplier */
1289 if (kvm_has_tsc_control &&
1290 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1291 decache_tsc_multiplier(vmx);
1293 vmx_vcpu_pi_load(vcpu, cpu);
1294 vmx->host_pkru = read_pkru();
1295 vmx->host_debugctlmsr = get_debugctlmsr();
1298 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1300 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1302 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1303 !irq_remapping_cap(IRQ_POSTING_CAP) ||
1304 !kvm_vcpu_apicv_active(vcpu))
1307 /* Set SN when the vCPU is preempted */
1308 if (vcpu->preempted)
1312 void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1314 vmx_vcpu_pi_put(vcpu);
1316 vmx_prepare_switch_to_host(to_vmx(vcpu));
1319 static bool emulation_required(struct kvm_vcpu *vcpu)
1321 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1324 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1326 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1328 unsigned long rflags, save_rflags;
1330 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1331 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1332 rflags = vmcs_readl(GUEST_RFLAGS);
1333 if (to_vmx(vcpu)->rmode.vm86_active) {
1334 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1335 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1336 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1338 to_vmx(vcpu)->rflags = rflags;
1340 return to_vmx(vcpu)->rflags;
1343 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1345 unsigned long old_rflags = vmx_get_rflags(vcpu);
1347 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1348 to_vmx(vcpu)->rflags = rflags;
1349 if (to_vmx(vcpu)->rmode.vm86_active) {
1350 to_vmx(vcpu)->rmode.save_rflags = rflags;
1351 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1353 vmcs_writel(GUEST_RFLAGS, rflags);
1355 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
1356 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
1359 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1361 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1364 if (interruptibility & GUEST_INTR_STATE_STI)
1365 ret |= KVM_X86_SHADOW_INT_STI;
1366 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1367 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1372 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1374 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1375 u32 interruptibility = interruptibility_old;
1377 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1379 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1380 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1381 else if (mask & KVM_X86_SHADOW_INT_STI)
1382 interruptibility |= GUEST_INTR_STATE_STI;
1384 if ((interruptibility != interruptibility_old))
1385 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1388 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1390 struct vcpu_vmx *vmx = to_vmx(vcpu);
1391 unsigned long value;
1394 * Any MSR write that attempts to change bits marked reserved will
1397 if (data & vmx->pt_desc.ctl_bitmask)
1401 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1402 * result in a #GP unless the same write also clears TraceEn.
1404 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1405 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1409 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1410 * and FabricEn would cause #GP, if
1411 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1413 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1414 !(data & RTIT_CTL_FABRIC_EN) &&
1415 !intel_pt_validate_cap(vmx->pt_desc.caps,
1416 PT_CAP_single_range_output))
1420 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1421 * utilize encodings marked reserved will casue a #GP fault.
1423 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1424 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1425 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1426 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1428 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1429 PT_CAP_cycle_thresholds);
1430 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1431 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1432 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1434 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1435 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1436 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1437 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1441 * If ADDRx_CFG is reserved or the encodings is >2 will
1442 * cause a #GP fault.
1444 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1445 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1447 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1448 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1450 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1451 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1453 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1454 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1461 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1465 rip = kvm_rip_read(vcpu);
1466 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1467 kvm_rip_write(vcpu, rip);
1469 /* skipping an emulated instruction also counts */
1470 vmx_set_interrupt_shadow(vcpu, 0);
1473 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1476 * Ensure that we clear the HLT state in the VMCS. We don't need to
1477 * explicitly skip the instruction because if the HLT state is set,
1478 * then the instruction is already executing and RIP has already been
1481 if (kvm_hlt_in_guest(vcpu->kvm) &&
1482 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1483 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1486 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1488 struct vcpu_vmx *vmx = to_vmx(vcpu);
1489 unsigned nr = vcpu->arch.exception.nr;
1490 bool has_error_code = vcpu->arch.exception.has_error_code;
1491 u32 error_code = vcpu->arch.exception.error_code;
1492 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1494 kvm_deliver_exception_payload(vcpu);
1496 if (has_error_code) {
1497 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1498 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1501 if (vmx->rmode.vm86_active) {
1503 if (kvm_exception_is_soft(nr))
1504 inc_eip = vcpu->arch.event_exit_inst_len;
1505 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1506 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1510 WARN_ON_ONCE(vmx->emulation_required);
1512 if (kvm_exception_is_soft(nr)) {
1513 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1514 vmx->vcpu.arch.event_exit_inst_len);
1515 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1517 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1519 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1521 vmx_clear_hlt(vcpu);
1524 static bool vmx_rdtscp_supported(void)
1526 return cpu_has_vmx_rdtscp();
1529 static bool vmx_invpcid_supported(void)
1531 return cpu_has_vmx_invpcid();
1535 * Swap MSR entry in host/guest MSR entry array.
1537 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1539 struct shared_msr_entry tmp;
1541 tmp = vmx->guest_msrs[to];
1542 vmx->guest_msrs[to] = vmx->guest_msrs[from];
1543 vmx->guest_msrs[from] = tmp;
1547 * Set up the vmcs to automatically save and restore system
1548 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1549 * mode, as fiddling with msrs is very expensive.
1551 static void setup_msrs(struct vcpu_vmx *vmx)
1553 int save_nmsrs, index;
1556 #ifdef CONFIG_X86_64
1558 * The SYSCALL MSRs are only needed on long mode guests, and only
1559 * when EFER.SCE is set.
1561 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1562 index = __find_msr_index(vmx, MSR_STAR);
1564 move_msr_up(vmx, index, save_nmsrs++);
1565 index = __find_msr_index(vmx, MSR_LSTAR);
1567 move_msr_up(vmx, index, save_nmsrs++);
1568 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1570 move_msr_up(vmx, index, save_nmsrs++);
1573 index = __find_msr_index(vmx, MSR_EFER);
1574 if (index >= 0 && update_transition_efer(vmx, index))
1575 move_msr_up(vmx, index, save_nmsrs++);
1576 index = __find_msr_index(vmx, MSR_TSC_AUX);
1577 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1578 move_msr_up(vmx, index, save_nmsrs++);
1580 vmx->save_nmsrs = save_nmsrs;
1581 vmx->guest_msrs_dirty = true;
1583 if (cpu_has_vmx_msr_bitmap())
1584 vmx_update_msr_bitmap(&vmx->vcpu);
1587 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1589 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1591 if (is_guest_mode(vcpu) &&
1592 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1593 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
1595 return vcpu->arch.tsc_offset;
1598 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1600 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1601 u64 g_tsc_offset = 0;
1604 * We're here if L1 chose not to trap WRMSR to TSC. According
1605 * to the spec, this should set L1's TSC; The offset that L1
1606 * set for L2 remains unchanged, and still needs to be added
1607 * to the newly set TSC to get L2's TSC.
1609 if (is_guest_mode(vcpu) &&
1610 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1611 g_tsc_offset = vmcs12->tsc_offset;
1613 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1614 vcpu->arch.tsc_offset - g_tsc_offset,
1616 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1617 return offset + g_tsc_offset;
1621 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1622 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1623 * all guests if the "nested" module option is off, and can also be disabled
1624 * for a single guest by disabling its VMX cpuid bit.
1626 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1628 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1631 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1634 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1636 return !(val & ~valid_bits);
1639 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1641 switch (msr->index) {
1642 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1645 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1654 * Reads an msr value (of 'msr_index') into 'pdata'.
1655 * Returns 0 on success, non-0 otherwise.
1656 * Assumes vcpu_load() was already called.
1658 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1660 struct vcpu_vmx *vmx = to_vmx(vcpu);
1661 struct shared_msr_entry *msr;
1664 switch (msr_info->index) {
1665 #ifdef CONFIG_X86_64
1667 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1670 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1672 case MSR_KERNEL_GS_BASE:
1673 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1677 return kvm_get_msr_common(vcpu, msr_info);
1678 case MSR_IA32_SPEC_CTRL:
1679 if (!msr_info->host_initiated &&
1680 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1683 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1685 case MSR_IA32_ARCH_CAPABILITIES:
1686 if (!msr_info->host_initiated &&
1687 !guest_cpuid_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
1689 msr_info->data = to_vmx(vcpu)->arch_capabilities;
1691 case MSR_IA32_SYSENTER_CS:
1692 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1694 case MSR_IA32_SYSENTER_EIP:
1695 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1697 case MSR_IA32_SYSENTER_ESP:
1698 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1700 case MSR_IA32_BNDCFGS:
1701 if (!kvm_mpx_supported() ||
1702 (!msr_info->host_initiated &&
1703 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1705 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1707 case MSR_IA32_MCG_EXT_CTL:
1708 if (!msr_info->host_initiated &&
1709 !(vmx->msr_ia32_feature_control &
1710 FEATURE_CONTROL_LMCE))
1712 msr_info->data = vcpu->arch.mcg_ext_ctl;
1714 case MSR_IA32_FEATURE_CONTROL:
1715 msr_info->data = vmx->msr_ia32_feature_control;
1717 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1718 if (!nested_vmx_allowed(vcpu))
1720 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1723 if (!vmx_xsaves_supported())
1725 msr_info->data = vcpu->arch.ia32_xss;
1727 case MSR_IA32_RTIT_CTL:
1728 if (pt_mode != PT_MODE_HOST_GUEST)
1730 msr_info->data = vmx->pt_desc.guest.ctl;
1732 case MSR_IA32_RTIT_STATUS:
1733 if (pt_mode != PT_MODE_HOST_GUEST)
1735 msr_info->data = vmx->pt_desc.guest.status;
1737 case MSR_IA32_RTIT_CR3_MATCH:
1738 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1739 !intel_pt_validate_cap(vmx->pt_desc.caps,
1740 PT_CAP_cr3_filtering))
1742 msr_info->data = vmx->pt_desc.guest.cr3_match;
1744 case MSR_IA32_RTIT_OUTPUT_BASE:
1745 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1746 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1747 PT_CAP_topa_output) &&
1748 !intel_pt_validate_cap(vmx->pt_desc.caps,
1749 PT_CAP_single_range_output)))
1751 msr_info->data = vmx->pt_desc.guest.output_base;
1753 case MSR_IA32_RTIT_OUTPUT_MASK:
1754 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1755 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1756 PT_CAP_topa_output) &&
1757 !intel_pt_validate_cap(vmx->pt_desc.caps,
1758 PT_CAP_single_range_output)))
1760 msr_info->data = vmx->pt_desc.guest.output_mask;
1762 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1763 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1764 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1765 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1766 PT_CAP_num_address_ranges)))
1769 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1771 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1774 if (!msr_info->host_initiated &&
1775 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1777 /* Else, falls through */
1779 msr = find_msr_entry(vmx, msr_info->index);
1781 msr_info->data = msr->data;
1784 return kvm_get_msr_common(vcpu, msr_info);
1791 * Writes msr value into into the appropriate "register".
1792 * Returns 0 on success, non-0 otherwise.
1793 * Assumes vcpu_load() was already called.
1795 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1797 struct vcpu_vmx *vmx = to_vmx(vcpu);
1798 struct shared_msr_entry *msr;
1800 u32 msr_index = msr_info->index;
1801 u64 data = msr_info->data;
1804 switch (msr_index) {
1806 ret = kvm_set_msr_common(vcpu, msr_info);
1808 #ifdef CONFIG_X86_64
1810 vmx_segment_cache_clear(vmx);
1811 vmcs_writel(GUEST_FS_BASE, data);
1814 vmx_segment_cache_clear(vmx);
1815 vmcs_writel(GUEST_GS_BASE, data);
1817 case MSR_KERNEL_GS_BASE:
1818 vmx_write_guest_kernel_gs_base(vmx, data);
1821 case MSR_IA32_SYSENTER_CS:
1822 vmcs_write32(GUEST_SYSENTER_CS, data);
1824 case MSR_IA32_SYSENTER_EIP:
1825 vmcs_writel(GUEST_SYSENTER_EIP, data);
1827 case MSR_IA32_SYSENTER_ESP:
1828 vmcs_writel(GUEST_SYSENTER_ESP, data);
1830 case MSR_IA32_BNDCFGS:
1831 if (!kvm_mpx_supported() ||
1832 (!msr_info->host_initiated &&
1833 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1835 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
1836 (data & MSR_IA32_BNDCFGS_RSVD))
1838 vmcs_write64(GUEST_BNDCFGS, data);
1840 case MSR_IA32_SPEC_CTRL:
1841 if (!msr_info->host_initiated &&
1842 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1845 /* The STIBP bit doesn't fault even if it's not advertised */
1846 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
1849 vmx->spec_ctrl = data;
1856 * When it's written (to non-zero) for the first time, pass
1860 * The handling of the MSR bitmap for L2 guests is done in
1861 * nested_vmx_merge_msr_bitmap. We should not touch the
1862 * vmcs02.msr_bitmap here since it gets completely overwritten
1863 * in the merging. We update the vmcs01 here for L1 as well
1864 * since it will end up touching the MSR anyway now.
1866 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
1870 case MSR_IA32_PRED_CMD:
1871 if (!msr_info->host_initiated &&
1872 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1875 if (data & ~PRED_CMD_IBPB)
1881 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
1885 * When it's written (to non-zero) for the first time, pass
1889 * The handling of the MSR bitmap for L2 guests is done in
1890 * nested_vmx_merge_msr_bitmap. We should not touch the
1891 * vmcs02.msr_bitmap here since it gets completely overwritten
1894 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
1897 case MSR_IA32_ARCH_CAPABILITIES:
1898 if (!msr_info->host_initiated)
1900 vmx->arch_capabilities = data;
1902 case MSR_IA32_CR_PAT:
1903 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
1904 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
1906 vmcs_write64(GUEST_IA32_PAT, data);
1907 vcpu->arch.pat = data;
1910 ret = kvm_set_msr_common(vcpu, msr_info);
1912 case MSR_IA32_TSC_ADJUST:
1913 ret = kvm_set_msr_common(vcpu, msr_info);
1915 case MSR_IA32_MCG_EXT_CTL:
1916 if ((!msr_info->host_initiated &&
1917 !(to_vmx(vcpu)->msr_ia32_feature_control &
1918 FEATURE_CONTROL_LMCE)) ||
1919 (data & ~MCG_EXT_CTL_LMCE_EN))
1921 vcpu->arch.mcg_ext_ctl = data;
1923 case MSR_IA32_FEATURE_CONTROL:
1924 if (!vmx_feature_control_msr_valid(vcpu, data) ||
1925 (to_vmx(vcpu)->msr_ia32_feature_control &
1926 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
1928 vmx->msr_ia32_feature_control = data;
1929 if (msr_info->host_initiated && data == 0)
1930 vmx_leave_nested(vcpu);
1932 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1933 if (!msr_info->host_initiated)
1934 return 1; /* they are read-only */
1935 if (!nested_vmx_allowed(vcpu))
1937 return vmx_set_vmx_msr(vcpu, msr_index, data);
1939 if (!vmx_xsaves_supported())
1942 * The only supported bit as of Skylake is bit 8, but
1943 * it is not supported on KVM.
1947 vcpu->arch.ia32_xss = data;
1948 if (vcpu->arch.ia32_xss != host_xss)
1949 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
1950 vcpu->arch.ia32_xss, host_xss, false);
1952 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
1954 case MSR_IA32_RTIT_CTL:
1955 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1956 vmx_rtit_ctl_check(vcpu, data) ||
1959 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
1960 vmx->pt_desc.guest.ctl = data;
1961 pt_update_intercept_for_msr(vmx);
1963 case MSR_IA32_RTIT_STATUS:
1964 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1965 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1966 (data & MSR_IA32_RTIT_STATUS_MASK))
1968 vmx->pt_desc.guest.status = data;
1970 case MSR_IA32_RTIT_CR3_MATCH:
1971 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1972 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1973 !intel_pt_validate_cap(vmx->pt_desc.caps,
1974 PT_CAP_cr3_filtering))
1976 vmx->pt_desc.guest.cr3_match = data;
1978 case MSR_IA32_RTIT_OUTPUT_BASE:
1979 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1980 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1981 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1982 PT_CAP_topa_output) &&
1983 !intel_pt_validate_cap(vmx->pt_desc.caps,
1984 PT_CAP_single_range_output)) ||
1985 (data & MSR_IA32_RTIT_OUTPUT_BASE_MASK))
1987 vmx->pt_desc.guest.output_base = data;
1989 case MSR_IA32_RTIT_OUTPUT_MASK:
1990 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1991 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1992 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1993 PT_CAP_topa_output) &&
1994 !intel_pt_validate_cap(vmx->pt_desc.caps,
1995 PT_CAP_single_range_output)))
1997 vmx->pt_desc.guest.output_mask = data;
1999 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2000 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2001 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2002 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2003 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2004 PT_CAP_num_address_ranges)))
2007 vmx->pt_desc.guest.addr_b[index / 2] = data;
2009 vmx->pt_desc.guest.addr_a[index / 2] = data;
2012 if (!msr_info->host_initiated &&
2013 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2015 /* Check reserved bit, higher 32 bits should be zero */
2016 if ((data >> 32) != 0)
2018 /* Else, falls through */
2020 msr = find_msr_entry(vmx, msr_index);
2022 u64 old_msr_data = msr->data;
2024 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2026 ret = kvm_set_shared_msr(msr->index, msr->data,
2030 msr->data = old_msr_data;
2034 ret = kvm_set_msr_common(vcpu, msr_info);
2040 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2042 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2045 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2048 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2050 case VCPU_EXREG_PDPTR:
2052 ept_save_pdptrs(vcpu);
2059 static __init int cpu_has_kvm_support(void)
2061 return cpu_has_vmx();
2064 static __init int vmx_disabled_by_bios(void)
2068 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2069 if (msr & FEATURE_CONTROL_LOCKED) {
2070 /* launched w/ TXT and VMX disabled */
2071 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2074 /* launched w/o TXT and VMX only enabled w/ TXT */
2075 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2076 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2077 && !tboot_enabled()) {
2078 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2079 "activate TXT before enabling KVM\n");
2082 /* launched w/o TXT and VMX disabled */
2083 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2084 && !tboot_enabled())
2091 static void kvm_cpu_vmxon(u64 addr)
2093 cr4_set_bits(X86_CR4_VMXE);
2094 intel_pt_handle_vmx(1);
2096 asm volatile ("vmxon %0" : : "m"(addr));
2099 static int hardware_enable(void)
2101 int cpu = raw_smp_processor_id();
2102 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2105 if (cr4_read_shadow() & X86_CR4_VMXE)
2109 * This can happen if we hot-added a CPU but failed to allocate
2110 * VP assist page for it.
2112 if (static_branch_unlikely(&enable_evmcs) &&
2113 !hv_get_vp_assist_page(cpu))
2116 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2117 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
2118 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
2121 * Now we can enable the vmclear operation in kdump
2122 * since the loaded_vmcss_on_cpu list on this cpu
2123 * has been initialized.
2125 * Though the cpu is not in VMX operation now, there
2126 * is no problem to enable the vmclear operation
2127 * for the loaded_vmcss_on_cpu list is empty!
2129 crash_enable_local_vmclear(cpu);
2131 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2133 test_bits = FEATURE_CONTROL_LOCKED;
2134 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2135 if (tboot_enabled())
2136 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2138 if ((old & test_bits) != test_bits) {
2139 /* enable and lock */
2140 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2142 kvm_cpu_vmxon(phys_addr);
2149 static void vmclear_local_loaded_vmcss(void)
2151 int cpu = raw_smp_processor_id();
2152 struct loaded_vmcs *v, *n;
2154 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2155 loaded_vmcss_on_cpu_link)
2156 __loaded_vmcs_clear(v);
2160 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2163 static void kvm_cpu_vmxoff(void)
2165 asm volatile (__ex("vmxoff"));
2167 intel_pt_handle_vmx(0);
2168 cr4_clear_bits(X86_CR4_VMXE);
2171 static void hardware_disable(void)
2173 vmclear_local_loaded_vmcss();
2177 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2178 u32 msr, u32 *result)
2180 u32 vmx_msr_low, vmx_msr_high;
2181 u32 ctl = ctl_min | ctl_opt;
2183 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2185 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2186 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2188 /* Ensure minimum (required) set of control bits are supported. */
2196 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2197 struct vmx_capability *vmx_cap)
2199 u32 vmx_msr_low, vmx_msr_high;
2200 u32 min, opt, min2, opt2;
2201 u32 _pin_based_exec_control = 0;
2202 u32 _cpu_based_exec_control = 0;
2203 u32 _cpu_based_2nd_exec_control = 0;
2204 u32 _vmexit_control = 0;
2205 u32 _vmentry_control = 0;
2207 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2208 min = CPU_BASED_HLT_EXITING |
2209 #ifdef CONFIG_X86_64
2210 CPU_BASED_CR8_LOAD_EXITING |
2211 CPU_BASED_CR8_STORE_EXITING |
2213 CPU_BASED_CR3_LOAD_EXITING |
2214 CPU_BASED_CR3_STORE_EXITING |
2215 CPU_BASED_UNCOND_IO_EXITING |
2216 CPU_BASED_MOV_DR_EXITING |
2217 CPU_BASED_USE_TSC_OFFSETING |
2218 CPU_BASED_MWAIT_EXITING |
2219 CPU_BASED_MONITOR_EXITING |
2220 CPU_BASED_INVLPG_EXITING |
2221 CPU_BASED_RDPMC_EXITING;
2223 opt = CPU_BASED_TPR_SHADOW |
2224 CPU_BASED_USE_MSR_BITMAPS |
2225 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2226 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2227 &_cpu_based_exec_control) < 0)
2229 #ifdef CONFIG_X86_64
2230 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2231 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2232 ~CPU_BASED_CR8_STORE_EXITING;
2234 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2236 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2237 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2238 SECONDARY_EXEC_WBINVD_EXITING |
2239 SECONDARY_EXEC_ENABLE_VPID |
2240 SECONDARY_EXEC_ENABLE_EPT |
2241 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2242 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2243 SECONDARY_EXEC_DESC |
2244 SECONDARY_EXEC_RDTSCP |
2245 SECONDARY_EXEC_ENABLE_INVPCID |
2246 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2247 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2248 SECONDARY_EXEC_SHADOW_VMCS |
2249 SECONDARY_EXEC_XSAVES |
2250 SECONDARY_EXEC_RDSEED_EXITING |
2251 SECONDARY_EXEC_RDRAND_EXITING |
2252 SECONDARY_EXEC_ENABLE_PML |
2253 SECONDARY_EXEC_TSC_SCALING |
2254 SECONDARY_EXEC_PT_USE_GPA |
2255 SECONDARY_EXEC_PT_CONCEAL_VMX |
2256 SECONDARY_EXEC_ENABLE_VMFUNC |
2257 SECONDARY_EXEC_ENCLS_EXITING;
2258 if (adjust_vmx_controls(min2, opt2,
2259 MSR_IA32_VMX_PROCBASED_CTLS2,
2260 &_cpu_based_2nd_exec_control) < 0)
2263 #ifndef CONFIG_X86_64
2264 if (!(_cpu_based_2nd_exec_control &
2265 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2266 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2269 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2270 _cpu_based_2nd_exec_control &= ~(
2271 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2272 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2273 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2275 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2276 &vmx_cap->ept, &vmx_cap->vpid);
2278 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2279 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2281 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2282 CPU_BASED_CR3_STORE_EXITING |
2283 CPU_BASED_INVLPG_EXITING);
2284 } else if (vmx_cap->ept) {
2286 pr_warn_once("EPT CAP should not exist if not support "
2287 "1-setting enable EPT VM-execution control\n");
2289 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2292 pr_warn_once("VPID CAP should not exist if not support "
2293 "1-setting enable VPID VM-execution control\n");
2296 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2297 #ifdef CONFIG_X86_64
2298 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2300 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2301 VM_EXIT_SAVE_IA32_PAT |
2302 VM_EXIT_LOAD_IA32_PAT |
2303 VM_EXIT_LOAD_IA32_EFER |
2304 VM_EXIT_CLEAR_BNDCFGS |
2305 VM_EXIT_PT_CONCEAL_PIP |
2306 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2307 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2308 &_vmexit_control) < 0)
2311 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2312 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2313 PIN_BASED_VMX_PREEMPTION_TIMER;
2314 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2315 &_pin_based_exec_control) < 0)
2318 if (cpu_has_broken_vmx_preemption_timer())
2319 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2320 if (!(_cpu_based_2nd_exec_control &
2321 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2322 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2324 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2325 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2326 VM_ENTRY_LOAD_IA32_PAT |
2327 VM_ENTRY_LOAD_IA32_EFER |
2328 VM_ENTRY_LOAD_BNDCFGS |
2329 VM_ENTRY_PT_CONCEAL_PIP |
2330 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2331 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2332 &_vmentry_control) < 0)
2336 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2337 * can't be used due to an errata where VM Exit may incorrectly clear
2338 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2339 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2341 if (boot_cpu_data.x86 == 0x6) {
2342 switch (boot_cpu_data.x86_model) {
2343 case 26: /* AAK155 */
2344 case 30: /* AAP115 */
2345 case 37: /* AAT100 */
2346 case 44: /* BC86,AAY89,BD102 */
2348 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2349 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2350 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2351 "does not work properly. Using workaround\n");
2359 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2361 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2362 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2365 #ifdef CONFIG_X86_64
2366 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2367 if (vmx_msr_high & (1u<<16))
2371 /* Require Write-Back (WB) memory type for VMCS accesses. */
2372 if (((vmx_msr_high >> 18) & 15) != 6)
2375 vmcs_conf->size = vmx_msr_high & 0x1fff;
2376 vmcs_conf->order = get_order(vmcs_conf->size);
2377 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2379 vmcs_conf->revision_id = vmx_msr_low;
2381 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2382 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2383 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2384 vmcs_conf->vmexit_ctrl = _vmexit_control;
2385 vmcs_conf->vmentry_ctrl = _vmentry_control;
2387 if (static_branch_unlikely(&enable_evmcs))
2388 evmcs_sanitize_exec_ctrls(vmcs_conf);
2393 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
2395 int node = cpu_to_node(cpu);
2399 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
2402 vmcs = page_address(pages);
2403 memset(vmcs, 0, vmcs_config.size);
2405 /* KVM supports Enlightened VMCS v1 only */
2406 if (static_branch_unlikely(&enable_evmcs))
2407 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2409 vmcs->hdr.revision_id = vmcs_config.revision_id;
2412 vmcs->hdr.shadow_vmcs = 1;
2416 void free_vmcs(struct vmcs *vmcs)
2418 free_pages((unsigned long)vmcs, vmcs_config.order);
2422 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2424 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2426 if (!loaded_vmcs->vmcs)
2428 loaded_vmcs_clear(loaded_vmcs);
2429 free_vmcs(loaded_vmcs->vmcs);
2430 loaded_vmcs->vmcs = NULL;
2431 if (loaded_vmcs->msr_bitmap)
2432 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2433 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2436 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2438 loaded_vmcs->vmcs = alloc_vmcs(false);
2439 if (!loaded_vmcs->vmcs)
2442 loaded_vmcs->shadow_vmcs = NULL;
2443 loaded_vmcs_init(loaded_vmcs);
2445 if (cpu_has_vmx_msr_bitmap()) {
2446 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
2447 if (!loaded_vmcs->msr_bitmap)
2449 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2451 if (IS_ENABLED(CONFIG_HYPERV) &&
2452 static_branch_unlikely(&enable_evmcs) &&
2453 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2454 struct hv_enlightened_vmcs *evmcs =
2455 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2457 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2461 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2466 free_loaded_vmcs(loaded_vmcs);
2470 static void free_kvm_area(void)
2474 for_each_possible_cpu(cpu) {
2475 free_vmcs(per_cpu(vmxarea, cpu));
2476 per_cpu(vmxarea, cpu) = NULL;
2480 static __init int alloc_kvm_area(void)
2484 for_each_possible_cpu(cpu) {
2487 vmcs = alloc_vmcs_cpu(false, cpu);
2494 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2495 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2496 * revision_id reported by MSR_IA32_VMX_BASIC.
2498 * However, even though not explicitly documented by
2499 * TLFS, VMXArea passed as VMXON argument should
2500 * still be marked with revision_id reported by
2503 if (static_branch_unlikely(&enable_evmcs))
2504 vmcs->hdr.revision_id = vmcs_config.revision_id;
2506 per_cpu(vmxarea, cpu) = vmcs;
2511 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2512 struct kvm_segment *save)
2514 if (!emulate_invalid_guest_state) {
2516 * CS and SS RPL should be equal during guest entry according
2517 * to VMX spec, but in reality it is not always so. Since vcpu
2518 * is in the middle of the transition from real mode to
2519 * protected mode it is safe to assume that RPL 0 is a good
2522 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2523 save->selector &= ~SEGMENT_RPL_MASK;
2524 save->dpl = save->selector & SEGMENT_RPL_MASK;
2527 vmx_set_segment(vcpu, save, seg);
2530 static void enter_pmode(struct kvm_vcpu *vcpu)
2532 unsigned long flags;
2533 struct vcpu_vmx *vmx = to_vmx(vcpu);
2536 * Update real mode segment cache. It may be not up-to-date if sement
2537 * register was written while vcpu was in a guest mode.
2539 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2540 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2541 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2542 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2543 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2544 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2546 vmx->rmode.vm86_active = 0;
2548 vmx_segment_cache_clear(vmx);
2550 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2552 flags = vmcs_readl(GUEST_RFLAGS);
2553 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2554 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2555 vmcs_writel(GUEST_RFLAGS, flags);
2557 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2558 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2560 update_exception_bitmap(vcpu);
2562 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2563 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2564 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2565 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2566 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2567 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2570 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2572 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2573 struct kvm_segment var = *save;
2576 if (seg == VCPU_SREG_CS)
2579 if (!emulate_invalid_guest_state) {
2580 var.selector = var.base >> 4;
2581 var.base = var.base & 0xffff0;
2591 if (save->base & 0xf)
2592 printk_once(KERN_WARNING "kvm: segment base is not "
2593 "paragraph aligned when entering "
2594 "protected mode (seg=%d)", seg);
2597 vmcs_write16(sf->selector, var.selector);
2598 vmcs_writel(sf->base, var.base);
2599 vmcs_write32(sf->limit, var.limit);
2600 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2603 static void enter_rmode(struct kvm_vcpu *vcpu)
2605 unsigned long flags;
2606 struct vcpu_vmx *vmx = to_vmx(vcpu);
2607 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2609 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2610 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2611 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2612 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2613 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2614 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2615 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2617 vmx->rmode.vm86_active = 1;
2620 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2621 * vcpu. Warn the user that an update is overdue.
2623 if (!kvm_vmx->tss_addr)
2624 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2625 "called before entering vcpu\n");
2627 vmx_segment_cache_clear(vmx);
2629 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2630 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2631 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2633 flags = vmcs_readl(GUEST_RFLAGS);
2634 vmx->rmode.save_rflags = flags;
2636 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2638 vmcs_writel(GUEST_RFLAGS, flags);
2639 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2640 update_exception_bitmap(vcpu);
2642 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2643 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2644 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2645 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2646 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2647 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2649 kvm_mmu_reset_context(vcpu);
2652 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2654 struct vcpu_vmx *vmx = to_vmx(vcpu);
2655 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2660 vcpu->arch.efer = efer;
2661 if (efer & EFER_LMA) {
2662 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2665 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2667 msr->data = efer & ~EFER_LME;
2672 #ifdef CONFIG_X86_64
2674 static void enter_lmode(struct kvm_vcpu *vcpu)
2678 vmx_segment_cache_clear(to_vmx(vcpu));
2680 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2681 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2682 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2684 vmcs_write32(GUEST_TR_AR_BYTES,
2685 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2686 | VMX_AR_TYPE_BUSY_64_TSS);
2688 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2691 static void exit_lmode(struct kvm_vcpu *vcpu)
2693 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2694 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2699 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2701 int vpid = to_vmx(vcpu)->vpid;
2703 if (!vpid_sync_vcpu_addr(vpid, addr))
2704 vpid_sync_context(vpid);
2707 * If VPIDs are not supported or enabled, then the above is a no-op.
2708 * But we don't really need a TLB flush in that case anyway, because
2709 * each VM entry/exit includes an implicit flush when VPID is 0.
2713 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2715 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2717 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
2718 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
2721 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2723 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
2724 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2725 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2728 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2730 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2732 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2733 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2736 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2738 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2740 if (!test_bit(VCPU_EXREG_PDPTR,
2741 (unsigned long *)&vcpu->arch.regs_dirty))
2744 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2745 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2746 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2747 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2748 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2752 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2754 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2756 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2757 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2758 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2759 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2760 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2763 __set_bit(VCPU_EXREG_PDPTR,
2764 (unsigned long *)&vcpu->arch.regs_avail);
2765 __set_bit(VCPU_EXREG_PDPTR,
2766 (unsigned long *)&vcpu->arch.regs_dirty);
2769 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2771 struct kvm_vcpu *vcpu)
2773 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2774 vmx_decache_cr3(vcpu);
2775 if (!(cr0 & X86_CR0_PG)) {
2776 /* From paging/starting to nonpaging */
2777 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2778 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
2779 (CPU_BASED_CR3_LOAD_EXITING |
2780 CPU_BASED_CR3_STORE_EXITING));
2781 vcpu->arch.cr0 = cr0;
2782 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2783 } else if (!is_paging(vcpu)) {
2784 /* From nonpaging to paging */
2785 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2786 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
2787 ~(CPU_BASED_CR3_LOAD_EXITING |
2788 CPU_BASED_CR3_STORE_EXITING));
2789 vcpu->arch.cr0 = cr0;
2790 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2793 if (!(cr0 & X86_CR0_WP))
2794 *hw_cr0 &= ~X86_CR0_WP;
2797 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2799 struct vcpu_vmx *vmx = to_vmx(vcpu);
2800 unsigned long hw_cr0;
2802 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
2803 if (enable_unrestricted_guest)
2804 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
2806 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
2808 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
2811 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
2815 #ifdef CONFIG_X86_64
2816 if (vcpu->arch.efer & EFER_LME) {
2817 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
2819 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
2824 if (enable_ept && !enable_unrestricted_guest)
2825 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
2827 vmcs_writel(CR0_READ_SHADOW, cr0);
2828 vmcs_writel(GUEST_CR0, hw_cr0);
2829 vcpu->arch.cr0 = cr0;
2831 /* depends on vcpu->arch.cr0 to be set to a new value */
2832 vmx->emulation_required = emulation_required(vcpu);
2835 static int get_ept_level(struct kvm_vcpu *vcpu)
2837 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
2842 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
2844 u64 eptp = VMX_EPTP_MT_WB;
2846 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
2848 if (enable_ept_ad_bits &&
2849 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
2850 eptp |= VMX_EPTP_AD_ENABLE_BIT;
2851 eptp |= (root_hpa & PAGE_MASK);
2856 void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
2858 struct kvm *kvm = vcpu->kvm;
2859 unsigned long guest_cr3;
2864 eptp = construct_eptp(vcpu, cr3);
2865 vmcs_write64(EPT_POINTER, eptp);
2867 if (kvm_x86_ops->tlb_remote_flush) {
2868 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2869 to_vmx(vcpu)->ept_pointer = eptp;
2870 to_kvm_vmx(kvm)->ept_pointers_match
2871 = EPT_POINTERS_CHECK;
2872 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2875 if (enable_unrestricted_guest || is_paging(vcpu) ||
2876 is_guest_mode(vcpu))
2877 guest_cr3 = kvm_read_cr3(vcpu);
2879 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
2880 ept_load_pdptrs(vcpu);
2883 vmcs_writel(GUEST_CR3, guest_cr3);
2886 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2889 * Pass through host's Machine Check Enable value to hw_cr4, which
2890 * is in force while we are in guest mode. Do not let guests control
2891 * this bit, even if host CR4.MCE == 0.
2893 unsigned long hw_cr4;
2895 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
2896 if (enable_unrestricted_guest)
2897 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
2898 else if (to_vmx(vcpu)->rmode.vm86_active)
2899 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
2901 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
2903 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
2904 if (cr4 & X86_CR4_UMIP) {
2905 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
2906 SECONDARY_EXEC_DESC);
2907 hw_cr4 &= ~X86_CR4_UMIP;
2908 } else if (!is_guest_mode(vcpu) ||
2909 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
2910 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
2911 SECONDARY_EXEC_DESC);
2914 if (cr4 & X86_CR4_VMXE) {
2916 * To use VMXON (and later other VMX instructions), a guest
2917 * must first be able to turn on cr4.VMXE (see handle_vmon()).
2918 * So basically the check on whether to allow nested VMX
2919 * is here. We operate under the default treatment of SMM,
2920 * so VMX cannot be enabled under SMM.
2922 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
2926 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
2929 vcpu->arch.cr4 = cr4;
2931 if (!enable_unrestricted_guest) {
2933 if (!is_paging(vcpu)) {
2934 hw_cr4 &= ~X86_CR4_PAE;
2935 hw_cr4 |= X86_CR4_PSE;
2936 } else if (!(cr4 & X86_CR4_PAE)) {
2937 hw_cr4 &= ~X86_CR4_PAE;
2942 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
2943 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
2944 * to be manually disabled when guest switches to non-paging
2947 * If !enable_unrestricted_guest, the CPU is always running
2948 * with CR0.PG=1 and CR4 needs to be modified.
2949 * If enable_unrestricted_guest, the CPU automatically
2950 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
2952 if (!is_paging(vcpu))
2953 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
2956 vmcs_writel(CR4_READ_SHADOW, cr4);
2957 vmcs_writel(GUEST_CR4, hw_cr4);
2961 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
2963 struct vcpu_vmx *vmx = to_vmx(vcpu);
2966 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
2967 *var = vmx->rmode.segs[seg];
2968 if (seg == VCPU_SREG_TR
2969 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
2971 var->base = vmx_read_guest_seg_base(vmx, seg);
2972 var->selector = vmx_read_guest_seg_selector(vmx, seg);
2975 var->base = vmx_read_guest_seg_base(vmx, seg);
2976 var->limit = vmx_read_guest_seg_limit(vmx, seg);
2977 var->selector = vmx_read_guest_seg_selector(vmx, seg);
2978 ar = vmx_read_guest_seg_ar(vmx, seg);
2979 var->unusable = (ar >> 16) & 1;
2980 var->type = ar & 15;
2981 var->s = (ar >> 4) & 1;
2982 var->dpl = (ar >> 5) & 3;
2984 * Some userspaces do not preserve unusable property. Since usable
2985 * segment has to be present according to VMX spec we can use present
2986 * property to amend userspace bug by making unusable segment always
2987 * nonpresent. vmx_segment_access_rights() already marks nonpresent
2988 * segment as unusable.
2990 var->present = !var->unusable;
2991 var->avl = (ar >> 12) & 1;
2992 var->l = (ar >> 13) & 1;
2993 var->db = (ar >> 14) & 1;
2994 var->g = (ar >> 15) & 1;
2997 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2999 struct kvm_segment s;
3001 if (to_vmx(vcpu)->rmode.vm86_active) {
3002 vmx_get_segment(vcpu, &s, seg);
3005 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3008 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3010 struct vcpu_vmx *vmx = to_vmx(vcpu);
3012 if (unlikely(vmx->rmode.vm86_active))
3015 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3016 return VMX_AR_DPL(ar);
3020 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3024 if (var->unusable || !var->present)
3027 ar = var->type & 15;
3028 ar |= (var->s & 1) << 4;
3029 ar |= (var->dpl & 3) << 5;
3030 ar |= (var->present & 1) << 7;
3031 ar |= (var->avl & 1) << 12;
3032 ar |= (var->l & 1) << 13;
3033 ar |= (var->db & 1) << 14;
3034 ar |= (var->g & 1) << 15;
3040 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3042 struct vcpu_vmx *vmx = to_vmx(vcpu);
3043 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3045 vmx_segment_cache_clear(vmx);
3047 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3048 vmx->rmode.segs[seg] = *var;
3049 if (seg == VCPU_SREG_TR)
3050 vmcs_write16(sf->selector, var->selector);
3052 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3056 vmcs_writel(sf->base, var->base);
3057 vmcs_write32(sf->limit, var->limit);
3058 vmcs_write16(sf->selector, var->selector);
3061 * Fix the "Accessed" bit in AR field of segment registers for older
3063 * IA32 arch specifies that at the time of processor reset the
3064 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3065 * is setting it to 0 in the userland code. This causes invalid guest
3066 * state vmexit when "unrestricted guest" mode is turned on.
3067 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3068 * tree. Newer qemu binaries with that qemu fix would not need this
3071 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3072 var->type |= 0x1; /* Accessed */
3074 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3077 vmx->emulation_required = emulation_required(vcpu);
3080 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3082 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3084 *db = (ar >> 14) & 1;
3085 *l = (ar >> 13) & 1;
3088 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3090 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3091 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3094 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3096 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3097 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3100 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3102 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3103 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3106 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3108 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3109 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3112 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3114 struct kvm_segment var;
3117 vmx_get_segment(vcpu, &var, seg);
3119 if (seg == VCPU_SREG_CS)
3121 ar = vmx_segment_access_rights(&var);
3123 if (var.base != (var.selector << 4))
3125 if (var.limit != 0xffff)
3133 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3135 struct kvm_segment cs;
3136 unsigned int cs_rpl;
3138 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3139 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3143 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3147 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3148 if (cs.dpl > cs_rpl)
3151 if (cs.dpl != cs_rpl)
3157 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3161 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3163 struct kvm_segment ss;
3164 unsigned int ss_rpl;
3166 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3167 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3171 if (ss.type != 3 && ss.type != 7)
3175 if (ss.dpl != ss_rpl) /* DPL != RPL */
3183 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3185 struct kvm_segment var;
3188 vmx_get_segment(vcpu, &var, seg);
3189 rpl = var.selector & SEGMENT_RPL_MASK;
3197 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3198 if (var.dpl < rpl) /* DPL < RPL */
3202 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3208 static bool tr_valid(struct kvm_vcpu *vcpu)
3210 struct kvm_segment tr;
3212 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3216 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3218 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3226 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3228 struct kvm_segment ldtr;
3230 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3234 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3244 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3246 struct kvm_segment cs, ss;
3248 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3249 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3251 return ((cs.selector & SEGMENT_RPL_MASK) ==
3252 (ss.selector & SEGMENT_RPL_MASK));
3256 * Check if guest state is valid. Returns true if valid, false if
3258 * We assume that registers are always usable
3260 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3262 if (enable_unrestricted_guest)
3265 /* real mode guest state checks */
3266 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3267 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3269 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3271 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3273 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3275 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3277 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3280 /* protected mode guest state checks */
3281 if (!cs_ss_rpl_check(vcpu))
3283 if (!code_segment_valid(vcpu))
3285 if (!stack_segment_valid(vcpu))
3287 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3289 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3291 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3293 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3295 if (!tr_valid(vcpu))
3297 if (!ldtr_valid(vcpu))
3301 * - Add checks on RIP
3302 * - Add checks on RFLAGS
3308 static int init_rmode_tss(struct kvm *kvm)
3314 idx = srcu_read_lock(&kvm->srcu);
3315 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3316 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3319 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3320 r = kvm_write_guest_page(kvm, fn++, &data,
3321 TSS_IOPB_BASE_OFFSET, sizeof(u16));
3324 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3327 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3331 r = kvm_write_guest_page(kvm, fn, &data,
3332 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3335 srcu_read_unlock(&kvm->srcu, idx);
3339 static int init_rmode_identity_map(struct kvm *kvm)
3341 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3343 kvm_pfn_t identity_map_pfn;
3346 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3347 mutex_lock(&kvm->slots_lock);
3349 if (likely(kvm_vmx->ept_identity_pagetable_done))
3352 if (!kvm_vmx->ept_identity_map_addr)
3353 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3354 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3356 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3357 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3361 idx = srcu_read_lock(&kvm->srcu);
3362 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3365 /* Set up identity-mapping pagetable for EPT in real mode */
3366 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3367 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3368 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3369 r = kvm_write_guest_page(kvm, identity_map_pfn,
3370 &tmp, i * sizeof(tmp), sizeof(tmp));
3374 kvm_vmx->ept_identity_pagetable_done = true;
3377 srcu_read_unlock(&kvm->srcu, idx);
3380 mutex_unlock(&kvm->slots_lock);
3384 static void seg_setup(int seg)
3386 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3389 vmcs_write16(sf->selector, 0);
3390 vmcs_writel(sf->base, 0);
3391 vmcs_write32(sf->limit, 0xffff);
3393 if (seg == VCPU_SREG_CS)
3394 ar |= 0x08; /* code segment */
3396 vmcs_write32(sf->ar_bytes, ar);
3399 static int alloc_apic_access_page(struct kvm *kvm)
3404 mutex_lock(&kvm->slots_lock);
3405 if (kvm->arch.apic_access_page_done)
3407 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3408 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3412 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3413 if (is_error_page(page)) {
3419 * Do not pin the page in memory, so that memory hot-unplug
3420 * is able to migrate it.
3423 kvm->arch.apic_access_page_done = true;
3425 mutex_unlock(&kvm->slots_lock);
3429 int allocate_vpid(void)
3435 spin_lock(&vmx_vpid_lock);
3436 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3437 if (vpid < VMX_NR_VPIDS)
3438 __set_bit(vpid, vmx_vpid_bitmap);
3441 spin_unlock(&vmx_vpid_lock);
3445 void free_vpid(int vpid)
3447 if (!enable_vpid || vpid == 0)
3449 spin_lock(&vmx_vpid_lock);
3450 __clear_bit(vpid, vmx_vpid_bitmap);
3451 spin_unlock(&vmx_vpid_lock);
3454 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3457 int f = sizeof(unsigned long);
3459 if (!cpu_has_vmx_msr_bitmap())
3462 if (static_branch_unlikely(&enable_evmcs))
3463 evmcs_touch_msr_bitmap();
3466 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3467 * have the write-low and read-high bitmap offsets the wrong way round.
3468 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3470 if (msr <= 0x1fff) {
3471 if (type & MSR_TYPE_R)
3473 __clear_bit(msr, msr_bitmap + 0x000 / f);
3475 if (type & MSR_TYPE_W)
3477 __clear_bit(msr, msr_bitmap + 0x800 / f);
3479 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3481 if (type & MSR_TYPE_R)
3483 __clear_bit(msr, msr_bitmap + 0x400 / f);
3485 if (type & MSR_TYPE_W)
3487 __clear_bit(msr, msr_bitmap + 0xc00 / f);
3492 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3495 int f = sizeof(unsigned long);
3497 if (!cpu_has_vmx_msr_bitmap())
3500 if (static_branch_unlikely(&enable_evmcs))
3501 evmcs_touch_msr_bitmap();
3504 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3505 * have the write-low and read-high bitmap offsets the wrong way round.
3506 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3508 if (msr <= 0x1fff) {
3509 if (type & MSR_TYPE_R)
3511 __set_bit(msr, msr_bitmap + 0x000 / f);
3513 if (type & MSR_TYPE_W)
3515 __set_bit(msr, msr_bitmap + 0x800 / f);
3517 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3519 if (type & MSR_TYPE_R)
3521 __set_bit(msr, msr_bitmap + 0x400 / f);
3523 if (type & MSR_TYPE_W)
3525 __set_bit(msr, msr_bitmap + 0xc00 / f);
3530 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3531 u32 msr, int type, bool value)
3534 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3536 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3539 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3543 if (cpu_has_secondary_exec_ctrls() &&
3544 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
3545 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3546 mode |= MSR_BITMAP_MODE_X2APIC;
3547 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3548 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3554 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3559 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3560 unsigned word = msr / BITS_PER_LONG;
3561 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3562 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3565 if (mode & MSR_BITMAP_MODE_X2APIC) {
3567 * TPR reads and writes can be virtualized even if virtual interrupt
3568 * delivery is not in use.
3570 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3571 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3572 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3573 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3574 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3579 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3581 struct vcpu_vmx *vmx = to_vmx(vcpu);
3582 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3583 u8 mode = vmx_msr_bitmap_mode(vcpu);
3584 u8 changed = mode ^ vmx->msr_bitmap_mode;
3589 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3590 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3592 vmx->msr_bitmap_mode = mode;
3595 void pt_update_intercept_for_msr(struct vcpu_vmx *vmx)
3597 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3598 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3601 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_STATUS,
3603 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_BASE,
3605 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_MASK,
3607 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_CR3_MATCH,
3609 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3610 vmx_set_intercept_for_msr(msr_bitmap,
3611 MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3612 vmx_set_intercept_for_msr(msr_bitmap,
3613 MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3617 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
3619 return enable_apicv;
3622 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3624 struct vcpu_vmx *vmx = to_vmx(vcpu);
3629 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3630 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3631 WARN_ON_ONCE(!vmx->nested.virtual_apic_page))
3634 rvi = vmx_get_rvi();
3636 vapic_page = kmap(vmx->nested.virtual_apic_page);
3637 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3638 kunmap(vmx->nested.virtual_apic_page);
3640 return ((rvi & 0xf0) > (vppr & 0xf0));
3643 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3647 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3649 if (vcpu->mode == IN_GUEST_MODE) {
3651 * The vector of interrupt to be delivered to vcpu had
3652 * been set in PIR before this function.
3654 * Following cases will be reached in this block, and
3655 * we always send a notification event in all cases as
3658 * Case 1: vcpu keeps in non-root mode. Sending a
3659 * notification event posts the interrupt to vcpu.
3661 * Case 2: vcpu exits to root mode and is still
3662 * runnable. PIR will be synced to vIRR before the
3663 * next vcpu entry. Sending a notification event in
3664 * this case has no effect, as vcpu is not in root
3667 * Case 3: vcpu exits to root mode and is blocked.
3668 * vcpu_block() has already synced PIR to vIRR and
3669 * never blocks vcpu if vIRR is not cleared. Therefore,
3670 * a blocked vcpu here does not wait for any requested
3671 * interrupts in PIR, and sending a notification event
3672 * which has no effect is safe here.
3675 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3682 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3685 struct vcpu_vmx *vmx = to_vmx(vcpu);
3687 if (is_guest_mode(vcpu) &&
3688 vector == vmx->nested.posted_intr_nv) {
3690 * If a posted intr is not recognized by hardware,
3691 * we will accomplish it in the next vmentry.
3693 vmx->nested.pi_pending = true;
3694 kvm_make_request(KVM_REQ_EVENT, vcpu);
3695 /* the PIR and ON have been set by L1. */
3696 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3697 kvm_vcpu_kick(vcpu);
3703 * Send interrupt to vcpu via posted interrupt way.
3704 * 1. If target vcpu is running(non-root mode), send posted interrupt
3705 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3706 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3707 * interrupt from PIR in next vmentry.
3709 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3711 struct vcpu_vmx *vmx = to_vmx(vcpu);
3714 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3718 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3721 /* If a previous notification has sent the IPI, nothing to do. */
3722 if (pi_test_and_set_on(&vmx->pi_desc))
3725 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3726 kvm_vcpu_kick(vcpu);
3730 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3731 * will not change in the lifetime of the guest.
3732 * Note that host-state that does change is set elsewhere. E.g., host-state
3733 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3735 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3740 unsigned long cr0, cr3, cr4;
3743 WARN_ON(cr0 & X86_CR0_TS);
3744 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
3747 * Save the most likely value for this task's CR3 in the VMCS.
3748 * We can't use __get_current_cr3_fast() because we're not atomic.
3751 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
3752 vmx->loaded_vmcs->host_state.cr3 = cr3;
3754 /* Save the most likely value for this task's CR4 in the VMCS. */
3755 cr4 = cr4_read_shadow();
3756 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
3757 vmx->loaded_vmcs->host_state.cr4 = cr4;
3759 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
3760 #ifdef CONFIG_X86_64
3762 * Load null selectors, so we can avoid reloading them in
3763 * vmx_prepare_switch_to_host(), in case userspace uses
3764 * the null selectors too (the expected case).
3766 vmcs_write16(HOST_DS_SELECTOR, 0);
3767 vmcs_write16(HOST_ES_SELECTOR, 0);
3769 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3770 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3772 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3773 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
3776 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
3777 vmx->host_idt_base = dt.address;
3779 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
3781 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3782 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3783 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
3784 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
3786 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
3787 rdmsr(MSR_IA32_CR_PAT, low32, high32);
3788 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
3791 if (cpu_has_load_ia32_efer())
3792 vmcs_write64(HOST_IA32_EFER, host_efer);
3795 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
3797 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
3799 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
3800 if (is_guest_mode(&vmx->vcpu))
3801 vmx->vcpu.arch.cr4_guest_owned_bits &=
3802 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
3803 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
3806 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
3808 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
3810 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
3811 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
3814 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
3816 /* Enable the preemption timer dynamically */
3817 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3818 return pin_based_exec_ctrl;
3821 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
3823 struct vcpu_vmx *vmx = to_vmx(vcpu);
3825 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
3826 if (cpu_has_secondary_exec_ctrls()) {
3827 if (kvm_vcpu_apicv_active(vcpu))
3828 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
3829 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3830 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3832 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
3833 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3834 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3837 if (cpu_has_vmx_msr_bitmap())
3838 vmx_update_msr_bitmap(vcpu);
3841 u32 vmx_exec_control(struct vcpu_vmx *vmx)
3843 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
3845 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
3846 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
3848 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
3849 exec_control &= ~CPU_BASED_TPR_SHADOW;
3850 #ifdef CONFIG_X86_64
3851 exec_control |= CPU_BASED_CR8_STORE_EXITING |
3852 CPU_BASED_CR8_LOAD_EXITING;
3856 exec_control |= CPU_BASED_CR3_STORE_EXITING |
3857 CPU_BASED_CR3_LOAD_EXITING |
3858 CPU_BASED_INVLPG_EXITING;
3859 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
3860 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
3861 CPU_BASED_MONITOR_EXITING);
3862 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
3863 exec_control &= ~CPU_BASED_HLT_EXITING;
3864 return exec_control;
3868 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
3870 struct kvm_vcpu *vcpu = &vmx->vcpu;
3872 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
3874 if (pt_mode == PT_MODE_SYSTEM)
3875 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
3876 if (!cpu_need_virtualize_apic_accesses(vcpu))
3877 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3879 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
3881 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
3882 enable_unrestricted_guest = 0;
3884 if (!enable_unrestricted_guest)
3885 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
3886 if (kvm_pause_in_guest(vmx->vcpu.kvm))
3887 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
3888 if (!kvm_vcpu_apicv_active(vcpu))
3889 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
3890 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3891 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
3893 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
3894 * in vmx_set_cr4. */
3895 exec_control &= ~SECONDARY_EXEC_DESC;
3897 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
3899 We can NOT enable shadow_vmcs here because we don't have yet
3902 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
3905 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
3907 if (vmx_xsaves_supported()) {
3908 /* Exposing XSAVES only when XSAVE is exposed */
3909 bool xsaves_enabled =
3910 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
3911 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
3913 if (!xsaves_enabled)
3914 exec_control &= ~SECONDARY_EXEC_XSAVES;
3918 vmx->nested.msrs.secondary_ctls_high |=
3919 SECONDARY_EXEC_XSAVES;
3921 vmx->nested.msrs.secondary_ctls_high &=
3922 ~SECONDARY_EXEC_XSAVES;
3926 if (vmx_rdtscp_supported()) {
3927 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
3928 if (!rdtscp_enabled)
3929 exec_control &= ~SECONDARY_EXEC_RDTSCP;
3933 vmx->nested.msrs.secondary_ctls_high |=
3934 SECONDARY_EXEC_RDTSCP;
3936 vmx->nested.msrs.secondary_ctls_high &=
3937 ~SECONDARY_EXEC_RDTSCP;
3941 if (vmx_invpcid_supported()) {
3942 /* Exposing INVPCID only when PCID is exposed */
3943 bool invpcid_enabled =
3944 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
3945 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
3947 if (!invpcid_enabled) {
3948 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
3949 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
3953 if (invpcid_enabled)
3954 vmx->nested.msrs.secondary_ctls_high |=
3955 SECONDARY_EXEC_ENABLE_INVPCID;
3957 vmx->nested.msrs.secondary_ctls_high &=
3958 ~SECONDARY_EXEC_ENABLE_INVPCID;
3962 if (vmx_rdrand_supported()) {
3963 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
3965 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
3969 vmx->nested.msrs.secondary_ctls_high |=
3970 SECONDARY_EXEC_RDRAND_EXITING;
3972 vmx->nested.msrs.secondary_ctls_high &=
3973 ~SECONDARY_EXEC_RDRAND_EXITING;
3977 if (vmx_rdseed_supported()) {
3978 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
3980 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
3984 vmx->nested.msrs.secondary_ctls_high |=
3985 SECONDARY_EXEC_RDSEED_EXITING;
3987 vmx->nested.msrs.secondary_ctls_high &=
3988 ~SECONDARY_EXEC_RDSEED_EXITING;
3992 vmx->secondary_exec_control = exec_control;
3995 static void ept_set_mmio_spte_mask(void)
3998 * EPT Misconfigurations can be generated if the value of bits 2:0
3999 * of an EPT paging-structure entry is 110b (write/execute).
4001 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
4002 VMX_EPT_MISCONFIG_WX_VALUE);
4005 #define VMX_XSS_EXIT_BITMAP 0
4008 * Sets up the vmcs for emulated real mode.
4010 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
4015 nested_vmx_vcpu_setup();
4017 if (cpu_has_vmx_msr_bitmap())
4018 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4020 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4023 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
4024 vmx->hv_deadline_tsc = -1;
4026 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
4028 if (cpu_has_secondary_exec_ctrls()) {
4029 vmx_compute_secondary_exec_control(vmx);
4030 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4031 vmx->secondary_exec_control);
4034 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4035 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4036 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4037 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4038 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4040 vmcs_write16(GUEST_INTR_STATUS, 0);
4042 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4043 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4046 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4047 vmcs_write32(PLE_GAP, ple_gap);
4048 vmx->ple_window = ple_window;
4049 vmx->ple_window_dirty = true;
4052 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4053 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4054 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4056 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4057 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4058 vmx_set_constant_host_state(vmx);
4059 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4060 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4062 if (cpu_has_vmx_vmfunc())
4063 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4065 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4066 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4067 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4068 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4069 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4071 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4072 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4074 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
4075 u32 index = vmx_msr_index[i];
4076 u32 data_low, data_high;
4079 if (rdmsr_safe(index, &data_low, &data_high) < 0)
4081 if (wrmsr_safe(index, data_low, data_high) < 0)
4083 vmx->guest_msrs[j].index = i;
4084 vmx->guest_msrs[j].data = 0;
4085 vmx->guest_msrs[j].mask = -1ull;
4089 vmx->arch_capabilities = kvm_get_arch_capabilities();
4091 vm_exit_controls_init(vmx, vmx_vmexit_ctrl());
4093 /* 22.2.1, 20.8.1 */
4094 vm_entry_controls_init(vmx, vmx_vmentry_ctrl());
4096 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
4097 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
4099 set_cr4_guest_host_mask(vmx);
4101 if (vmx_xsaves_supported())
4102 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4105 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4106 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4109 if (cpu_has_vmx_encls_vmexit())
4110 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
4112 if (pt_mode == PT_MODE_HOST_GUEST) {
4113 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4114 /* Bit[6~0] are forced to 1, writes are ignored. */
4115 vmx->pt_desc.guest.output_mask = 0x7F;
4116 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4120 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4122 struct vcpu_vmx *vmx = to_vmx(vcpu);
4123 struct msr_data apic_base_msr;
4126 vmx->rmode.vm86_active = 0;
4129 vcpu->arch.microcode_version = 0x100000000ULL;
4130 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4131 kvm_set_cr8(vcpu, 0);
4134 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4135 MSR_IA32_APICBASE_ENABLE;
4136 if (kvm_vcpu_is_reset_bsp(vcpu))
4137 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4138 apic_base_msr.host_initiated = true;
4139 kvm_set_apic_base(vcpu, &apic_base_msr);
4142 vmx_segment_cache_clear(vmx);
4144 seg_setup(VCPU_SREG_CS);
4145 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4146 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4148 seg_setup(VCPU_SREG_DS);
4149 seg_setup(VCPU_SREG_ES);
4150 seg_setup(VCPU_SREG_FS);
4151 seg_setup(VCPU_SREG_GS);
4152 seg_setup(VCPU_SREG_SS);
4154 vmcs_write16(GUEST_TR_SELECTOR, 0);
4155 vmcs_writel(GUEST_TR_BASE, 0);
4156 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4157 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4159 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4160 vmcs_writel(GUEST_LDTR_BASE, 0);
4161 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4162 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4165 vmcs_write32(GUEST_SYSENTER_CS, 0);
4166 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4167 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4168 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4171 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4172 kvm_rip_write(vcpu, 0xfff0);
4174 vmcs_writel(GUEST_GDTR_BASE, 0);
4175 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4177 vmcs_writel(GUEST_IDTR_BASE, 0);
4178 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4180 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4181 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4182 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4183 if (kvm_mpx_supported())
4184 vmcs_write64(GUEST_BNDCFGS, 0);
4188 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4190 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4191 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4192 if (cpu_need_tpr_shadow(vcpu))
4193 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4194 __pa(vcpu->arch.apic->regs));
4195 vmcs_write32(TPR_THRESHOLD, 0);
4198 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4201 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4203 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4204 vmx->vcpu.arch.cr0 = cr0;
4205 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4206 vmx_set_cr4(vcpu, 0);
4207 vmx_set_efer(vcpu, 0);
4209 update_exception_bitmap(vcpu);
4211 vpid_sync_context(vmx->vpid);
4213 vmx_clear_hlt(vcpu);
4216 static void enable_irq_window(struct kvm_vcpu *vcpu)
4218 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
4219 CPU_BASED_VIRTUAL_INTR_PENDING);
4222 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4225 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4226 enable_irq_window(vcpu);
4230 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
4231 CPU_BASED_VIRTUAL_NMI_PENDING);
4234 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4236 struct vcpu_vmx *vmx = to_vmx(vcpu);
4238 int irq = vcpu->arch.interrupt.nr;
4240 trace_kvm_inj_virq(irq);
4242 ++vcpu->stat.irq_injections;
4243 if (vmx->rmode.vm86_active) {
4245 if (vcpu->arch.interrupt.soft)
4246 inc_eip = vcpu->arch.event_exit_inst_len;
4247 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
4248 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4251 intr = irq | INTR_INFO_VALID_MASK;
4252 if (vcpu->arch.interrupt.soft) {
4253 intr |= INTR_TYPE_SOFT_INTR;
4254 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4255 vmx->vcpu.arch.event_exit_inst_len);
4257 intr |= INTR_TYPE_EXT_INTR;
4258 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4260 vmx_clear_hlt(vcpu);
4263 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4265 struct vcpu_vmx *vmx = to_vmx(vcpu);
4269 * Tracking the NMI-blocked state in software is built upon
4270 * finding the next open IRQ window. This, in turn, depends on
4271 * well-behaving guests: They have to keep IRQs disabled at
4272 * least as long as the NMI handler runs. Otherwise we may
4273 * cause NMI nesting, maybe breaking the guest. But as this is
4274 * highly unlikely, we can live with the residual risk.
4276 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4277 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4280 ++vcpu->stat.nmi_injections;
4281 vmx->loaded_vmcs->nmi_known_unmasked = false;
4283 if (vmx->rmode.vm86_active) {
4284 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
4285 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4289 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4290 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4292 vmx_clear_hlt(vcpu);
4295 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4297 struct vcpu_vmx *vmx = to_vmx(vcpu);
4301 return vmx->loaded_vmcs->soft_vnmi_blocked;
4302 if (vmx->loaded_vmcs->nmi_known_unmasked)
4304 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4305 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4309 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4311 struct vcpu_vmx *vmx = to_vmx(vcpu);
4314 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4315 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4316 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4319 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4321 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4322 GUEST_INTR_STATE_NMI);
4324 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4325 GUEST_INTR_STATE_NMI);
4329 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4331 if (to_vmx(vcpu)->nested.nested_run_pending)
4335 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4338 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4339 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4340 | GUEST_INTR_STATE_NMI));
4343 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4345 return (!to_vmx(vcpu)->nested.nested_run_pending &&
4346 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4347 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4348 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4351 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4355 if (enable_unrestricted_guest)
4358 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4362 to_kvm_vmx(kvm)->tss_addr = addr;
4363 return init_rmode_tss(kvm);
4366 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4368 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4372 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4377 * Update instruction length as we may reinject the exception
4378 * from user space while in guest debugging mode.
4380 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4381 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4382 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4386 if (vcpu->guest_debug &
4387 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4404 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4405 int vec, u32 err_code)
4408 * Instruction with address size override prefix opcode 0x67
4409 * Cause the #SS fault with 0 error code in VM86 mode.
4411 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4412 if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
4413 if (vcpu->arch.halt_request) {
4414 vcpu->arch.halt_request = 0;
4415 return kvm_vcpu_halt(vcpu);
4423 * Forward all other exceptions that are valid in real mode.
4424 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4425 * the required debugging infrastructure rework.
4427 kvm_queue_exception(vcpu, vec);
4432 * Trigger machine check on the host. We assume all the MSRs are already set up
4433 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4434 * We pass a fake environment to the machine check handler because we want
4435 * the guest to be always treated like user space, no matter what context
4436 * it used internally.
4438 static void kvm_machine_check(void)
4440 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4441 struct pt_regs regs = {
4442 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4443 .flags = X86_EFLAGS_IF,
4446 do_machine_check(®s, 0);
4450 static int handle_machine_check(struct kvm_vcpu *vcpu)
4452 /* already handled by vcpu_run */
4456 static int handle_exception(struct kvm_vcpu *vcpu)
4458 struct vcpu_vmx *vmx = to_vmx(vcpu);
4459 struct kvm_run *kvm_run = vcpu->run;
4460 u32 intr_info, ex_no, error_code;
4461 unsigned long cr2, rip, dr6;
4463 enum emulation_result er;
4465 vect_info = vmx->idt_vectoring_info;
4466 intr_info = vmx->exit_intr_info;
4468 if (is_machine_check(intr_info))
4469 return handle_machine_check(vcpu);
4471 if (is_nmi(intr_info))
4472 return 1; /* already handled by vmx_vcpu_run() */
4474 if (is_invalid_opcode(intr_info))
4475 return handle_ud(vcpu);
4478 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4479 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4481 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4482 WARN_ON_ONCE(!enable_vmware_backdoor);
4483 er = kvm_emulate_instruction(vcpu,
4484 EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
4485 if (er == EMULATE_USER_EXIT)
4487 else if (er != EMULATE_DONE)
4488 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4493 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4494 * MMIO, it is better to report an internal error.
4495 * See the comments in vmx_handle_exit.
4497 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4498 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4499 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4500 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4501 vcpu->run->internal.ndata = 3;
4502 vcpu->run->internal.data[0] = vect_info;
4503 vcpu->run->internal.data[1] = intr_info;
4504 vcpu->run->internal.data[2] = error_code;
4508 if (is_page_fault(intr_info)) {
4509 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4510 /* EPT won't cause page fault directly */
4511 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
4512 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4515 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4517 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4518 return handle_rmode_exception(vcpu, ex_no, error_code);
4522 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4525 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4526 if (!(vcpu->guest_debug &
4527 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4528 vcpu->arch.dr6 &= ~15;
4529 vcpu->arch.dr6 |= dr6 | DR6_RTM;
4530 if (is_icebp(intr_info))
4531 skip_emulated_instruction(vcpu);
4533 kvm_queue_exception(vcpu, DB_VECTOR);
4536 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4537 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4541 * Update instruction length as we may reinject #BP from
4542 * user space while in guest debugging mode. Reading it for
4543 * #DB as well causes no harm, it is not used in that case.
4545 vmx->vcpu.arch.event_exit_inst_len =
4546 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4547 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4548 rip = kvm_rip_read(vcpu);
4549 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4550 kvm_run->debug.arch.exception = ex_no;
4553 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4554 kvm_run->ex.exception = ex_no;
4555 kvm_run->ex.error_code = error_code;
4561 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4563 ++vcpu->stat.irq_exits;
4567 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4569 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4570 vcpu->mmio_needed = 0;
4574 static int handle_io(struct kvm_vcpu *vcpu)
4576 unsigned long exit_qualification;
4577 int size, in, string;
4580 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4581 string = (exit_qualification & 16) != 0;
4583 ++vcpu->stat.io_exits;
4586 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4588 port = exit_qualification >> 16;
4589 size = (exit_qualification & 7) + 1;
4590 in = (exit_qualification & 8) != 0;
4592 return kvm_fast_pio(vcpu, size, port, in);
4596 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4599 * Patch in the VMCALL instruction:
4601 hypercall[0] = 0x0f;
4602 hypercall[1] = 0x01;
4603 hypercall[2] = 0xc1;
4606 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4607 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4609 if (is_guest_mode(vcpu)) {
4610 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4611 unsigned long orig_val = val;
4614 * We get here when L2 changed cr0 in a way that did not change
4615 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4616 * but did change L0 shadowed bits. So we first calculate the
4617 * effective cr0 value that L1 would like to write into the
4618 * hardware. It consists of the L2-owned bits from the new
4619 * value combined with the L1-owned bits from L1's guest_cr0.
4621 val = (val & ~vmcs12->cr0_guest_host_mask) |
4622 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4624 if (!nested_guest_cr0_valid(vcpu, val))
4627 if (kvm_set_cr0(vcpu, val))
4629 vmcs_writel(CR0_READ_SHADOW, orig_val);
4632 if (to_vmx(vcpu)->nested.vmxon &&
4633 !nested_host_cr0_valid(vcpu, val))
4636 return kvm_set_cr0(vcpu, val);
4640 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4642 if (is_guest_mode(vcpu)) {
4643 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4644 unsigned long orig_val = val;
4646 /* analogously to handle_set_cr0 */
4647 val = (val & ~vmcs12->cr4_guest_host_mask) |
4648 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4649 if (kvm_set_cr4(vcpu, val))
4651 vmcs_writel(CR4_READ_SHADOW, orig_val);
4654 return kvm_set_cr4(vcpu, val);
4657 static int handle_desc(struct kvm_vcpu *vcpu)
4659 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4660 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4663 static int handle_cr(struct kvm_vcpu *vcpu)
4665 unsigned long exit_qualification, val;
4671 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4672 cr = exit_qualification & 15;
4673 reg = (exit_qualification >> 8) & 15;
4674 switch ((exit_qualification >> 4) & 3) {
4675 case 0: /* mov to cr */
4676 val = kvm_register_readl(vcpu, reg);
4677 trace_kvm_cr_write(cr, val);
4680 err = handle_set_cr0(vcpu, val);
4681 return kvm_complete_insn_gp(vcpu, err);
4683 WARN_ON_ONCE(enable_unrestricted_guest);
4684 err = kvm_set_cr3(vcpu, val);
4685 return kvm_complete_insn_gp(vcpu, err);
4687 err = handle_set_cr4(vcpu, val);
4688 return kvm_complete_insn_gp(vcpu, err);
4690 u8 cr8_prev = kvm_get_cr8(vcpu);
4692 err = kvm_set_cr8(vcpu, cr8);
4693 ret = kvm_complete_insn_gp(vcpu, err);
4694 if (lapic_in_kernel(vcpu))
4696 if (cr8_prev <= cr8)
4699 * TODO: we might be squashing a
4700 * KVM_GUESTDBG_SINGLESTEP-triggered
4701 * KVM_EXIT_DEBUG here.
4703 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4709 WARN_ONCE(1, "Guest should always own CR0.TS");
4710 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4711 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4712 return kvm_skip_emulated_instruction(vcpu);
4713 case 1: /*mov from cr*/
4716 WARN_ON_ONCE(enable_unrestricted_guest);
4717 val = kvm_read_cr3(vcpu);
4718 kvm_register_write(vcpu, reg, val);
4719 trace_kvm_cr_read(cr, val);
4720 return kvm_skip_emulated_instruction(vcpu);
4722 val = kvm_get_cr8(vcpu);
4723 kvm_register_write(vcpu, reg, val);
4724 trace_kvm_cr_read(cr, val);
4725 return kvm_skip_emulated_instruction(vcpu);
4729 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4730 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4731 kvm_lmsw(vcpu, val);
4733 return kvm_skip_emulated_instruction(vcpu);
4737 vcpu->run->exit_reason = 0;
4738 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4739 (int)(exit_qualification >> 4) & 3, cr);
4743 static int handle_dr(struct kvm_vcpu *vcpu)
4745 unsigned long exit_qualification;
4748 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4749 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
4751 /* First, if DR does not exist, trigger UD */
4752 if (!kvm_require_dr(vcpu, dr))
4755 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
4756 if (!kvm_require_cpl(vcpu, 0))
4758 dr7 = vmcs_readl(GUEST_DR7);
4761 * As the vm-exit takes precedence over the debug trap, we
4762 * need to emulate the latter, either for the host or the
4763 * guest debugging itself.
4765 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
4766 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
4767 vcpu->run->debug.arch.dr7 = dr7;
4768 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
4769 vcpu->run->debug.arch.exception = DB_VECTOR;
4770 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
4773 vcpu->arch.dr6 &= ~15;
4774 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
4775 kvm_queue_exception(vcpu, DB_VECTOR);
4780 if (vcpu->guest_debug == 0) {
4781 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4782 CPU_BASED_MOV_DR_EXITING);
4785 * No more DR vmexits; force a reload of the debug registers
4786 * and reenter on this instruction. The next vmexit will
4787 * retrieve the full state of the debug registers.
4789 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4793 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
4794 if (exit_qualification & TYPE_MOV_FROM_DR) {
4797 if (kvm_get_dr(vcpu, dr, &val))
4799 kvm_register_write(vcpu, reg, val);
4801 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
4804 return kvm_skip_emulated_instruction(vcpu);
4807 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
4809 return vcpu->arch.dr6;
4812 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
4816 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
4818 get_debugreg(vcpu->arch.db[0], 0);
4819 get_debugreg(vcpu->arch.db[1], 1);
4820 get_debugreg(vcpu->arch.db[2], 2);
4821 get_debugreg(vcpu->arch.db[3], 3);
4822 get_debugreg(vcpu->arch.dr6, 6);
4823 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
4825 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
4826 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
4829 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
4831 vmcs_writel(GUEST_DR7, val);
4834 static int handle_cpuid(struct kvm_vcpu *vcpu)
4836 return kvm_emulate_cpuid(vcpu);
4839 static int handle_rdmsr(struct kvm_vcpu *vcpu)
4841 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4842 struct msr_data msr_info;
4844 msr_info.index = ecx;
4845 msr_info.host_initiated = false;
4846 if (vmx_get_msr(vcpu, &msr_info)) {
4847 trace_kvm_msr_read_ex(ecx);
4848 kvm_inject_gp(vcpu, 0);
4852 trace_kvm_msr_read(ecx, msr_info.data);
4854 /* FIXME: handling of bits 32:63 of rax, rdx */
4855 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
4856 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
4857 return kvm_skip_emulated_instruction(vcpu);
4860 static int handle_wrmsr(struct kvm_vcpu *vcpu)
4862 struct msr_data msr;
4863 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4864 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
4865 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
4869 msr.host_initiated = false;
4870 if (kvm_set_msr(vcpu, &msr) != 0) {
4871 trace_kvm_msr_write_ex(ecx, data);
4872 kvm_inject_gp(vcpu, 0);
4876 trace_kvm_msr_write(ecx, data);
4877 return kvm_skip_emulated_instruction(vcpu);
4880 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
4882 kvm_apic_update_ppr(vcpu);
4886 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
4888 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4889 CPU_BASED_VIRTUAL_INTR_PENDING);
4891 kvm_make_request(KVM_REQ_EVENT, vcpu);
4893 ++vcpu->stat.irq_window_exits;
4897 static int handle_halt(struct kvm_vcpu *vcpu)
4899 return kvm_emulate_halt(vcpu);
4902 static int handle_vmcall(struct kvm_vcpu *vcpu)
4904 return kvm_emulate_hypercall(vcpu);
4907 static int handle_invd(struct kvm_vcpu *vcpu)
4909 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4912 static int handle_invlpg(struct kvm_vcpu *vcpu)
4914 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4916 kvm_mmu_invlpg(vcpu, exit_qualification);
4917 return kvm_skip_emulated_instruction(vcpu);
4920 static int handle_rdpmc(struct kvm_vcpu *vcpu)
4924 err = kvm_rdpmc(vcpu);
4925 return kvm_complete_insn_gp(vcpu, err);
4928 static int handle_wbinvd(struct kvm_vcpu *vcpu)
4930 return kvm_emulate_wbinvd(vcpu);
4933 static int handle_xsetbv(struct kvm_vcpu *vcpu)
4935 u64 new_bv = kvm_read_edx_eax(vcpu);
4936 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
4938 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
4939 return kvm_skip_emulated_instruction(vcpu);
4943 static int handle_xsaves(struct kvm_vcpu *vcpu)
4945 kvm_skip_emulated_instruction(vcpu);
4946 WARN(1, "this should never happen\n");
4950 static int handle_xrstors(struct kvm_vcpu *vcpu)
4952 kvm_skip_emulated_instruction(vcpu);
4953 WARN(1, "this should never happen\n");
4957 static int handle_apic_access(struct kvm_vcpu *vcpu)
4959 if (likely(fasteoi)) {
4960 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4961 int access_type, offset;
4963 access_type = exit_qualification & APIC_ACCESS_TYPE;
4964 offset = exit_qualification & APIC_ACCESS_OFFSET;
4966 * Sane guest uses MOV to write EOI, with written value
4967 * not cared. So make a short-circuit here by avoiding
4968 * heavy instruction emulation.
4970 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
4971 (offset == APIC_EOI)) {
4972 kvm_lapic_set_eoi(vcpu);
4973 return kvm_skip_emulated_instruction(vcpu);
4976 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4979 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
4981 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4982 int vector = exit_qualification & 0xff;
4984 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
4985 kvm_apic_set_eoi_accelerated(vcpu, vector);
4989 static int handle_apic_write(struct kvm_vcpu *vcpu)
4991 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4992 u32 offset = exit_qualification & 0xfff;
4994 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
4995 kvm_apic_write_nodecode(vcpu, offset);
4999 static int handle_task_switch(struct kvm_vcpu *vcpu)
5001 struct vcpu_vmx *vmx = to_vmx(vcpu);
5002 unsigned long exit_qualification;
5003 bool has_error_code = false;
5006 int reason, type, idt_v, idt_index;
5008 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5009 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5010 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5012 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5014 reason = (u32)exit_qualification >> 30;
5015 if (reason == TASK_SWITCH_GATE && idt_v) {
5017 case INTR_TYPE_NMI_INTR:
5018 vcpu->arch.nmi_injected = false;
5019 vmx_set_nmi_mask(vcpu, true);
5021 case INTR_TYPE_EXT_INTR:
5022 case INTR_TYPE_SOFT_INTR:
5023 kvm_clear_interrupt_queue(vcpu);
5025 case INTR_TYPE_HARD_EXCEPTION:
5026 if (vmx->idt_vectoring_info &
5027 VECTORING_INFO_DELIVER_CODE_MASK) {
5028 has_error_code = true;
5030 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5033 case INTR_TYPE_SOFT_EXCEPTION:
5034 kvm_clear_exception_queue(vcpu);
5040 tss_selector = exit_qualification;
5042 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5043 type != INTR_TYPE_EXT_INTR &&
5044 type != INTR_TYPE_NMI_INTR))
5045 skip_emulated_instruction(vcpu);
5047 if (kvm_task_switch(vcpu, tss_selector,
5048 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
5049 has_error_code, error_code) == EMULATE_FAIL) {
5050 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5051 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5052 vcpu->run->internal.ndata = 0;
5057 * TODO: What about debug traps on tss switch?
5058 * Are we supposed to inject them and update dr6?
5064 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5066 unsigned long exit_qualification;
5070 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5073 * EPT violation happened while executing iret from NMI,
5074 * "blocked by NMI" bit has to be set before next VM entry.
5075 * There are errata that may cause this bit to not be set:
5078 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5080 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5081 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5083 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5084 trace_kvm_page_fault(gpa, exit_qualification);
5086 /* Is it a read fault? */
5087 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5088 ? PFERR_USER_MASK : 0;
5089 /* Is it a write fault? */
5090 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5091 ? PFERR_WRITE_MASK : 0;
5092 /* Is it a fetch fault? */
5093 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5094 ? PFERR_FETCH_MASK : 0;
5095 /* ept page table entry is present? */
5096 error_code |= (exit_qualification &
5097 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5098 EPT_VIOLATION_EXECUTABLE))
5099 ? PFERR_PRESENT_MASK : 0;
5101 error_code |= (exit_qualification & 0x100) != 0 ?
5102 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5104 vcpu->arch.exit_qualification = exit_qualification;
5105 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5108 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5113 * A nested guest cannot optimize MMIO vmexits, because we have an
5114 * nGPA here instead of the required GPA.
5116 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5117 if (!is_guest_mode(vcpu) &&
5118 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5119 trace_kvm_fast_mmio(gpa);
5121 * Doing kvm_skip_emulated_instruction() depends on undefined
5122 * behavior: Intel's manual doesn't mandate
5123 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
5124 * occurs and while on real hardware it was observed to be set,
5125 * other hypervisors (namely Hyper-V) don't set it, we end up
5126 * advancing IP with some random value. Disable fast mmio when
5127 * running nested and keep it for real hardware in hope that
5128 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
5130 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
5131 return kvm_skip_emulated_instruction(vcpu);
5133 return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
5137 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5140 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5142 WARN_ON_ONCE(!enable_vnmi);
5143 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
5144 CPU_BASED_VIRTUAL_NMI_PENDING);
5145 ++vcpu->stat.nmi_window_exits;
5146 kvm_make_request(KVM_REQ_EVENT, vcpu);
5151 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5153 struct vcpu_vmx *vmx = to_vmx(vcpu);
5154 enum emulation_result err = EMULATE_DONE;
5157 bool intr_window_requested;
5158 unsigned count = 130;
5161 * We should never reach the point where we are emulating L2
5162 * due to invalid guest state as that means we incorrectly
5163 * allowed a nested VMEntry with an invalid vmcs12.
5165 WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
5167 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5168 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
5170 while (vmx->emulation_required && count-- != 0) {
5171 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5172 return handle_interrupt_window(&vmx->vcpu);
5174 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5177 err = kvm_emulate_instruction(vcpu, 0);
5179 if (err == EMULATE_USER_EXIT) {
5180 ++vcpu->stat.mmio_exits;
5185 if (err != EMULATE_DONE)
5186 goto emulation_error;
5188 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5189 vcpu->arch.exception.pending)
5190 goto emulation_error;
5192 if (vcpu->arch.halt_request) {
5193 vcpu->arch.halt_request = 0;
5194 ret = kvm_vcpu_halt(vcpu);
5198 if (signal_pending(current))
5208 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5209 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5210 vcpu->run->internal.ndata = 0;
5214 static void grow_ple_window(struct kvm_vcpu *vcpu)
5216 struct vcpu_vmx *vmx = to_vmx(vcpu);
5217 int old = vmx->ple_window;
5219 vmx->ple_window = __grow_ple_window(old, ple_window,
5223 if (vmx->ple_window != old)
5224 vmx->ple_window_dirty = true;
5226 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
5229 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5231 struct vcpu_vmx *vmx = to_vmx(vcpu);
5232 int old = vmx->ple_window;
5234 vmx->ple_window = __shrink_ple_window(old, ple_window,
5238 if (vmx->ple_window != old)
5239 vmx->ple_window_dirty = true;
5241 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
5245 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5247 static void wakeup_handler(void)
5249 struct kvm_vcpu *vcpu;
5250 int cpu = smp_processor_id();
5252 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5253 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5254 blocked_vcpu_list) {
5255 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5257 if (pi_test_on(pi_desc) == 1)
5258 kvm_vcpu_kick(vcpu);
5260 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5263 static void vmx_enable_tdp(void)
5265 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5266 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5267 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5268 0ull, VMX_EPT_EXECUTABLE_MASK,
5269 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5270 VMX_EPT_RWX_MASK, 0ull);
5272 ept_set_mmio_spte_mask();
5277 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5278 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5280 static int handle_pause(struct kvm_vcpu *vcpu)
5282 if (!kvm_pause_in_guest(vcpu->kvm))
5283 grow_ple_window(vcpu);
5286 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5287 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5288 * never set PAUSE_EXITING and just set PLE if supported,
5289 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5291 kvm_vcpu_on_spin(vcpu, true);
5292 return kvm_skip_emulated_instruction(vcpu);
5295 static int handle_nop(struct kvm_vcpu *vcpu)
5297 return kvm_skip_emulated_instruction(vcpu);
5300 static int handle_mwait(struct kvm_vcpu *vcpu)
5302 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5303 return handle_nop(vcpu);
5306 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5308 kvm_queue_exception(vcpu, UD_VECTOR);
5312 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5317 static int handle_monitor(struct kvm_vcpu *vcpu)
5319 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5320 return handle_nop(vcpu);
5323 static int handle_invpcid(struct kvm_vcpu *vcpu)
5325 u32 vmx_instruction_info;
5329 struct x86_exception e;
5331 unsigned long roots_to_free = 0;
5337 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5338 kvm_queue_exception(vcpu, UD_VECTOR);
5342 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5343 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5346 kvm_inject_gp(vcpu, 0);
5350 /* According to the Intel instruction reference, the memory operand
5351 * is read even if it isn't needed (e.g., for type==all)
5353 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5354 vmx_instruction_info, false, &gva))
5357 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5358 kvm_inject_page_fault(vcpu, &e);
5362 if (operand.pcid >> 12 != 0) {
5363 kvm_inject_gp(vcpu, 0);
5367 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5370 case INVPCID_TYPE_INDIV_ADDR:
5371 if ((!pcid_enabled && (operand.pcid != 0)) ||
5372 is_noncanonical_address(operand.gla, vcpu)) {
5373 kvm_inject_gp(vcpu, 0);
5376 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5377 return kvm_skip_emulated_instruction(vcpu);
5379 case INVPCID_TYPE_SINGLE_CTXT:
5380 if (!pcid_enabled && (operand.pcid != 0)) {
5381 kvm_inject_gp(vcpu, 0);
5385 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5386 kvm_mmu_sync_roots(vcpu);
5387 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5390 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5391 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
5393 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5395 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5397 * If neither the current cr3 nor any of the prev_roots use the
5398 * given PCID, then nothing needs to be done here because a
5399 * resync will happen anyway before switching to any other CR3.
5402 return kvm_skip_emulated_instruction(vcpu);
5404 case INVPCID_TYPE_ALL_NON_GLOBAL:
5406 * Currently, KVM doesn't mark global entries in the shadow
5407 * page tables, so a non-global flush just degenerates to a
5408 * global flush. If needed, we could optimize this later by
5409 * keeping track of global entries in shadow page tables.
5413 case INVPCID_TYPE_ALL_INCL_GLOBAL:
5414 kvm_mmu_unload(vcpu);
5415 return kvm_skip_emulated_instruction(vcpu);
5418 BUG(); /* We have already checked above that type <= 3 */
5422 static int handle_pml_full(struct kvm_vcpu *vcpu)
5424 unsigned long exit_qualification;
5426 trace_kvm_pml_full(vcpu->vcpu_id);
5428 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5431 * PML buffer FULL happened while executing iret from NMI,
5432 * "blocked by NMI" bit has to be set before next VM entry.
5434 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5436 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5437 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5438 GUEST_INTR_STATE_NMI);
5441 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5442 * here.., and there's no userspace involvement needed for PML.
5447 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5449 if (!to_vmx(vcpu)->req_immediate_exit)
5450 kvm_lapic_expired_hv_timer(vcpu);
5455 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5456 * are overwritten by nested_vmx_setup() when nested=1.
5458 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5460 kvm_queue_exception(vcpu, UD_VECTOR);
5464 static int handle_encls(struct kvm_vcpu *vcpu)
5467 * SGX virtualization is not yet supported. There is no software
5468 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5469 * to prevent the guest from executing ENCLS.
5471 kvm_queue_exception(vcpu, UD_VECTOR);
5476 * The exit handlers return 1 if the exit was handled fully and guest execution
5477 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5478 * to be done to userspace and return 0.
5480 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5481 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
5482 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5483 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5484 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5485 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5486 [EXIT_REASON_CR_ACCESS] = handle_cr,
5487 [EXIT_REASON_DR_ACCESS] = handle_dr,
5488 [EXIT_REASON_CPUID] = handle_cpuid,
5489 [EXIT_REASON_MSR_READ] = handle_rdmsr,
5490 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
5491 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
5492 [EXIT_REASON_HLT] = handle_halt,
5493 [EXIT_REASON_INVD] = handle_invd,
5494 [EXIT_REASON_INVLPG] = handle_invlpg,
5495 [EXIT_REASON_RDPMC] = handle_rdpmc,
5496 [EXIT_REASON_VMCALL] = handle_vmcall,
5497 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5498 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5499 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5500 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5501 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5502 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5503 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5504 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5505 [EXIT_REASON_VMON] = handle_vmx_instruction,
5506 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5507 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5508 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5509 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5510 [EXIT_REASON_WBINVD] = handle_wbinvd,
5511 [EXIT_REASON_XSETBV] = handle_xsetbv,
5512 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5513 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5514 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5515 [EXIT_REASON_LDTR_TR] = handle_desc,
5516 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5517 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5518 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5519 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5520 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5521 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5522 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5523 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5524 [EXIT_REASON_RDRAND] = handle_invalid_op,
5525 [EXIT_REASON_RDSEED] = handle_invalid_op,
5526 [EXIT_REASON_XSAVES] = handle_xsaves,
5527 [EXIT_REASON_XRSTORS] = handle_xrstors,
5528 [EXIT_REASON_PML_FULL] = handle_pml_full,
5529 [EXIT_REASON_INVPCID] = handle_invpcid,
5530 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5531 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5532 [EXIT_REASON_ENCLS] = handle_encls,
5535 static const int kvm_vmx_max_exit_handlers =
5536 ARRAY_SIZE(kvm_vmx_exit_handlers);
5538 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5540 *info1 = vmcs_readl(EXIT_QUALIFICATION);
5541 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
5544 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5547 __free_page(vmx->pml_pg);
5552 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5554 struct vcpu_vmx *vmx = to_vmx(vcpu);
5558 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5560 /* Do nothing if PML buffer is empty */
5561 if (pml_idx == (PML_ENTITY_NUM - 1))
5564 /* PML index always points to next available PML buffer entity */
5565 if (pml_idx >= PML_ENTITY_NUM)
5570 pml_buf = page_address(vmx->pml_pg);
5571 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5574 gpa = pml_buf[pml_idx];
5575 WARN_ON(gpa & (PAGE_SIZE - 1));
5576 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5579 /* reset PML index */
5580 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5584 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5585 * Called before reporting dirty_bitmap to userspace.
5587 static void kvm_flush_pml_buffers(struct kvm *kvm)
5590 struct kvm_vcpu *vcpu;
5592 * We only need to kick vcpu out of guest mode here, as PML buffer
5593 * is flushed at beginning of all VMEXITs, and it's obvious that only
5594 * vcpus running in guest are possible to have unflushed GPAs in PML
5597 kvm_for_each_vcpu(i, vcpu, kvm)
5598 kvm_vcpu_kick(vcpu);
5601 static void vmx_dump_sel(char *name, uint32_t sel)
5603 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5604 name, vmcs_read16(sel),
5605 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5606 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5607 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5610 static void vmx_dump_dtsel(char *name, uint32_t limit)
5612 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5613 name, vmcs_read32(limit),
5614 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5617 static void dump_vmcs(void)
5619 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5620 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5621 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5622 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5623 u32 secondary_exec_control = 0;
5624 unsigned long cr4 = vmcs_readl(GUEST_CR4);
5625 u64 efer = vmcs_read64(GUEST_IA32_EFER);
5628 if (cpu_has_secondary_exec_ctrls())
5629 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5631 pr_err("*** Guest State ***\n");
5632 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5633 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5634 vmcs_readl(CR0_GUEST_HOST_MASK));
5635 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5636 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5637 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5638 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5639 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5641 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5642 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5643 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5644 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5646 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5647 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5648 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5649 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5650 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5651 vmcs_readl(GUEST_SYSENTER_ESP),
5652 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5653 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5654 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5655 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5656 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5657 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5658 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5659 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5660 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5661 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5662 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5663 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5664 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5665 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5666 efer, vmcs_read64(GUEST_IA32_PAT));
5667 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5668 vmcs_read64(GUEST_IA32_DEBUGCTL),
5669 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5670 if (cpu_has_load_perf_global_ctrl() &&
5671 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5672 pr_err("PerfGlobCtl = 0x%016llx\n",
5673 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5674 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5675 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5676 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5677 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5678 vmcs_read32(GUEST_ACTIVITY_STATE));
5679 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5680 pr_err("InterruptStatus = %04x\n",
5681 vmcs_read16(GUEST_INTR_STATUS));
5683 pr_err("*** Host State ***\n");
5684 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5685 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5686 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5687 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5688 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5689 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5690 vmcs_read16(HOST_TR_SELECTOR));
5691 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5692 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5693 vmcs_readl(HOST_TR_BASE));
5694 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5695 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5696 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5697 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5698 vmcs_readl(HOST_CR4));
5699 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5700 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5701 vmcs_read32(HOST_IA32_SYSENTER_CS),
5702 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5703 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5704 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5705 vmcs_read64(HOST_IA32_EFER),
5706 vmcs_read64(HOST_IA32_PAT));
5707 if (cpu_has_load_perf_global_ctrl() &&
5708 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5709 pr_err("PerfGlobCtl = 0x%016llx\n",
5710 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5712 pr_err("*** Control State ***\n");
5713 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5714 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5715 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5716 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5717 vmcs_read32(EXCEPTION_BITMAP),
5718 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5719 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5720 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5721 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5722 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5723 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5724 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5725 vmcs_read32(VM_EXIT_INTR_INFO),
5726 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5727 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5728 pr_err(" reason=%08x qualification=%016lx\n",
5729 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5730 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5731 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5732 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5733 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5734 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5735 pr_err("TSC Multiplier = 0x%016llx\n",
5736 vmcs_read64(TSC_MULTIPLIER));
5737 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
5738 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5739 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5740 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5741 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5742 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5743 n = vmcs_read32(CR3_TARGET_COUNT);
5744 for (i = 0; i + 1 < n; i += 4)
5745 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
5746 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
5747 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
5749 pr_err("CR3 target%u=%016lx\n",
5750 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
5751 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5752 pr_err("PLE Gap=%08x Window=%08x\n",
5753 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5754 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5755 pr_err("Virtual processor ID = 0x%04x\n",
5756 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5760 * The guest has exited. See if we can fix it or if we need userspace
5763 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
5765 struct vcpu_vmx *vmx = to_vmx(vcpu);
5766 u32 exit_reason = vmx->exit_reason;
5767 u32 vectoring_info = vmx->idt_vectoring_info;
5769 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
5772 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5773 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5774 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5775 * mode as if vcpus is in root mode, the PML buffer must has been
5779 vmx_flush_pml_buffer(vcpu);
5781 /* If guest state is invalid, start emulating */
5782 if (vmx->emulation_required)
5783 return handle_invalid_guest_state(vcpu);
5785 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
5786 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
5788 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5790 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5791 vcpu->run->fail_entry.hardware_entry_failure_reason
5796 if (unlikely(vmx->fail)) {
5797 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5798 vcpu->run->fail_entry.hardware_entry_failure_reason
5799 = vmcs_read32(VM_INSTRUCTION_ERROR);
5805 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5806 * delivery event since it indicates guest is accessing MMIO.
5807 * The vm-exit can be triggered again after return to guest that
5808 * will cause infinite loop.
5810 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5811 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5812 exit_reason != EXIT_REASON_EPT_VIOLATION &&
5813 exit_reason != EXIT_REASON_PML_FULL &&
5814 exit_reason != EXIT_REASON_TASK_SWITCH)) {
5815 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5816 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
5817 vcpu->run->internal.ndata = 3;
5818 vcpu->run->internal.data[0] = vectoring_info;
5819 vcpu->run->internal.data[1] = exit_reason;
5820 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
5821 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
5822 vcpu->run->internal.ndata++;
5823 vcpu->run->internal.data[3] =
5824 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5829 if (unlikely(!enable_vnmi &&
5830 vmx->loaded_vmcs->soft_vnmi_blocked)) {
5831 if (vmx_interrupt_allowed(vcpu)) {
5832 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5833 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
5834 vcpu->arch.nmi_pending) {
5836 * This CPU don't support us in finding the end of an
5837 * NMI-blocked window if the guest runs with IRQs
5838 * disabled. So we pull the trigger after 1 s of
5839 * futile waiting, but inform the user about this.
5841 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
5842 "state on VCPU %d after 1 s timeout\n",
5843 __func__, vcpu->vcpu_id);
5844 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5848 if (exit_reason < kvm_vmx_max_exit_handlers
5849 && kvm_vmx_exit_handlers[exit_reason])
5850 return kvm_vmx_exit_handlers[exit_reason](vcpu);
5852 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
5854 kvm_queue_exception(vcpu, UD_VECTOR);
5860 * Software based L1D cache flush which is used when microcode providing
5861 * the cache control MSR is not loaded.
5863 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
5864 * flush it is required to read in 64 KiB because the replacement algorithm
5865 * is not exactly LRU. This could be sized at runtime via topology
5866 * information but as all relevant affected CPUs have 32KiB L1D cache size
5867 * there is no point in doing so.
5869 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
5871 int size = PAGE_SIZE << L1D_CACHE_ORDER;
5874 * This code is only executed when the the flush mode is 'cond' or
5877 if (static_branch_likely(&vmx_l1d_flush_cond)) {
5881 * Clear the per-vcpu flush bit, it gets set again
5882 * either from vcpu_run() or from one of the unsafe
5885 flush_l1d = vcpu->arch.l1tf_flush_l1d;
5886 vcpu->arch.l1tf_flush_l1d = false;
5889 * Clear the per-cpu flush bit, it gets set again from
5890 * the interrupt handlers.
5892 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
5893 kvm_clear_cpu_l1tf_flush_l1d();
5899 vcpu->stat.l1d_flush++;
5901 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
5902 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
5907 /* First ensure the pages are in the TLB */
5908 "xorl %%eax, %%eax\n"
5909 ".Lpopulate_tlb:\n\t"
5910 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5911 "addl $4096, %%eax\n\t"
5912 "cmpl %%eax, %[size]\n\t"
5913 "jne .Lpopulate_tlb\n\t"
5914 "xorl %%eax, %%eax\n\t"
5916 /* Now fill the cache */
5917 "xorl %%eax, %%eax\n"
5919 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5920 "addl $64, %%eax\n\t"
5921 "cmpl %%eax, %[size]\n\t"
5922 "jne .Lfill_cache\n\t"
5924 :: [flush_pages] "r" (vmx_l1d_flush_pages),
5926 : "eax", "ebx", "ecx", "edx");
5929 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5931 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5933 if (is_guest_mode(vcpu) &&
5934 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
5937 if (irr == -1 || tpr < irr) {
5938 vmcs_write32(TPR_THRESHOLD, 0);
5942 vmcs_write32(TPR_THRESHOLD, irr);
5945 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5947 u32 sec_exec_control;
5949 if (!lapic_in_kernel(vcpu))
5952 if (!flexpriority_enabled &&
5953 !cpu_has_vmx_virtualize_x2apic_mode())
5956 /* Postpone execution until vmcs01 is the current VMCS. */
5957 if (is_guest_mode(vcpu)) {
5958 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
5962 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5963 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
5964 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
5966 switch (kvm_get_apic_mode(vcpu)) {
5967 case LAPIC_MODE_INVALID:
5968 WARN_ONCE(true, "Invalid local APIC state");
5969 case LAPIC_MODE_DISABLED:
5971 case LAPIC_MODE_XAPIC:
5972 if (flexpriority_enabled) {
5974 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5975 vmx_flush_tlb(vcpu, true);
5978 case LAPIC_MODE_X2APIC:
5979 if (cpu_has_vmx_virtualize_x2apic_mode())
5981 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5984 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
5986 vmx_update_msr_bitmap(vcpu);
5989 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
5991 if (!is_guest_mode(vcpu)) {
5992 vmcs_write64(APIC_ACCESS_ADDR, hpa);
5993 vmx_flush_tlb(vcpu, true);
5997 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6005 status = vmcs_read16(GUEST_INTR_STATUS);
6007 if (max_isr != old) {
6009 status |= max_isr << 8;
6010 vmcs_write16(GUEST_INTR_STATUS, status);
6014 static void vmx_set_rvi(int vector)
6022 status = vmcs_read16(GUEST_INTR_STATUS);
6023 old = (u8)status & 0xff;
6024 if ((u8)vector != old) {
6026 status |= (u8)vector;
6027 vmcs_write16(GUEST_INTR_STATUS, status);
6031 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6034 * When running L2, updating RVI is only relevant when
6035 * vmcs12 virtual-interrupt-delivery enabled.
6036 * However, it can be enabled only when L1 also
6037 * intercepts external-interrupts and in that case
6038 * we should not update vmcs02 RVI but instead intercept
6039 * interrupt. Therefore, do nothing when running L2.
6041 if (!is_guest_mode(vcpu))
6042 vmx_set_rvi(max_irr);
6045 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6047 struct vcpu_vmx *vmx = to_vmx(vcpu);
6049 bool max_irr_updated;
6051 WARN_ON(!vcpu->arch.apicv_active);
6052 if (pi_test_on(&vmx->pi_desc)) {
6053 pi_clear_on(&vmx->pi_desc);
6055 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
6056 * But on x86 this is just a compiler barrier anyway.
6058 smp_mb__after_atomic();
6060 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6063 * If we are running L2 and L1 has a new pending interrupt
6064 * which can be injected, we should re-evaluate
6065 * what should be done with this new L1 interrupt.
6066 * If L1 intercepts external-interrupts, we should
6067 * exit from L2 to L1. Otherwise, interrupt should be
6068 * delivered directly to L2.
6070 if (is_guest_mode(vcpu) && max_irr_updated) {
6071 if (nested_exit_on_intr(vcpu))
6072 kvm_vcpu_exiting_guest_mode(vcpu);
6074 kvm_make_request(KVM_REQ_EVENT, vcpu);
6077 max_irr = kvm_lapic_find_highest_irr(vcpu);
6079 vmx_hwapic_irr_update(vcpu, max_irr);
6083 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6085 if (!kvm_vcpu_apicv_active(vcpu))
6088 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6089 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6090 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6091 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6094 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6096 struct vcpu_vmx *vmx = to_vmx(vcpu);
6098 pi_clear_on(&vmx->pi_desc);
6099 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6102 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
6104 u32 exit_intr_info = 0;
6105 u16 basic_exit_reason = (u16)vmx->exit_reason;
6107 if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
6108 || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
6111 if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6112 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6113 vmx->exit_intr_info = exit_intr_info;
6115 /* if exit due to PF check for async PF */
6116 if (is_page_fault(exit_intr_info))
6117 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
6119 /* Handle machine checks before interrupts are enabled */
6120 if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
6121 is_machine_check(exit_intr_info))
6122 kvm_machine_check();
6124 /* We need to handle NMIs before interrupts are enabled */
6125 if (is_nmi(exit_intr_info)) {
6126 kvm_before_interrupt(&vmx->vcpu);
6128 kvm_after_interrupt(&vmx->vcpu);
6132 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
6134 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6136 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
6137 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
6138 unsigned int vector;
6139 unsigned long entry;
6141 struct vcpu_vmx *vmx = to_vmx(vcpu);
6142 #ifdef CONFIG_X86_64
6146 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6147 desc = (gate_desc *)vmx->host_idt_base + vector;
6148 entry = gate_offset(desc);
6150 #ifdef CONFIG_X86_64
6151 "mov %%" _ASM_SP ", %[sp]\n\t"
6152 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
6157 __ASM_SIZE(push) " $%c[cs]\n\t"
6160 #ifdef CONFIG_X86_64
6165 THUNK_TARGET(entry),
6166 [ss]"i"(__KERNEL_DS),
6167 [cs]"i"(__KERNEL_CS)
6171 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
6173 static bool vmx_has_emulated_msr(int index)
6176 case MSR_IA32_SMBASE:
6178 * We cannot do SMM unless we can run the guest in big
6181 return enable_unrestricted_guest || emulate_invalid_guest_state;
6182 case MSR_AMD64_VIRT_SPEC_CTRL:
6183 /* This is AMD only. */
6190 static bool vmx_pt_supported(void)
6192 return pt_mode == PT_MODE_HOST_GUEST;
6195 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6200 bool idtv_info_valid;
6202 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6205 if (vmx->loaded_vmcs->nmi_known_unmasked)
6208 * Can't use vmx->exit_intr_info since we're not sure what
6209 * the exit reason is.
6211 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6212 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6213 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6215 * SDM 3: 27.7.1.2 (September 2008)
6216 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6217 * a guest IRET fault.
6218 * SDM 3: 23.2.2 (September 2008)
6219 * Bit 12 is undefined in any of the following cases:
6220 * If the VM exit sets the valid bit in the IDT-vectoring
6221 * information field.
6222 * If the VM exit is due to a double fault.
6224 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6225 vector != DF_VECTOR && !idtv_info_valid)
6226 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6227 GUEST_INTR_STATE_NMI);
6229 vmx->loaded_vmcs->nmi_known_unmasked =
6230 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6231 & GUEST_INTR_STATE_NMI);
6232 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6233 vmx->loaded_vmcs->vnmi_blocked_time +=
6234 ktime_to_ns(ktime_sub(ktime_get(),
6235 vmx->loaded_vmcs->entry_time));
6238 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6239 u32 idt_vectoring_info,
6240 int instr_len_field,
6241 int error_code_field)
6245 bool idtv_info_valid;
6247 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6249 vcpu->arch.nmi_injected = false;
6250 kvm_clear_exception_queue(vcpu);
6251 kvm_clear_interrupt_queue(vcpu);
6253 if (!idtv_info_valid)
6256 kvm_make_request(KVM_REQ_EVENT, vcpu);
6258 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6259 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6262 case INTR_TYPE_NMI_INTR:
6263 vcpu->arch.nmi_injected = true;
6265 * SDM 3: 27.7.1.2 (September 2008)
6266 * Clear bit "block by NMI" before VM entry if a NMI
6269 vmx_set_nmi_mask(vcpu, false);
6271 case INTR_TYPE_SOFT_EXCEPTION:
6272 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6274 case INTR_TYPE_HARD_EXCEPTION:
6275 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6276 u32 err = vmcs_read32(error_code_field);
6277 kvm_requeue_exception_e(vcpu, vector, err);
6279 kvm_requeue_exception(vcpu, vector);
6281 case INTR_TYPE_SOFT_INTR:
6282 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6284 case INTR_TYPE_EXT_INTR:
6285 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6292 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6294 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6295 VM_EXIT_INSTRUCTION_LEN,
6296 IDT_VECTORING_ERROR_CODE);
6299 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6301 __vmx_complete_interrupts(vcpu,
6302 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6303 VM_ENTRY_INSTRUCTION_LEN,
6304 VM_ENTRY_EXCEPTION_ERROR_CODE);
6306 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6309 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6312 struct perf_guest_switch_msr *msrs;
6314 msrs = perf_guest_get_msrs(&nr_msrs);
6319 for (i = 0; i < nr_msrs; i++)
6320 if (msrs[i].host == msrs[i].guest)
6321 clear_atomic_switch_msr(vmx, msrs[i].msr);
6323 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6324 msrs[i].host, false);
6327 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
6329 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
6330 if (!vmx->loaded_vmcs->hv_timer_armed)
6331 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
6332 PIN_BASED_VMX_PREEMPTION_TIMER);
6333 vmx->loaded_vmcs->hv_timer_armed = true;
6336 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6338 struct vcpu_vmx *vmx = to_vmx(vcpu);
6342 if (vmx->req_immediate_exit) {
6343 vmx_arm_hv_timer(vmx, 0);
6347 if (vmx->hv_deadline_tsc != -1) {
6349 if (vmx->hv_deadline_tsc > tscl)
6350 /* set_hv_timer ensures the delta fits in 32-bits */
6351 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6352 cpu_preemption_timer_multi);
6356 vmx_arm_hv_timer(vmx, delta_tsc);
6360 if (vmx->loaded_vmcs->hv_timer_armed)
6361 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
6362 PIN_BASED_VMX_PREEMPTION_TIMER);
6363 vmx->loaded_vmcs->hv_timer_armed = false;
6366 void vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6368 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6369 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6370 vmcs_writel(HOST_RSP, host_rsp);
6374 static void __vmx_vcpu_run(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx)
6376 if (static_branch_unlikely(&vmx_l1d_should_flush))
6377 vmx_l1d_flush(vcpu);
6379 if (vcpu->arch.cr2 != read_cr2())
6380 write_cr2(vcpu->arch.cr2);
6383 /* Store host registers */
6384 "push %%" _ASM_BP " \n\t"
6385 "sub $%c[wordsize], %%" _ASM_SP "\n\t" /* placeholder for guest RCX */
6386 "push %%" _ASM_ARG1 " \n\t"
6388 /* Adjust RSP to account for the CALL to vmx_vmenter(). */
6389 "lea -%c[wordsize](%%" _ASM_SP "), %%" _ASM_ARG2 " \n\t"
6390 "call vmx_update_host_rsp \n\t"
6392 /* Load the vcpu_vmx pointer to RCX. */
6393 "mov (%%" _ASM_SP "), %%" _ASM_CX " \n\t"
6395 /* Check if vmlaunch or vmresume is needed */
6396 "cmpb $0, %%bl \n\t"
6398 /* Load guest registers. Don't clobber flags. */
6399 "mov %c[rax](%%" _ASM_CX "), %%" _ASM_AX " \n\t"
6400 "mov %c[rbx](%%" _ASM_CX "), %%" _ASM_BX " \n\t"
6401 "mov %c[rdx](%%" _ASM_CX "), %%" _ASM_DX " \n\t"
6402 "mov %c[rsi](%%" _ASM_CX "), %%" _ASM_SI " \n\t"
6403 "mov %c[rdi](%%" _ASM_CX "), %%" _ASM_DI " \n\t"
6404 "mov %c[rbp](%%" _ASM_CX "), %%" _ASM_BP " \n\t"
6405 #ifdef CONFIG_X86_64
6406 "mov %c[r8](%%" _ASM_CX "), %%r8 \n\t"
6407 "mov %c[r9](%%" _ASM_CX "), %%r9 \n\t"
6408 "mov %c[r10](%%" _ASM_CX "), %%r10 \n\t"
6409 "mov %c[r11](%%" _ASM_CX "), %%r11 \n\t"
6410 "mov %c[r12](%%" _ASM_CX "), %%r12 \n\t"
6411 "mov %c[r13](%%" _ASM_CX "), %%r13 \n\t"
6412 "mov %c[r14](%%" _ASM_CX "), %%r14 \n\t"
6413 "mov %c[r15](%%" _ASM_CX "), %%r15 \n\t"
6415 /* Load guest RCX. This kills the vmx_vcpu pointer! */
6416 "mov %c[rcx](%%" _ASM_CX "), %%" _ASM_CX " \n\t"
6418 /* Enter guest mode */
6419 "call vmx_vmenter\n\t"
6421 /* Save guest's RCX to the stack placeholder (see above) */
6422 "mov %%" _ASM_CX ", %c[wordsize](%%" _ASM_SP ") \n\t"
6424 /* Load host's RCX, i.e. the vmx_vcpu pointer */
6425 "pop %%" _ASM_CX " \n\t"
6427 /* Set vmx->fail based on EFLAGS.{CF,ZF} */
6428 "setbe %c[fail](%%" _ASM_CX ")\n\t"
6430 /* Save all guest registers, including RCX from the stack */
6431 "mov %%" _ASM_AX ", %c[rax](%%" _ASM_CX ") \n\t"
6432 "mov %%" _ASM_BX ", %c[rbx](%%" _ASM_CX ") \n\t"
6433 __ASM_SIZE(pop) " %c[rcx](%%" _ASM_CX ") \n\t"
6434 "mov %%" _ASM_DX ", %c[rdx](%%" _ASM_CX ") \n\t"
6435 "mov %%" _ASM_SI ", %c[rsi](%%" _ASM_CX ") \n\t"
6436 "mov %%" _ASM_DI ", %c[rdi](%%" _ASM_CX ") \n\t"
6437 "mov %%" _ASM_BP ", %c[rbp](%%" _ASM_CX ") \n\t"
6438 #ifdef CONFIG_X86_64
6439 "mov %%r8, %c[r8](%%" _ASM_CX ") \n\t"
6440 "mov %%r9, %c[r9](%%" _ASM_CX ") \n\t"
6441 "mov %%r10, %c[r10](%%" _ASM_CX ") \n\t"
6442 "mov %%r11, %c[r11](%%" _ASM_CX ") \n\t"
6443 "mov %%r12, %c[r12](%%" _ASM_CX ") \n\t"
6444 "mov %%r13, %c[r13](%%" _ASM_CX ") \n\t"
6445 "mov %%r14, %c[r14](%%" _ASM_CX ") \n\t"
6446 "mov %%r15, %c[r15](%%" _ASM_CX ") \n\t"
6449 * Clear all general purpose registers (except RSP, which is loaded by
6450 * the CPU during VM-Exit) to prevent speculative use of the guest's
6451 * values, even those that are saved/loaded via the stack. In theory,
6452 * an L1 cache miss when restoring registers could lead to speculative
6453 * execution with the guest's values. Zeroing XORs are dirt cheap,
6454 * i.e. the extra paranoia is essentially free.
6456 "xor %%r8d, %%r8d \n\t"
6457 "xor %%r9d, %%r9d \n\t"
6458 "xor %%r10d, %%r10d \n\t"
6459 "xor %%r11d, %%r11d \n\t"
6460 "xor %%r12d, %%r12d \n\t"
6461 "xor %%r13d, %%r13d \n\t"
6462 "xor %%r14d, %%r14d \n\t"
6463 "xor %%r15d, %%r15d \n\t"
6465 "xor %%eax, %%eax \n\t"
6466 "xor %%ebx, %%ebx \n\t"
6467 "xor %%ecx, %%ecx \n\t"
6468 "xor %%edx, %%edx \n\t"
6469 "xor %%esi, %%esi \n\t"
6470 "xor %%edi, %%edi \n\t"
6471 "xor %%ebp, %%ebp \n\t"
6472 "pop %%" _ASM_BP " \n\t"
6473 : ASM_CALL_CONSTRAINT, "=b"((int){0}),
6474 #ifdef CONFIG_X86_64
6481 "b"(vmx->loaded_vmcs->launched),
6482 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
6483 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
6484 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
6485 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
6486 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
6487 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
6488 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
6489 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
6490 #ifdef CONFIG_X86_64
6491 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
6492 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
6493 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
6494 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
6495 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
6496 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
6497 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
6498 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
6500 [wordsize]"i"(sizeof(ulong))
6502 #ifdef CONFIG_X86_64
6503 , "rax", "rcx", "rdx", "rsi"
6504 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
6506 , "ecx", "edx", "edi", "esi"
6510 vcpu->arch.cr2 = read_cr2();
6512 STACK_FRAME_NON_STANDARD(__vmx_vcpu_run);
6514 static void vmx_vcpu_run(struct kvm_vcpu *vcpu)
6516 struct vcpu_vmx *vmx = to_vmx(vcpu);
6517 unsigned long cr3, cr4;
6519 /* Record the guest's net vcpu time for enforced NMI injections. */
6520 if (unlikely(!enable_vnmi &&
6521 vmx->loaded_vmcs->soft_vnmi_blocked))
6522 vmx->loaded_vmcs->entry_time = ktime_get();
6524 /* Don't enter VMX if guest state is invalid, let the exit handler
6525 start emulation until we arrive back to a valid state */
6526 if (vmx->emulation_required)
6529 if (vmx->ple_window_dirty) {
6530 vmx->ple_window_dirty = false;
6531 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6534 if (vmx->nested.need_vmcs12_sync)
6535 nested_sync_from_vmcs12(vcpu);
6537 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
6538 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6539 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
6540 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6542 cr3 = __get_current_cr3_fast();
6543 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6544 vmcs_writel(HOST_CR3, cr3);
6545 vmx->loaded_vmcs->host_state.cr3 = cr3;
6548 cr4 = cr4_read_shadow();
6549 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6550 vmcs_writel(HOST_CR4, cr4);
6551 vmx->loaded_vmcs->host_state.cr4 = cr4;
6554 /* When single-stepping over STI and MOV SS, we must clear the
6555 * corresponding interruptibility bits in the guest state. Otherwise
6556 * vmentry fails as it then expects bit 14 (BS) in pending debug
6557 * exceptions being set, but that's not correct for the guest debugging
6559 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6560 vmx_set_interrupt_shadow(vcpu, 0);
6562 if (static_cpu_has(X86_FEATURE_PKU) &&
6563 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
6564 vcpu->arch.pkru != vmx->host_pkru)
6565 __write_pkru(vcpu->arch.pkru);
6567 pt_guest_enter(vmx);
6569 atomic_switch_perf_msrs(vmx);
6571 vmx_update_hv_timer(vcpu);
6574 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6575 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6576 * is no need to worry about the conditional branch over the wrmsr
6577 * being speculatively taken.
6579 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6581 __vmx_vcpu_run(vcpu, vmx);
6584 * We do not use IBRS in the kernel. If this vCPU has used the
6585 * SPEC_CTRL MSR it may have left it on; save the value and
6586 * turn it off. This is much more efficient than blindly adding
6587 * it to the atomic save/restore list. Especially as the former
6588 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6590 * For non-nested case:
6591 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6595 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6598 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6599 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6601 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6603 /* Eliminate branch target predictions from guest mode */
6606 /* All fields are clean at this point */
6607 if (static_branch_unlikely(&enable_evmcs))
6608 current_evmcs->hv_clean_fields |=
6609 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6611 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6612 if (vmx->host_debugctlmsr)
6613 update_debugctlmsr(vmx->host_debugctlmsr);
6615 #ifndef CONFIG_X86_64
6617 * The sysexit path does not restore ds/es, so we must set them to
6618 * a reasonable value ourselves.
6620 * We can't defer this to vmx_prepare_switch_to_host() since that
6621 * function may be executed in interrupt context, which saves and
6622 * restore segments around it, nullifying its effect.
6624 loadsegment(ds, __USER_DS);
6625 loadsegment(es, __USER_DS);
6628 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
6629 | (1 << VCPU_EXREG_RFLAGS)
6630 | (1 << VCPU_EXREG_PDPTR)
6631 | (1 << VCPU_EXREG_SEGMENTS)
6632 | (1 << VCPU_EXREG_CR3));
6633 vcpu->arch.regs_dirty = 0;
6638 * eager fpu is enabled if PKEY is supported and CR4 is switched
6639 * back on host, so it is safe to read guest PKRU from current
6642 if (static_cpu_has(X86_FEATURE_PKU) &&
6643 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
6644 vcpu->arch.pkru = __read_pkru();
6645 if (vcpu->arch.pkru != vmx->host_pkru)
6646 __write_pkru(vmx->host_pkru);
6649 vmx->nested.nested_run_pending = 0;
6650 vmx->idt_vectoring_info = 0;
6652 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
6653 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6656 vmx->loaded_vmcs->launched = 1;
6657 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6659 vmx_complete_atomic_exit(vmx);
6660 vmx_recover_nmi_blocking(vmx);
6661 vmx_complete_interrupts(vmx);
6664 static struct kvm *vmx_vm_alloc(void)
6666 struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
6667 return &kvm_vmx->kvm;
6670 static void vmx_vm_free(struct kvm *kvm)
6672 vfree(to_kvm_vmx(kvm));
6675 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6677 struct vcpu_vmx *vmx = to_vmx(vcpu);
6680 vmx_destroy_pml_buffer(vmx);
6681 free_vpid(vmx->vpid);
6682 leave_guest_mode(vcpu);
6683 nested_vmx_free_vcpu(vcpu);
6684 free_loaded_vmcs(vmx->loaded_vmcs);
6685 kfree(vmx->guest_msrs);
6686 kvm_vcpu_uninit(vcpu);
6687 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6688 kmem_cache_free(kvm_vcpu_cache, vmx);
6691 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
6694 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
6695 unsigned long *msr_bitmap;
6699 return ERR_PTR(-ENOMEM);
6701 vmx->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache, GFP_KERNEL);
6702 if (!vmx->vcpu.arch.guest_fpu) {
6703 printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
6705 goto free_partial_vcpu;
6708 vmx->vpid = allocate_vpid();
6710 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
6717 * If PML is turned on, failure on enabling PML just results in failure
6718 * of creating the vcpu, therefore we can simplify PML logic (by
6719 * avoiding dealing with cases, such as enabling PML partially on vcpus
6720 * for the guest, etc.
6723 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
6728 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
6729 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
6732 if (!vmx->guest_msrs)
6735 err = alloc_loaded_vmcs(&vmx->vmcs01);
6739 msr_bitmap = vmx->vmcs01.msr_bitmap;
6740 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6741 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6742 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6743 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6744 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6745 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6746 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6747 vmx->msr_bitmap_mode = 0;
6749 vmx->loaded_vmcs = &vmx->vmcs01;
6751 vmx_vcpu_load(&vmx->vcpu, cpu);
6752 vmx->vcpu.cpu = cpu;
6753 vmx_vcpu_setup(vmx);
6754 vmx_vcpu_put(&vmx->vcpu);
6756 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
6757 err = alloc_apic_access_page(kvm);
6762 if (enable_ept && !enable_unrestricted_guest) {
6763 err = init_rmode_identity_map(kvm);
6769 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
6771 kvm_vcpu_apicv_active(&vmx->vcpu));
6773 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6775 vmx->nested.posted_intr_nv = -1;
6776 vmx->nested.current_vmptr = -1ull;
6778 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
6781 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6782 * or POSTED_INTR_WAKEUP_VECTOR.
6784 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6785 vmx->pi_desc.sn = 1;
6787 vmx->ept_pointer = INVALID_PAGE;
6792 free_loaded_vmcs(vmx->loaded_vmcs);
6794 kfree(vmx->guest_msrs);
6796 vmx_destroy_pml_buffer(vmx);
6798 kvm_vcpu_uninit(&vmx->vcpu);
6800 free_vpid(vmx->vpid);
6801 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6803 kmem_cache_free(kvm_vcpu_cache, vmx);
6804 return ERR_PTR(err);
6807 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/l1tf.html for details.\n"
6808 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/l1tf.html for details.\n"
6810 static int vmx_vm_init(struct kvm *kvm)
6812 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
6815 kvm->arch.pause_in_guest = true;
6817 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6818 switch (l1tf_mitigation) {
6819 case L1TF_MITIGATION_OFF:
6820 case L1TF_MITIGATION_FLUSH_NOWARN:
6821 /* 'I explicitly don't care' is set */
6823 case L1TF_MITIGATION_FLUSH:
6824 case L1TF_MITIGATION_FLUSH_NOSMT:
6825 case L1TF_MITIGATION_FULL:
6827 * Warn upon starting the first VM in a potentially
6828 * insecure environment.
6830 if (sched_smt_active())
6831 pr_warn_once(L1TF_MSG_SMT);
6832 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6833 pr_warn_once(L1TF_MSG_L1D);
6835 case L1TF_MITIGATION_FULL_FORCE:
6836 /* Flush is enforced */
6843 static void __init vmx_check_processor_compat(void *rtn)
6845 struct vmcs_config vmcs_conf;
6846 struct vmx_capability vmx_cap;
6849 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
6852 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept,
6854 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6855 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6856 smp_processor_id());
6861 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6866 /* For VT-d and EPT combination
6867 * 1. MMIO: always map as UC
6869 * a. VT-d without snooping control feature: can't guarantee the
6870 * result, try to trust guest.
6871 * b. VT-d with snooping control feature: snooping control feature of
6872 * VT-d engine can guarantee the cache correctness. Just set it
6873 * to WB to keep consistent with host. So the same as item 3.
6874 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
6875 * consistent with host MTRR
6878 cache = MTRR_TYPE_UNCACHABLE;
6882 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
6883 ipat = VMX_EPT_IPAT_BIT;
6884 cache = MTRR_TYPE_WRBACK;
6888 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
6889 ipat = VMX_EPT_IPAT_BIT;
6890 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
6891 cache = MTRR_TYPE_WRBACK;
6893 cache = MTRR_TYPE_UNCACHABLE;
6897 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
6900 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
6903 static int vmx_get_lpage_level(void)
6905 if (enable_ept && !cpu_has_vmx_ept_1g_page())
6906 return PT_DIRECTORY_LEVEL;
6908 /* For shadow and EPT supported 1GB page */
6909 return PT_PDPE_LEVEL;
6912 static void vmcs_set_secondary_exec_control(u32 new_ctl)
6915 * These bits in the secondary execution controls field
6916 * are dynamic, the others are mostly based on the hypervisor
6917 * architecture and the guest's CPUID. Do not touch the
6921 SECONDARY_EXEC_SHADOW_VMCS |
6922 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
6923 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6924 SECONDARY_EXEC_DESC;
6926 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6928 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6929 (new_ctl & ~mask) | (cur_ctl & mask));
6933 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
6934 * (indicating "allowed-1") if they are supported in the guest's CPUID.
6936 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
6938 struct vcpu_vmx *vmx = to_vmx(vcpu);
6939 struct kvm_cpuid_entry2 *entry;
6941 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
6942 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
6944 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
6945 if (entry && (entry->_reg & (_cpuid_mask))) \
6946 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
6949 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
6950 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
6951 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
6952 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
6953 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
6954 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
6955 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
6956 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
6957 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
6958 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
6959 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
6960 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
6961 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
6962 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
6963 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
6965 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
6966 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
6967 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
6968 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
6969 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
6970 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
6972 #undef cr4_fixed1_update
6975 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
6977 struct vcpu_vmx *vmx = to_vmx(vcpu);
6979 if (kvm_mpx_supported()) {
6980 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
6983 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
6984 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
6986 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
6987 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
6992 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
6994 struct vcpu_vmx *vmx = to_vmx(vcpu);
6995 struct kvm_cpuid_entry2 *best = NULL;
6998 for (i = 0; i < PT_CPUID_LEAVES; i++) {
6999 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7002 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7003 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7004 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7005 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7008 /* Get the number of configurable Address Ranges for filtering */
7009 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7010 PT_CAP_num_address_ranges);
7012 /* Initialize and clear the no dependency bits */
7013 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7014 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7017 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7018 * will inject an #GP
7020 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7021 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7024 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7025 * PSBFreq can be set
7027 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7028 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7029 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7032 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7033 * MTCFreq can be set
7035 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7036 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7037 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7039 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7040 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7041 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7044 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7045 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7046 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7048 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7049 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7050 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7052 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
7053 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7054 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7056 /* unmask address range configure area */
7057 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7058 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7061 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
7063 struct vcpu_vmx *vmx = to_vmx(vcpu);
7065 if (cpu_has_secondary_exec_ctrls()) {
7066 vmx_compute_secondary_exec_control(vmx);
7067 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
7070 if (nested_vmx_allowed(vcpu))
7071 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7072 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7074 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7075 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7077 if (nested_vmx_allowed(vcpu)) {
7078 nested_vmx_cr_fixed1_bits_update(vcpu);
7079 nested_vmx_entry_exit_ctls_update(vcpu);
7082 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7083 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7084 update_intel_pt_cfg(vcpu);
7087 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
7089 if (func == 1 && nested)
7090 entry->ecx |= bit(X86_FEATURE_VMX);
7093 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7095 to_vmx(vcpu)->req_immediate_exit = true;
7098 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7099 struct x86_instruction_info *info,
7100 enum x86_intercept_stage stage)
7102 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7103 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7106 * RDPID causes #UD if disabled through secondary execution controls.
7107 * Because it is marked as EmulateOnUD, we need to intercept it here.
7109 if (info->intercept == x86_intercept_rdtscp &&
7110 !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
7111 ctxt->exception.vector = UD_VECTOR;
7112 ctxt->exception.error_code_valid = false;
7113 return X86EMUL_PROPAGATE_FAULT;
7116 /* TODO: check more intercepts... */
7117 return X86EMUL_CONTINUE;
7120 #ifdef CONFIG_X86_64
7121 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7122 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7123 u64 divisor, u64 *result)
7125 u64 low = a << shift, high = a >> (64 - shift);
7127 /* To avoid the overflow on divq */
7128 if (high >= divisor)
7131 /* Low hold the result, high hold rem which is discarded */
7132 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7133 "rm" (divisor), "0" (low), "1" (high));
7139 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
7141 struct vcpu_vmx *vmx;
7142 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7144 if (kvm_mwait_in_guest(vcpu->kvm))
7149 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7150 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7151 lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
7153 if (delta_tsc > lapic_timer_advance_cycles)
7154 delta_tsc -= lapic_timer_advance_cycles;
7158 /* Convert to host delta tsc if tsc scaling is enabled */
7159 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7160 u64_shl_div_u64(delta_tsc,
7161 kvm_tsc_scaling_ratio_frac_bits,
7162 vcpu->arch.tsc_scaling_ratio,
7167 * If the delta tsc can't fit in the 32 bit after the multi shift,
7168 * we can't use the preemption timer.
7169 * It's possible that it fits on later vmentries, but checking
7170 * on every vmentry is costly so we just use an hrtimer.
7172 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7175 vmx->hv_deadline_tsc = tscl + delta_tsc;
7176 return delta_tsc == 0;
7179 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7181 to_vmx(vcpu)->hv_deadline_tsc = -1;
7185 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7187 if (!kvm_pause_in_guest(vcpu->kvm))
7188 shrink_ple_window(vcpu);
7191 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7192 struct kvm_memory_slot *slot)
7194 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7195 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7198 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7199 struct kvm_memory_slot *slot)
7201 kvm_mmu_slot_set_dirty(kvm, slot);
7204 static void vmx_flush_log_dirty(struct kvm *kvm)
7206 kvm_flush_pml_buffers(kvm);
7209 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
7211 struct vmcs12 *vmcs12;
7212 struct vcpu_vmx *vmx = to_vmx(vcpu);
7214 struct page *page = NULL;
7217 if (is_guest_mode(vcpu)) {
7218 WARN_ON_ONCE(vmx->nested.pml_full);
7221 * Check if PML is enabled for the nested guest.
7222 * Whether eptp bit 6 is set is already checked
7223 * as part of A/D emulation.
7225 vmcs12 = get_vmcs12(vcpu);
7226 if (!nested_cpu_has_pml(vmcs12))
7229 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
7230 vmx->nested.pml_full = true;
7234 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
7236 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
7237 if (is_error_page(page))
7240 pml_address = kmap(page);
7241 pml_address[vmcs12->guest_pml_index--] = gpa;
7243 kvm_release_page_clean(page);
7249 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7250 struct kvm_memory_slot *memslot,
7251 gfn_t offset, unsigned long mask)
7253 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7256 static void __pi_post_block(struct kvm_vcpu *vcpu)
7258 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7259 struct pi_desc old, new;
7263 old.control = new.control = pi_desc->control;
7264 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
7265 "Wakeup handler not enabled while the VCPU is blocked\n");
7267 dest = cpu_physical_id(vcpu->cpu);
7269 if (x2apic_enabled())
7272 new.ndst = (dest << 8) & 0xFF00;
7274 /* set 'NV' to 'notification vector' */
7275 new.nv = POSTED_INTR_VECTOR;
7276 } while (cmpxchg64(&pi_desc->control, old.control,
7277 new.control) != old.control);
7279 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
7280 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7281 list_del(&vcpu->blocked_vcpu_list);
7282 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7283 vcpu->pre_pcpu = -1;
7288 * This routine does the following things for vCPU which is going
7289 * to be blocked if VT-d PI is enabled.
7290 * - Store the vCPU to the wakeup list, so when interrupts happen
7291 * we can find the right vCPU to wake up.
7292 * - Change the Posted-interrupt descriptor as below:
7293 * 'NDST' <-- vcpu->pre_pcpu
7294 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
7295 * - If 'ON' is set during this process, which means at least one
7296 * interrupt is posted for this vCPU, we cannot block it, in
7297 * this case, return 1, otherwise, return 0.
7300 static int pi_pre_block(struct kvm_vcpu *vcpu)
7303 struct pi_desc old, new;
7304 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7306 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
7307 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7308 !kvm_vcpu_apicv_active(vcpu))
7311 WARN_ON(irqs_disabled());
7312 local_irq_disable();
7313 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
7314 vcpu->pre_pcpu = vcpu->cpu;
7315 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7316 list_add_tail(&vcpu->blocked_vcpu_list,
7317 &per_cpu(blocked_vcpu_on_cpu,
7319 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7323 old.control = new.control = pi_desc->control;
7325 WARN((pi_desc->sn == 1),
7326 "Warning: SN field of posted-interrupts "
7327 "is set before blocking\n");
7330 * Since vCPU can be preempted during this process,
7331 * vcpu->cpu could be different with pre_pcpu, we
7332 * need to set pre_pcpu as the destination of wakeup
7333 * notification event, then we can find the right vCPU
7334 * to wakeup in wakeup handler if interrupts happen
7335 * when the vCPU is in blocked state.
7337 dest = cpu_physical_id(vcpu->pre_pcpu);
7339 if (x2apic_enabled())
7342 new.ndst = (dest << 8) & 0xFF00;
7344 /* set 'NV' to 'wakeup vector' */
7345 new.nv = POSTED_INTR_WAKEUP_VECTOR;
7346 } while (cmpxchg64(&pi_desc->control, old.control,
7347 new.control) != old.control);
7349 /* We should not block the vCPU if an interrupt is posted for it. */
7350 if (pi_test_on(pi_desc) == 1)
7351 __pi_post_block(vcpu);
7354 return (vcpu->pre_pcpu == -1);
7357 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7359 if (pi_pre_block(vcpu))
7362 if (kvm_lapic_hv_timer_in_use(vcpu))
7363 kvm_lapic_switch_to_sw_timer(vcpu);
7368 static void pi_post_block(struct kvm_vcpu *vcpu)
7370 if (vcpu->pre_pcpu == -1)
7373 WARN_ON(irqs_disabled());
7374 local_irq_disable();
7375 __pi_post_block(vcpu);
7379 static void vmx_post_block(struct kvm_vcpu *vcpu)
7381 if (kvm_x86_ops->set_hv_timer)
7382 kvm_lapic_switch_to_hv_timer(vcpu);
7384 pi_post_block(vcpu);
7388 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
7391 * @host_irq: host irq of the interrupt
7392 * @guest_irq: gsi of the interrupt
7393 * @set: set or unset PI
7394 * returns 0 on success, < 0 on failure
7396 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7397 uint32_t guest_irq, bool set)
7399 struct kvm_kernel_irq_routing_entry *e;
7400 struct kvm_irq_routing_table *irq_rt;
7401 struct kvm_lapic_irq irq;
7402 struct kvm_vcpu *vcpu;
7403 struct vcpu_data vcpu_info;
7406 if (!kvm_arch_has_assigned_device(kvm) ||
7407 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7408 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7411 idx = srcu_read_lock(&kvm->irq_srcu);
7412 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7413 if (guest_irq >= irq_rt->nr_rt_entries ||
7414 hlist_empty(&irq_rt->map[guest_irq])) {
7415 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7416 guest_irq, irq_rt->nr_rt_entries);
7420 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7421 if (e->type != KVM_IRQ_ROUTING_MSI)
7424 * VT-d PI cannot support posting multicast/broadcast
7425 * interrupts to a vCPU, we still use interrupt remapping
7426 * for these kind of interrupts.
7428 * For lowest-priority interrupts, we only support
7429 * those with single CPU as the destination, e.g. user
7430 * configures the interrupts via /proc/irq or uses
7431 * irqbalance to make the interrupts single-CPU.
7433 * We will support full lowest-priority interrupt later.
7436 kvm_set_msi_irq(kvm, e, &irq);
7437 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
7439 * Make sure the IRTE is in remapped mode if
7440 * we don't handle it in posted mode.
7442 ret = irq_set_vcpu_affinity(host_irq, NULL);
7445 "failed to back to remapped mode, irq: %u\n",
7453 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7454 vcpu_info.vector = irq.vector;
7456 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7457 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7460 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7462 ret = irq_set_vcpu_affinity(host_irq, NULL);
7465 printk(KERN_INFO "%s: failed to update PI IRTE\n",
7473 srcu_read_unlock(&kvm->irq_srcu, idx);
7477 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7479 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7480 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7481 FEATURE_CONTROL_LMCE;
7483 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7484 ~FEATURE_CONTROL_LMCE;
7487 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
7489 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7490 if (to_vmx(vcpu)->nested.nested_run_pending)
7495 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7497 struct vcpu_vmx *vmx = to_vmx(vcpu);
7499 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7500 if (vmx->nested.smm.guest_mode)
7501 nested_vmx_vmexit(vcpu, -1, 0, 0);
7503 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7504 vmx->nested.vmxon = false;
7505 vmx_clear_hlt(vcpu);
7509 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
7511 struct vcpu_vmx *vmx = to_vmx(vcpu);
7514 if (vmx->nested.smm.vmxon) {
7515 vmx->nested.vmxon = true;
7516 vmx->nested.smm.vmxon = false;
7519 if (vmx->nested.smm.guest_mode) {
7520 vcpu->arch.hflags &= ~HF_SMM_MASK;
7521 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7522 vcpu->arch.hflags |= HF_SMM_MASK;
7526 vmx->nested.smm.guest_mode = false;
7531 static int enable_smi_window(struct kvm_vcpu *vcpu)
7536 static __init int hardware_setup(void)
7538 unsigned long host_bndcfgs;
7541 rdmsrl_safe(MSR_EFER, &host_efer);
7543 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7544 kvm_define_shared_msr(i, vmx_msr_index[i]);
7546 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7549 if (boot_cpu_has(X86_FEATURE_NX))
7550 kvm_enable_efer_bits(EFER_NX);
7552 if (boot_cpu_has(X86_FEATURE_MPX)) {
7553 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7554 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7557 if (boot_cpu_has(X86_FEATURE_XSAVES))
7558 rdmsrl(MSR_IA32_XSS, host_xss);
7560 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7561 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7564 if (!cpu_has_vmx_ept() ||
7565 !cpu_has_vmx_ept_4levels() ||
7566 !cpu_has_vmx_ept_mt_wb() ||
7567 !cpu_has_vmx_invept_global())
7570 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7571 enable_ept_ad_bits = 0;
7573 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7574 enable_unrestricted_guest = 0;
7576 if (!cpu_has_vmx_flexpriority())
7577 flexpriority_enabled = 0;
7579 if (!cpu_has_virtual_nmis())
7583 * set_apic_access_page_addr() is used to reload apic access
7584 * page upon invalidation. No need to do anything if not
7585 * using the APIC_ACCESS_ADDR VMCS field.
7587 if (!flexpriority_enabled)
7588 kvm_x86_ops->set_apic_access_page_addr = NULL;
7590 if (!cpu_has_vmx_tpr_shadow())
7591 kvm_x86_ops->update_cr8_intercept = NULL;
7593 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7594 kvm_disable_largepages();
7596 #if IS_ENABLED(CONFIG_HYPERV)
7597 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7599 kvm_x86_ops->tlb_remote_flush = hv_remote_flush_tlb;
7600 kvm_x86_ops->tlb_remote_flush_with_range =
7601 hv_remote_flush_tlb_with_range;
7605 if (!cpu_has_vmx_ple()) {
7608 ple_window_grow = 0;
7610 ple_window_shrink = 0;
7613 if (!cpu_has_vmx_apicv()) {
7615 kvm_x86_ops->sync_pir_to_irr = NULL;
7618 if (cpu_has_vmx_tsc_scaling()) {
7619 kvm_has_tsc_control = true;
7620 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7621 kvm_tsc_scaling_ratio_frac_bits = 48;
7624 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7632 * Only enable PML when hardware supports PML feature, and both EPT
7633 * and EPT A/D bit features are enabled -- PML depends on them to work.
7635 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7639 kvm_x86_ops->slot_enable_log_dirty = NULL;
7640 kvm_x86_ops->slot_disable_log_dirty = NULL;
7641 kvm_x86_ops->flush_log_dirty = NULL;
7642 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7645 if (!cpu_has_vmx_preemption_timer())
7646 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7648 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7651 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7652 cpu_preemption_timer_multi =
7653 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7655 kvm_x86_ops->set_hv_timer = NULL;
7656 kvm_x86_ops->cancel_hv_timer = NULL;
7659 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7661 kvm_mce_cap_supported |= MCG_LMCE_P;
7663 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7665 if (!enable_ept || !cpu_has_vmx_intel_pt())
7666 pt_mode = PT_MODE_SYSTEM;
7669 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7670 vmx_capability.ept, enable_apicv);
7672 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7677 r = alloc_kvm_area();
7679 nested_vmx_hardware_unsetup();
7683 static __exit void hardware_unsetup(void)
7686 nested_vmx_hardware_unsetup();
7691 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
7692 .cpu_has_kvm_support = cpu_has_kvm_support,
7693 .disabled_by_bios = vmx_disabled_by_bios,
7694 .hardware_setup = hardware_setup,
7695 .hardware_unsetup = hardware_unsetup,
7696 .check_processor_compatibility = vmx_check_processor_compat,
7697 .hardware_enable = hardware_enable,
7698 .hardware_disable = hardware_disable,
7699 .cpu_has_accelerated_tpr = report_flexpriority,
7700 .has_emulated_msr = vmx_has_emulated_msr,
7702 .vm_init = vmx_vm_init,
7703 .vm_alloc = vmx_vm_alloc,
7704 .vm_free = vmx_vm_free,
7706 .vcpu_create = vmx_create_vcpu,
7707 .vcpu_free = vmx_free_vcpu,
7708 .vcpu_reset = vmx_vcpu_reset,
7710 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7711 .vcpu_load = vmx_vcpu_load,
7712 .vcpu_put = vmx_vcpu_put,
7714 .update_bp_intercept = update_exception_bitmap,
7715 .get_msr_feature = vmx_get_msr_feature,
7716 .get_msr = vmx_get_msr,
7717 .set_msr = vmx_set_msr,
7718 .get_segment_base = vmx_get_segment_base,
7719 .get_segment = vmx_get_segment,
7720 .set_segment = vmx_set_segment,
7721 .get_cpl = vmx_get_cpl,
7722 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7723 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
7724 .decache_cr3 = vmx_decache_cr3,
7725 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
7726 .set_cr0 = vmx_set_cr0,
7727 .set_cr3 = vmx_set_cr3,
7728 .set_cr4 = vmx_set_cr4,
7729 .set_efer = vmx_set_efer,
7730 .get_idt = vmx_get_idt,
7731 .set_idt = vmx_set_idt,
7732 .get_gdt = vmx_get_gdt,
7733 .set_gdt = vmx_set_gdt,
7734 .get_dr6 = vmx_get_dr6,
7735 .set_dr6 = vmx_set_dr6,
7736 .set_dr7 = vmx_set_dr7,
7737 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7738 .cache_reg = vmx_cache_reg,
7739 .get_rflags = vmx_get_rflags,
7740 .set_rflags = vmx_set_rflags,
7742 .tlb_flush = vmx_flush_tlb,
7743 .tlb_flush_gva = vmx_flush_tlb_gva,
7745 .run = vmx_vcpu_run,
7746 .handle_exit = vmx_handle_exit,
7747 .skip_emulated_instruction = skip_emulated_instruction,
7748 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7749 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7750 .patch_hypercall = vmx_patch_hypercall,
7751 .set_irq = vmx_inject_irq,
7752 .set_nmi = vmx_inject_nmi,
7753 .queue_exception = vmx_queue_exception,
7754 .cancel_injection = vmx_cancel_injection,
7755 .interrupt_allowed = vmx_interrupt_allowed,
7756 .nmi_allowed = vmx_nmi_allowed,
7757 .get_nmi_mask = vmx_get_nmi_mask,
7758 .set_nmi_mask = vmx_set_nmi_mask,
7759 .enable_nmi_window = enable_nmi_window,
7760 .enable_irq_window = enable_irq_window,
7761 .update_cr8_intercept = update_cr8_intercept,
7762 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7763 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7764 .get_enable_apicv = vmx_get_enable_apicv,
7765 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7766 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7767 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7768 .hwapic_irr_update = vmx_hwapic_irr_update,
7769 .hwapic_isr_update = vmx_hwapic_isr_update,
7770 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7771 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7772 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7774 .set_tss_addr = vmx_set_tss_addr,
7775 .set_identity_map_addr = vmx_set_identity_map_addr,
7776 .get_tdp_level = get_ept_level,
7777 .get_mt_mask = vmx_get_mt_mask,
7779 .get_exit_info = vmx_get_exit_info,
7781 .get_lpage_level = vmx_get_lpage_level,
7783 .cpuid_update = vmx_cpuid_update,
7785 .rdtscp_supported = vmx_rdtscp_supported,
7786 .invpcid_supported = vmx_invpcid_supported,
7788 .set_supported_cpuid = vmx_set_supported_cpuid,
7790 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7792 .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
7793 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7795 .set_tdp_cr3 = vmx_set_cr3,
7797 .check_intercept = vmx_check_intercept,
7798 .handle_external_intr = vmx_handle_external_intr,
7799 .mpx_supported = vmx_mpx_supported,
7800 .xsaves_supported = vmx_xsaves_supported,
7801 .umip_emulated = vmx_umip_emulated,
7802 .pt_supported = vmx_pt_supported,
7804 .request_immediate_exit = vmx_request_immediate_exit,
7806 .sched_in = vmx_sched_in,
7808 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7809 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7810 .flush_log_dirty = vmx_flush_log_dirty,
7811 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7812 .write_log_dirty = vmx_write_pml_buffer,
7814 .pre_block = vmx_pre_block,
7815 .post_block = vmx_post_block,
7817 .pmu_ops = &intel_pmu_ops,
7819 .update_pi_irte = vmx_update_pi_irte,
7821 #ifdef CONFIG_X86_64
7822 .set_hv_timer = vmx_set_hv_timer,
7823 .cancel_hv_timer = vmx_cancel_hv_timer,
7826 .setup_mce = vmx_setup_mce,
7828 .smi_allowed = vmx_smi_allowed,
7829 .pre_enter_smm = vmx_pre_enter_smm,
7830 .pre_leave_smm = vmx_pre_leave_smm,
7831 .enable_smi_window = enable_smi_window,
7833 .check_nested_events = NULL,
7834 .get_nested_state = NULL,
7835 .set_nested_state = NULL,
7836 .get_vmcs12_pages = NULL,
7837 .nested_enable_evmcs = NULL,
7840 static void vmx_cleanup_l1d_flush(void)
7842 if (vmx_l1d_flush_pages) {
7843 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7844 vmx_l1d_flush_pages = NULL;
7846 /* Restore state so sysfs ignores VMX */
7847 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
7850 static void vmx_exit(void)
7852 #ifdef CONFIG_KEXEC_CORE
7853 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
7859 #if IS_ENABLED(CONFIG_HYPERV)
7860 if (static_branch_unlikely(&enable_evmcs)) {
7862 struct hv_vp_assist_page *vp_ap;
7864 * Reset everything to support using non-enlightened VMCS
7865 * access later (e.g. when we reload the module with
7866 * enlightened_vmcs=0)
7868 for_each_online_cpu(cpu) {
7869 vp_ap = hv_get_vp_assist_page(cpu);
7874 vp_ap->current_nested_vmcs = 0;
7875 vp_ap->enlighten_vmentry = 0;
7878 static_branch_disable(&enable_evmcs);
7881 vmx_cleanup_l1d_flush();
7883 module_exit(vmx_exit);
7885 static int __init vmx_init(void)
7889 #if IS_ENABLED(CONFIG_HYPERV)
7891 * Enlightened VMCS usage should be recommended and the host needs
7892 * to support eVMCS v1 or above. We can also disable eVMCS support
7893 * with module parameter.
7895 if (enlightened_vmcs &&
7896 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
7897 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
7898 KVM_EVMCS_VERSION) {
7901 /* Check that we have assist pages on all online CPUs */
7902 for_each_online_cpu(cpu) {
7903 if (!hv_get_vp_assist_page(cpu)) {
7904 enlightened_vmcs = false;
7909 if (enlightened_vmcs) {
7910 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
7911 static_branch_enable(&enable_evmcs);
7914 enlightened_vmcs = false;
7918 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
7919 __alignof__(struct vcpu_vmx), THIS_MODULE);
7924 * Must be called after kvm_init() so enable_ept is properly set
7925 * up. Hand the parameter mitigation value in which was stored in
7926 * the pre module init parser. If no parameter was given, it will
7927 * contain 'auto' which will be turned into the default 'cond'
7930 if (boot_cpu_has(X86_BUG_L1TF)) {
7931 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
7938 #ifdef CONFIG_KEXEC_CORE
7939 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
7940 crash_vmclear_local_loaded_vmcss);
7942 vmx_check_vmcs12_offsets();
7946 module_init(vmx_init);