1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
16 #include <linux/frame.h>
17 #include <linux/highmem.h>
18 #include <linux/hrtimer.h>
19 #include <linux/kernel.h>
20 #include <linux/kvm_host.h>
21 #include <linux/module.h>
22 #include <linux/moduleparam.h>
23 #include <linux/mod_devicetable.h>
25 #include <linux/sched.h>
26 #include <linux/sched/smt.h>
27 #include <linux/slab.h>
28 #include <linux/tboot.h>
29 #include <linux/trace_events.h>
34 #include <asm/debugreg.h>
36 #include <asm/fpu/internal.h>
38 #include <asm/irq_remapping.h>
39 #include <asm/kexec.h>
40 #include <asm/perf_event.h>
42 #include <asm/mmu_context.h>
43 #include <asm/mshyperv.h>
44 #include <asm/spec-ctrl.h>
45 #include <asm/virtext.h>
48 #include "capabilities.h"
52 #include "kvm_cache_regs.h"
64 MODULE_AUTHOR("Qumranet");
65 MODULE_LICENSE("GPL");
67 static const struct x86_cpu_id vmx_cpu_id[] = {
68 X86_FEATURE_MATCH(X86_FEATURE_VMX),
71 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
73 bool __read_mostly enable_vpid = 1;
74 module_param_named(vpid, enable_vpid, bool, 0444);
76 static bool __read_mostly enable_vnmi = 1;
77 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
79 bool __read_mostly flexpriority_enabled = 1;
80 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
82 bool __read_mostly enable_ept = 1;
83 module_param_named(ept, enable_ept, bool, S_IRUGO);
85 bool __read_mostly enable_unrestricted_guest = 1;
86 module_param_named(unrestricted_guest,
87 enable_unrestricted_guest, bool, S_IRUGO);
89 bool __read_mostly enable_ept_ad_bits = 1;
90 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
92 static bool __read_mostly emulate_invalid_guest_state = true;
93 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
95 static bool __read_mostly fasteoi = 1;
96 module_param(fasteoi, bool, S_IRUGO);
98 bool __read_mostly enable_apicv = 1;
99 module_param(enable_apicv, bool, S_IRUGO);
102 * If nested=1, nested virtualization is supported, i.e., guests may use
103 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
104 * use VMX instructions.
106 static bool __read_mostly nested = 1;
107 module_param(nested, bool, S_IRUGO);
109 static u64 __read_mostly host_xss;
111 bool __read_mostly enable_pml = 1;
112 module_param_named(pml, enable_pml, bool, S_IRUGO);
114 static bool __read_mostly dump_invalid_vmcs = 0;
115 module_param(dump_invalid_vmcs, bool, 0644);
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)
212 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
213 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
218 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
222 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
225 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
226 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
227 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
232 /* If set to auto use the default l1tf mitigation method */
233 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
234 switch (l1tf_mitigation) {
235 case L1TF_MITIGATION_OFF:
236 l1tf = VMENTER_L1D_FLUSH_NEVER;
238 case L1TF_MITIGATION_FLUSH_NOWARN:
239 case L1TF_MITIGATION_FLUSH:
240 case L1TF_MITIGATION_FLUSH_NOSMT:
241 l1tf = VMENTER_L1D_FLUSH_COND;
243 case L1TF_MITIGATION_FULL:
244 case L1TF_MITIGATION_FULL_FORCE:
245 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
248 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
249 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
252 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
253 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
255 * This allocation for vmx_l1d_flush_pages is not tied to a VM
256 * lifetime and so should not be charged to a memcg.
258 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
261 vmx_l1d_flush_pages = page_address(page);
264 * Initialize each page with a different pattern in
265 * order to protect against KSM in the nested
266 * virtualization case.
268 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
269 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
274 l1tf_vmx_mitigation = l1tf;
276 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
277 static_branch_enable(&vmx_l1d_should_flush);
279 static_branch_disable(&vmx_l1d_should_flush);
281 if (l1tf == VMENTER_L1D_FLUSH_COND)
282 static_branch_enable(&vmx_l1d_flush_cond);
284 static_branch_disable(&vmx_l1d_flush_cond);
288 static int vmentry_l1d_flush_parse(const char *s)
293 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
294 if (vmentry_l1d_param[i].for_parse &&
295 sysfs_streq(s, vmentry_l1d_param[i].option))
302 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
306 l1tf = vmentry_l1d_flush_parse(s);
310 if (!boot_cpu_has(X86_BUG_L1TF))
314 * Has vmx_init() run already? If not then this is the pre init
315 * parameter parsing. In that case just store the value and let
316 * vmx_init() do the proper setup after enable_ept has been
319 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
320 vmentry_l1d_flush_param = l1tf;
324 mutex_lock(&vmx_l1d_flush_mutex);
325 ret = vmx_setup_l1d_flush(l1tf);
326 mutex_unlock(&vmx_l1d_flush_mutex);
330 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
332 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
333 return sprintf(s, "???\n");
335 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
338 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
339 .set = vmentry_l1d_flush_set,
340 .get = vmentry_l1d_flush_get,
342 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
344 static bool guest_state_valid(struct kvm_vcpu *vcpu);
345 static u32 vmx_segment_access_rights(struct kvm_segment *var);
346 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
349 void vmx_vmexit(void);
351 #define vmx_insn_failed(fmt...) \
354 pr_warn_ratelimited(fmt); \
357 asmlinkage void vmread_error(unsigned long field, bool fault)
360 kvm_spurious_fault();
362 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
365 noinline void vmwrite_error(unsigned long field, unsigned long value)
367 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
368 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
371 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
373 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
376 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
378 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
381 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
383 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
387 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
389 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
393 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
394 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
396 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
397 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
399 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
402 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
403 * can find which vCPU should be waken up.
405 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
406 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
408 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
409 static DEFINE_SPINLOCK(vmx_vpid_lock);
411 struct vmcs_config vmcs_config;
412 struct vmx_capability vmx_capability;
414 #define VMX_SEGMENT_FIELD(seg) \
415 [VCPU_SREG_##seg] = { \
416 .selector = GUEST_##seg##_SELECTOR, \
417 .base = GUEST_##seg##_BASE, \
418 .limit = GUEST_##seg##_LIMIT, \
419 .ar_bytes = GUEST_##seg##_AR_BYTES, \
422 static const struct kvm_vmx_segment_field {
427 } kvm_vmx_segment_fields[] = {
428 VMX_SEGMENT_FIELD(CS),
429 VMX_SEGMENT_FIELD(DS),
430 VMX_SEGMENT_FIELD(ES),
431 VMX_SEGMENT_FIELD(FS),
432 VMX_SEGMENT_FIELD(GS),
433 VMX_SEGMENT_FIELD(SS),
434 VMX_SEGMENT_FIELD(TR),
435 VMX_SEGMENT_FIELD(LDTR),
439 static unsigned long host_idt_base;
442 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
443 * will emulate SYSCALL in legacy mode if the vendor string in guest
444 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
445 * support this emulation, IA32_STAR must always be included in
446 * vmx_msr_index[], even in i386 builds.
448 const u32 vmx_msr_index[] = {
450 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
452 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
455 #if IS_ENABLED(CONFIG_HYPERV)
456 static bool __read_mostly enlightened_vmcs = true;
457 module_param(enlightened_vmcs, bool, 0444);
459 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
460 static void check_ept_pointer_match(struct kvm *kvm)
462 struct kvm_vcpu *vcpu;
463 u64 tmp_eptp = INVALID_PAGE;
466 kvm_for_each_vcpu(i, vcpu, kvm) {
467 if (!VALID_PAGE(tmp_eptp)) {
468 tmp_eptp = to_vmx(vcpu)->ept_pointer;
469 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
470 to_kvm_vmx(kvm)->ept_pointers_match
471 = EPT_POINTERS_MISMATCH;
476 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
479 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
482 struct kvm_tlb_range *range = data;
484 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
488 static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
489 struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
491 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
494 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
495 * of the base of EPT PML4 table, strip off EPT configuration
499 return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
500 kvm_fill_hv_flush_list_func, (void *)range);
502 return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
505 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
506 struct kvm_tlb_range *range)
508 struct kvm_vcpu *vcpu;
511 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
513 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
514 check_ept_pointer_match(kvm);
516 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
517 kvm_for_each_vcpu(i, vcpu, kvm) {
518 /* If ept_pointer is invalid pointer, bypass flush request. */
519 if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
520 ret |= __hv_remote_flush_tlb_with_range(
524 ret = __hv_remote_flush_tlb_with_range(kvm,
525 kvm_get_vcpu(kvm, 0), range);
528 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
531 static int hv_remote_flush_tlb(struct kvm *kvm)
533 return hv_remote_flush_tlb_with_range(kvm, NULL);
536 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
538 struct hv_enlightened_vmcs *evmcs;
539 struct hv_partition_assist_pg **p_hv_pa_pg =
540 &vcpu->kvm->arch.hyperv.hv_pa_pg;
542 * Synthetic VM-Exit is not enabled in current code and so All
543 * evmcs in singe VM shares same assist page.
546 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL);
551 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
553 evmcs->partition_assist_page =
555 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
556 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
561 #endif /* IS_ENABLED(CONFIG_HYPERV) */
564 * Comment's format: document - errata name - stepping - processor name.
566 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
568 static u32 vmx_preemption_cpu_tfms[] = {
569 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
571 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
572 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
573 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
575 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
577 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
578 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
580 * 320767.pdf - AAP86 - B1 -
581 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
584 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
586 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
588 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
590 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
591 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
592 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
594 /* Xeon E3-1220 V2 */
598 static inline bool cpu_has_broken_vmx_preemption_timer(void)
600 u32 eax = cpuid_eax(0x00000001), i;
602 /* Clear the reserved bits */
603 eax &= ~(0x3U << 14 | 0xfU << 28);
604 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
605 if (eax == vmx_preemption_cpu_tfms[i])
611 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
613 return flexpriority_enabled && lapic_in_kernel(vcpu);
616 static inline bool report_flexpriority(void)
618 return flexpriority_enabled;
621 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
625 for (i = 0; i < vmx->nmsrs; ++i)
626 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
631 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
635 i = __find_msr_index(vmx, msr);
637 return &vmx->guest_msrs[i];
641 void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
643 vmcs_clear(loaded_vmcs->vmcs);
644 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
645 vmcs_clear(loaded_vmcs->shadow_vmcs);
646 loaded_vmcs->cpu = -1;
647 loaded_vmcs->launched = 0;
650 #ifdef CONFIG_KEXEC_CORE
651 static void crash_vmclear_local_loaded_vmcss(void)
653 int cpu = raw_smp_processor_id();
654 struct loaded_vmcs *v;
656 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
657 loaded_vmcss_on_cpu_link)
660 #endif /* CONFIG_KEXEC_CORE */
662 static void __loaded_vmcs_clear(void *arg)
664 struct loaded_vmcs *loaded_vmcs = arg;
665 int cpu = raw_smp_processor_id();
667 if (loaded_vmcs->cpu != cpu)
668 return; /* vcpu migration can race with cpu offline */
669 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
670 per_cpu(current_vmcs, cpu) = NULL;
672 vmcs_clear(loaded_vmcs->vmcs);
673 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
674 vmcs_clear(loaded_vmcs->shadow_vmcs);
676 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
679 * Ensure all writes to loaded_vmcs, including deleting it from its
680 * current percpu list, complete before setting loaded_vmcs->vcpu to
681 * -1, otherwise a different cpu can see vcpu == -1 first and add
682 * loaded_vmcs to its percpu list before it's deleted from this cpu's
683 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
687 loaded_vmcs->cpu = -1;
688 loaded_vmcs->launched = 0;
691 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
693 int cpu = loaded_vmcs->cpu;
696 smp_call_function_single(cpu,
697 __loaded_vmcs_clear, loaded_vmcs, 1);
700 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
704 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
706 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
707 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
708 vmx->segment_cache.bitmask = 0;
710 ret = vmx->segment_cache.bitmask & mask;
711 vmx->segment_cache.bitmask |= mask;
715 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
717 u16 *p = &vmx->segment_cache.seg[seg].selector;
719 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
720 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
724 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
726 ulong *p = &vmx->segment_cache.seg[seg].base;
728 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
729 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
733 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
735 u32 *p = &vmx->segment_cache.seg[seg].limit;
737 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
738 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
742 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
744 u32 *p = &vmx->segment_cache.seg[seg].ar;
746 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
747 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
751 void update_exception_bitmap(struct kvm_vcpu *vcpu)
755 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
756 (1u << DB_VECTOR) | (1u << AC_VECTOR);
758 * Guest access to VMware backdoor ports could legitimately
759 * trigger #GP because of TSS I/O permission bitmap.
760 * We intercept those #GP and allow access to them anyway
763 if (enable_vmware_backdoor)
764 eb |= (1u << GP_VECTOR);
765 if ((vcpu->guest_debug &
766 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
767 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
768 eb |= 1u << BP_VECTOR;
769 if (to_vmx(vcpu)->rmode.vm86_active)
772 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
774 /* When we are running a nested L2 guest and L1 specified for it a
775 * certain exception bitmap, we must trap the same exceptions and pass
776 * them to L1. When running L2, we will only handle the exceptions
777 * specified above if L1 did not want them.
779 if (is_guest_mode(vcpu))
780 eb |= get_vmcs12(vcpu)->exception_bitmap;
782 vmcs_write32(EXCEPTION_BITMAP, eb);
786 * Check if MSR is intercepted for currently loaded MSR bitmap.
788 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
790 unsigned long *msr_bitmap;
791 int f = sizeof(unsigned long);
793 if (!cpu_has_vmx_msr_bitmap())
796 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
799 return !!test_bit(msr, msr_bitmap + 0x800 / f);
800 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
802 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
808 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
809 unsigned long entry, unsigned long exit)
811 vm_entry_controls_clearbit(vmx, entry);
812 vm_exit_controls_clearbit(vmx, exit);
815 static int find_msr(struct vmx_msrs *m, unsigned int msr)
819 for (i = 0; i < m->nr; ++i) {
820 if (m->val[i].index == msr)
826 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
829 struct msr_autoload *m = &vmx->msr_autoload;
833 if (cpu_has_load_ia32_efer()) {
834 clear_atomic_switch_msr_special(vmx,
835 VM_ENTRY_LOAD_IA32_EFER,
836 VM_EXIT_LOAD_IA32_EFER);
840 case MSR_CORE_PERF_GLOBAL_CTRL:
841 if (cpu_has_load_perf_global_ctrl()) {
842 clear_atomic_switch_msr_special(vmx,
843 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
844 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
849 i = find_msr(&m->guest, msr);
853 m->guest.val[i] = m->guest.val[m->guest.nr];
854 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
857 i = find_msr(&m->host, msr);
862 m->host.val[i] = m->host.val[m->host.nr];
863 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
866 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
867 unsigned long entry, unsigned long exit,
868 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
869 u64 guest_val, u64 host_val)
871 vmcs_write64(guest_val_vmcs, guest_val);
872 if (host_val_vmcs != HOST_IA32_EFER)
873 vmcs_write64(host_val_vmcs, host_val);
874 vm_entry_controls_setbit(vmx, entry);
875 vm_exit_controls_setbit(vmx, exit);
878 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
879 u64 guest_val, u64 host_val, bool entry_only)
882 struct msr_autoload *m = &vmx->msr_autoload;
886 if (cpu_has_load_ia32_efer()) {
887 add_atomic_switch_msr_special(vmx,
888 VM_ENTRY_LOAD_IA32_EFER,
889 VM_EXIT_LOAD_IA32_EFER,
892 guest_val, host_val);
896 case MSR_CORE_PERF_GLOBAL_CTRL:
897 if (cpu_has_load_perf_global_ctrl()) {
898 add_atomic_switch_msr_special(vmx,
899 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
900 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
901 GUEST_IA32_PERF_GLOBAL_CTRL,
902 HOST_IA32_PERF_GLOBAL_CTRL,
903 guest_val, host_val);
907 case MSR_IA32_PEBS_ENABLE:
908 /* PEBS needs a quiescent period after being disabled (to write
909 * a record). Disabling PEBS through VMX MSR swapping doesn't
910 * provide that period, so a CPU could write host's record into
913 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
916 i = find_msr(&m->guest, msr);
918 j = find_msr(&m->host, msr);
920 if ((i < 0 && m->guest.nr == NR_AUTOLOAD_MSRS) ||
921 (j < 0 && m->host.nr == NR_AUTOLOAD_MSRS)) {
922 printk_once(KERN_WARNING "Not enough msr switch entries. "
923 "Can't add msr %x\n", msr);
928 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
930 m->guest.val[i].index = msr;
931 m->guest.val[i].value = guest_val;
938 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
940 m->host.val[j].index = msr;
941 m->host.val[j].value = host_val;
944 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
946 u64 guest_efer = vmx->vcpu.arch.efer;
949 /* Shadow paging assumes NX to be available. */
951 guest_efer |= EFER_NX;
954 * LMA and LME handled by hardware; SCE meaningless outside long mode.
956 ignore_bits |= EFER_SCE;
958 ignore_bits |= EFER_LMA | EFER_LME;
959 /* SCE is meaningful only in long mode on Intel */
960 if (guest_efer & EFER_LMA)
961 ignore_bits &= ~(u64)EFER_SCE;
965 * On EPT, we can't emulate NX, so we must switch EFER atomically.
966 * On CPUs that support "load IA32_EFER", always switch EFER
967 * atomically, since it's faster than switching it manually.
969 if (cpu_has_load_ia32_efer() ||
970 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
971 if (!(guest_efer & EFER_LMA))
972 guest_efer &= ~EFER_LME;
973 if (guest_efer != host_efer)
974 add_atomic_switch_msr(vmx, MSR_EFER,
975 guest_efer, host_efer, false);
977 clear_atomic_switch_msr(vmx, MSR_EFER);
980 clear_atomic_switch_msr(vmx, MSR_EFER);
982 guest_efer &= ~ignore_bits;
983 guest_efer |= host_efer & ignore_bits;
985 vmx->guest_msrs[efer_offset].data = guest_efer;
986 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
994 * On 32-bit kernels, VM exits still load the FS and GS bases from the
995 * VMCS rather than the segment table. KVM uses this helper to figure
996 * out the current bases to poke them into the VMCS before entry.
998 static unsigned long segment_base(u16 selector)
1000 struct desc_struct *table;
1003 if (!(selector & ~SEGMENT_RPL_MASK))
1006 table = get_current_gdt_ro();
1008 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1009 u16 ldt_selector = kvm_read_ldt();
1011 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1014 table = (struct desc_struct *)segment_base(ldt_selector);
1016 v = get_desc_base(&table[selector >> 3]);
1021 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1025 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1026 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1027 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1028 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1029 for (i = 0; i < addr_range; i++) {
1030 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1031 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1035 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1039 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1040 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1041 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1042 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1043 for (i = 0; i < addr_range; i++) {
1044 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1045 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1049 static void pt_guest_enter(struct vcpu_vmx *vmx)
1051 if (pt_mode == PT_MODE_SYSTEM)
1055 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1056 * Save host state before VM entry.
1058 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1059 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1060 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1061 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1062 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1066 static void pt_guest_exit(struct vcpu_vmx *vmx)
1068 if (pt_mode == PT_MODE_SYSTEM)
1071 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1072 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1073 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1076 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1077 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1080 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1081 unsigned long fs_base, unsigned long gs_base)
1083 if (unlikely(fs_sel != host->fs_sel)) {
1085 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1087 vmcs_write16(HOST_FS_SELECTOR, 0);
1088 host->fs_sel = fs_sel;
1090 if (unlikely(gs_sel != host->gs_sel)) {
1092 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1094 vmcs_write16(HOST_GS_SELECTOR, 0);
1095 host->gs_sel = gs_sel;
1097 if (unlikely(fs_base != host->fs_base)) {
1098 vmcs_writel(HOST_FS_BASE, fs_base);
1099 host->fs_base = fs_base;
1101 if (unlikely(gs_base != host->gs_base)) {
1102 vmcs_writel(HOST_GS_BASE, gs_base);
1103 host->gs_base = gs_base;
1107 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1109 struct vcpu_vmx *vmx = to_vmx(vcpu);
1110 struct vmcs_host_state *host_state;
1111 #ifdef CONFIG_X86_64
1112 int cpu = raw_smp_processor_id();
1114 unsigned long fs_base, gs_base;
1118 vmx->req_immediate_exit = false;
1121 * Note that guest MSRs to be saved/restored can also be changed
1122 * when guest state is loaded. This happens when guest transitions
1123 * to/from long-mode by setting MSR_EFER.LMA.
1125 if (!vmx->guest_msrs_ready) {
1126 vmx->guest_msrs_ready = true;
1127 for (i = 0; i < vmx->save_nmsrs; ++i)
1128 kvm_set_shared_msr(vmx->guest_msrs[i].index,
1129 vmx->guest_msrs[i].data,
1130 vmx->guest_msrs[i].mask);
1133 if (vmx->guest_state_loaded)
1136 host_state = &vmx->loaded_vmcs->host_state;
1139 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1140 * allow segment selectors with cpl > 0 or ti == 1.
1142 host_state->ldt_sel = kvm_read_ldt();
1144 #ifdef CONFIG_X86_64
1145 savesegment(ds, host_state->ds_sel);
1146 savesegment(es, host_state->es_sel);
1148 gs_base = cpu_kernelmode_gs_base(cpu);
1149 if (likely(is_64bit_mm(current->mm))) {
1150 save_fsgs_for_kvm();
1151 fs_sel = current->thread.fsindex;
1152 gs_sel = current->thread.gsindex;
1153 fs_base = current->thread.fsbase;
1154 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1156 savesegment(fs, fs_sel);
1157 savesegment(gs, gs_sel);
1158 fs_base = read_msr(MSR_FS_BASE);
1159 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1162 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1164 savesegment(fs, fs_sel);
1165 savesegment(gs, gs_sel);
1166 fs_base = segment_base(fs_sel);
1167 gs_base = segment_base(gs_sel);
1170 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1171 vmx->guest_state_loaded = true;
1174 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1176 struct vmcs_host_state *host_state;
1178 if (!vmx->guest_state_loaded)
1181 host_state = &vmx->loaded_vmcs->host_state;
1183 ++vmx->vcpu.stat.host_state_reload;
1185 #ifdef CONFIG_X86_64
1186 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1188 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1189 kvm_load_ldt(host_state->ldt_sel);
1190 #ifdef CONFIG_X86_64
1191 load_gs_index(host_state->gs_sel);
1193 loadsegment(gs, host_state->gs_sel);
1196 if (host_state->fs_sel & 7)
1197 loadsegment(fs, host_state->fs_sel);
1198 #ifdef CONFIG_X86_64
1199 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1200 loadsegment(ds, host_state->ds_sel);
1201 loadsegment(es, host_state->es_sel);
1204 invalidate_tss_limit();
1205 #ifdef CONFIG_X86_64
1206 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1208 load_fixmap_gdt(raw_smp_processor_id());
1209 vmx->guest_state_loaded = false;
1210 vmx->guest_msrs_ready = false;
1213 #ifdef CONFIG_X86_64
1214 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1217 if (vmx->guest_state_loaded)
1218 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1220 return vmx->msr_guest_kernel_gs_base;
1223 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1226 if (vmx->guest_state_loaded)
1227 wrmsrl(MSR_KERNEL_GS_BASE, data);
1229 vmx->msr_guest_kernel_gs_base = data;
1233 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1235 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1236 struct pi_desc old, new;
1240 * In case of hot-plug or hot-unplug, we may have to undo
1241 * vmx_vcpu_pi_put even if there is no assigned device. And we
1242 * always keep PI.NDST up to date for simplicity: it makes the
1243 * code easier, and CPU migration is not a fast path.
1245 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1249 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
1250 * PI.NDST: pi_post_block is the one expected to change PID.NDST and the
1251 * wakeup handler expects the vCPU to be on the blocked_vcpu_list that
1252 * matches PI.NDST. Otherwise, a vcpu may not be able to be woken up
1255 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR || vcpu->cpu == cpu) {
1256 pi_clear_sn(pi_desc);
1257 goto after_clear_sn;
1260 /* The full case. */
1262 old.control = new.control = pi_desc->control;
1264 dest = cpu_physical_id(cpu);
1266 if (x2apic_enabled())
1269 new.ndst = (dest << 8) & 0xFF00;
1272 } while (cmpxchg64(&pi_desc->control, old.control,
1273 new.control) != old.control);
1278 * Clear SN before reading the bitmap. The VT-d firmware
1279 * writes the bitmap and reads SN atomically (5.2.3 in the
1280 * spec), so it doesn't really have a memory barrier that
1281 * pairs with this, but we cannot do that and we need one.
1283 smp_mb__after_atomic();
1285 if (!pi_is_pir_empty(pi_desc))
1289 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu)
1291 struct vcpu_vmx *vmx = to_vmx(vcpu);
1292 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1294 if (!already_loaded) {
1295 loaded_vmcs_clear(vmx->loaded_vmcs);
1296 local_irq_disable();
1299 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1300 * this cpu's percpu list, otherwise it may not yet be deleted
1301 * from its previous cpu's percpu list. Pairs with the
1302 * smb_wmb() in __loaded_vmcs_clear().
1306 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1307 &per_cpu(loaded_vmcss_on_cpu, cpu));
1311 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1312 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1313 vmcs_load(vmx->loaded_vmcs->vmcs);
1314 indirect_branch_prediction_barrier();
1317 if (!already_loaded) {
1318 void *gdt = get_current_gdt_ro();
1319 unsigned long sysenter_esp;
1321 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1324 * Linux uses per-cpu TSS and GDT, so set these when switching
1325 * processors. See 22.2.4.
1327 vmcs_writel(HOST_TR_BASE,
1328 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1329 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1332 * VM exits change the host TR limit to 0x67 after a VM
1333 * exit. This is okay, since 0x67 covers everything except
1334 * the IO bitmap and have have code to handle the IO bitmap
1335 * being lost after a VM exit.
1337 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
1339 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1340 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1342 vmx->loaded_vmcs->cpu = cpu;
1345 /* Setup TSC multiplier */
1346 if (kvm_has_tsc_control &&
1347 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1348 decache_tsc_multiplier(vmx);
1352 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1353 * vcpu mutex is already taken.
1355 void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1357 struct vcpu_vmx *vmx = to_vmx(vcpu);
1359 vmx_vcpu_load_vmcs(vcpu, cpu);
1361 vmx_vcpu_pi_load(vcpu, cpu);
1363 vmx->host_pkru = read_pkru();
1364 vmx->host_debugctlmsr = get_debugctlmsr();
1367 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1369 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1371 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1372 !irq_remapping_cap(IRQ_POSTING_CAP) ||
1373 !kvm_vcpu_apicv_active(vcpu))
1376 /* Set SN when the vCPU is preempted */
1377 if (vcpu->preempted)
1381 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1383 vmx_vcpu_pi_put(vcpu);
1385 vmx_prepare_switch_to_host(to_vmx(vcpu));
1388 static bool emulation_required(struct kvm_vcpu *vcpu)
1390 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1393 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1395 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1397 unsigned long rflags, save_rflags;
1399 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1400 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1401 rflags = vmcs_readl(GUEST_RFLAGS);
1402 if (to_vmx(vcpu)->rmode.vm86_active) {
1403 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1404 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1405 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1407 to_vmx(vcpu)->rflags = rflags;
1409 return to_vmx(vcpu)->rflags;
1412 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1414 unsigned long old_rflags = vmx_get_rflags(vcpu);
1416 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1417 to_vmx(vcpu)->rflags = rflags;
1418 if (to_vmx(vcpu)->rmode.vm86_active) {
1419 to_vmx(vcpu)->rmode.save_rflags = rflags;
1420 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1422 vmcs_writel(GUEST_RFLAGS, rflags);
1424 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
1425 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
1428 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1430 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1433 if (interruptibility & GUEST_INTR_STATE_STI)
1434 ret |= KVM_X86_SHADOW_INT_STI;
1435 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1436 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1441 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1443 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1444 u32 interruptibility = interruptibility_old;
1446 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1448 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1449 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1450 else if (mask & KVM_X86_SHADOW_INT_STI)
1451 interruptibility |= GUEST_INTR_STATE_STI;
1453 if ((interruptibility != interruptibility_old))
1454 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1457 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1459 struct vcpu_vmx *vmx = to_vmx(vcpu);
1460 unsigned long value;
1463 * Any MSR write that attempts to change bits marked reserved will
1466 if (data & vmx->pt_desc.ctl_bitmask)
1470 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1471 * result in a #GP unless the same write also clears TraceEn.
1473 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1474 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1478 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1479 * and FabricEn would cause #GP, if
1480 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1482 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1483 !(data & RTIT_CTL_FABRIC_EN) &&
1484 !intel_pt_validate_cap(vmx->pt_desc.caps,
1485 PT_CAP_single_range_output))
1489 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1490 * utilize encodings marked reserved will casue a #GP fault.
1492 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1493 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1494 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1495 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1497 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1498 PT_CAP_cycle_thresholds);
1499 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1500 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1501 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1503 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1504 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1505 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1506 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1510 * If ADDRx_CFG is reserved or the encodings is >2 will
1511 * cause a #GP fault.
1513 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1514 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1516 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1517 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1519 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1520 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1522 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1523 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1529 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1534 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1535 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1536 * set when EPT misconfig occurs. In practice, real hardware updates
1537 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1538 * (namely Hyper-V) don't set it due to it being undefined behavior,
1539 * i.e. we end up advancing IP with some random value.
1541 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1542 to_vmx(vcpu)->exit_reason != EXIT_REASON_EPT_MISCONFIG) {
1543 rip = kvm_rip_read(vcpu);
1544 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1545 kvm_rip_write(vcpu, rip);
1547 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1551 /* skipping an emulated instruction also counts */
1552 vmx_set_interrupt_shadow(vcpu, 0);
1557 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1560 * Ensure that we clear the HLT state in the VMCS. We don't need to
1561 * explicitly skip the instruction because if the HLT state is set,
1562 * then the instruction is already executing and RIP has already been
1565 if (kvm_hlt_in_guest(vcpu->kvm) &&
1566 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1567 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1570 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1572 struct vcpu_vmx *vmx = to_vmx(vcpu);
1573 unsigned nr = vcpu->arch.exception.nr;
1574 bool has_error_code = vcpu->arch.exception.has_error_code;
1575 u32 error_code = vcpu->arch.exception.error_code;
1576 u32 intr_info = nr | INTR_INFO_VALID_MASK;
1578 kvm_deliver_exception_payload(vcpu);
1580 if (has_error_code) {
1581 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1582 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1585 if (vmx->rmode.vm86_active) {
1587 if (kvm_exception_is_soft(nr))
1588 inc_eip = vcpu->arch.event_exit_inst_len;
1589 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1593 WARN_ON_ONCE(vmx->emulation_required);
1595 if (kvm_exception_is_soft(nr)) {
1596 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1597 vmx->vcpu.arch.event_exit_inst_len);
1598 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1600 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1602 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1604 vmx_clear_hlt(vcpu);
1607 static bool vmx_rdtscp_supported(void)
1609 return cpu_has_vmx_rdtscp();
1612 static bool vmx_invpcid_supported(void)
1614 return cpu_has_vmx_invpcid();
1618 * Swap MSR entry in host/guest MSR entry array.
1620 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1622 struct shared_msr_entry tmp;
1624 tmp = vmx->guest_msrs[to];
1625 vmx->guest_msrs[to] = vmx->guest_msrs[from];
1626 vmx->guest_msrs[from] = tmp;
1630 * Set up the vmcs to automatically save and restore system
1631 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1632 * mode, as fiddling with msrs is very expensive.
1634 static void setup_msrs(struct vcpu_vmx *vmx)
1636 int save_nmsrs, index;
1639 #ifdef CONFIG_X86_64
1641 * The SYSCALL MSRs are only needed on long mode guests, and only
1642 * when EFER.SCE is set.
1644 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1645 index = __find_msr_index(vmx, MSR_STAR);
1647 move_msr_up(vmx, index, save_nmsrs++);
1648 index = __find_msr_index(vmx, MSR_LSTAR);
1650 move_msr_up(vmx, index, save_nmsrs++);
1651 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1653 move_msr_up(vmx, index, save_nmsrs++);
1656 index = __find_msr_index(vmx, MSR_EFER);
1657 if (index >= 0 && update_transition_efer(vmx, index))
1658 move_msr_up(vmx, index, save_nmsrs++);
1659 index = __find_msr_index(vmx, MSR_TSC_AUX);
1660 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1661 move_msr_up(vmx, index, save_nmsrs++);
1663 vmx->save_nmsrs = save_nmsrs;
1664 vmx->guest_msrs_ready = false;
1666 if (cpu_has_vmx_msr_bitmap())
1667 vmx_update_msr_bitmap(&vmx->vcpu);
1670 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1672 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1674 if (is_guest_mode(vcpu) &&
1675 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1676 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
1678 return vcpu->arch.tsc_offset;
1681 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1683 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1684 u64 g_tsc_offset = 0;
1687 * We're here if L1 chose not to trap WRMSR to TSC. According
1688 * to the spec, this should set L1's TSC; The offset that L1
1689 * set for L2 remains unchanged, and still needs to be added
1690 * to the newly set TSC to get L2's TSC.
1692 if (is_guest_mode(vcpu) &&
1693 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1694 g_tsc_offset = vmcs12->tsc_offset;
1696 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1697 vcpu->arch.tsc_offset - g_tsc_offset,
1699 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1700 return offset + g_tsc_offset;
1704 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1705 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1706 * all guests if the "nested" module option is off, and can also be disabled
1707 * for a single guest by disabling its VMX cpuid bit.
1709 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1711 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1714 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1717 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1719 return !(val & ~valid_bits);
1722 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1724 switch (msr->index) {
1725 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1728 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1737 * Reads an msr value (of 'msr_index') into 'pdata'.
1738 * Returns 0 on success, non-0 otherwise.
1739 * Assumes vcpu_load() was already called.
1741 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1743 struct vcpu_vmx *vmx = to_vmx(vcpu);
1744 struct shared_msr_entry *msr;
1747 switch (msr_info->index) {
1748 #ifdef CONFIG_X86_64
1750 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1753 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1755 case MSR_KERNEL_GS_BASE:
1756 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1760 return kvm_get_msr_common(vcpu, msr_info);
1761 case MSR_IA32_UMWAIT_CONTROL:
1762 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1765 msr_info->data = vmx->msr_ia32_umwait_control;
1767 case MSR_IA32_SPEC_CTRL:
1768 if (!msr_info->host_initiated &&
1769 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1772 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1774 case MSR_IA32_SYSENTER_CS:
1775 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1777 case MSR_IA32_SYSENTER_EIP:
1778 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1780 case MSR_IA32_SYSENTER_ESP:
1781 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1783 case MSR_IA32_BNDCFGS:
1784 if (!kvm_mpx_supported() ||
1785 (!msr_info->host_initiated &&
1786 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1788 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1790 case MSR_IA32_MCG_EXT_CTL:
1791 if (!msr_info->host_initiated &&
1792 !(vmx->msr_ia32_feature_control &
1793 FEATURE_CONTROL_LMCE))
1795 msr_info->data = vcpu->arch.mcg_ext_ctl;
1797 case MSR_IA32_FEATURE_CONTROL:
1798 msr_info->data = vmx->msr_ia32_feature_control;
1800 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1801 if (!nested_vmx_allowed(vcpu))
1803 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1806 if (!vmx_xsaves_supported() ||
1807 (!msr_info->host_initiated &&
1808 !(guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
1809 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))))
1811 msr_info->data = vcpu->arch.ia32_xss;
1813 case MSR_IA32_RTIT_CTL:
1814 if (pt_mode != PT_MODE_HOST_GUEST)
1816 msr_info->data = vmx->pt_desc.guest.ctl;
1818 case MSR_IA32_RTIT_STATUS:
1819 if (pt_mode != PT_MODE_HOST_GUEST)
1821 msr_info->data = vmx->pt_desc.guest.status;
1823 case MSR_IA32_RTIT_CR3_MATCH:
1824 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1825 !intel_pt_validate_cap(vmx->pt_desc.caps,
1826 PT_CAP_cr3_filtering))
1828 msr_info->data = vmx->pt_desc.guest.cr3_match;
1830 case MSR_IA32_RTIT_OUTPUT_BASE:
1831 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1832 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1833 PT_CAP_topa_output) &&
1834 !intel_pt_validate_cap(vmx->pt_desc.caps,
1835 PT_CAP_single_range_output)))
1837 msr_info->data = vmx->pt_desc.guest.output_base;
1839 case MSR_IA32_RTIT_OUTPUT_MASK:
1840 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1841 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1842 PT_CAP_topa_output) &&
1843 !intel_pt_validate_cap(vmx->pt_desc.caps,
1844 PT_CAP_single_range_output)))
1846 msr_info->data = vmx->pt_desc.guest.output_mask;
1848 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1849 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1850 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1851 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1852 PT_CAP_num_address_ranges)))
1855 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1857 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1860 if (!msr_info->host_initiated &&
1861 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1863 /* Else, falls through */
1865 msr = find_msr_entry(vmx, msr_info->index);
1867 msr_info->data = msr->data;
1870 return kvm_get_msr_common(vcpu, msr_info);
1877 * Writes msr value into into the appropriate "register".
1878 * Returns 0 on success, non-0 otherwise.
1879 * Assumes vcpu_load() was already called.
1881 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1883 struct vcpu_vmx *vmx = to_vmx(vcpu);
1884 struct shared_msr_entry *msr;
1886 u32 msr_index = msr_info->index;
1887 u64 data = msr_info->data;
1890 switch (msr_index) {
1892 ret = kvm_set_msr_common(vcpu, msr_info);
1894 #ifdef CONFIG_X86_64
1896 vmx_segment_cache_clear(vmx);
1897 vmcs_writel(GUEST_FS_BASE, data);
1900 vmx_segment_cache_clear(vmx);
1901 vmcs_writel(GUEST_GS_BASE, data);
1903 case MSR_KERNEL_GS_BASE:
1904 vmx_write_guest_kernel_gs_base(vmx, data);
1907 case MSR_IA32_SYSENTER_CS:
1908 if (is_guest_mode(vcpu))
1909 get_vmcs12(vcpu)->guest_sysenter_cs = data;
1910 vmcs_write32(GUEST_SYSENTER_CS, data);
1912 case MSR_IA32_SYSENTER_EIP:
1913 if (is_guest_mode(vcpu))
1914 get_vmcs12(vcpu)->guest_sysenter_eip = data;
1915 vmcs_writel(GUEST_SYSENTER_EIP, data);
1917 case MSR_IA32_SYSENTER_ESP:
1918 if (is_guest_mode(vcpu))
1919 get_vmcs12(vcpu)->guest_sysenter_esp = data;
1920 vmcs_writel(GUEST_SYSENTER_ESP, data);
1922 case MSR_IA32_DEBUGCTLMSR:
1923 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
1924 VM_EXIT_SAVE_DEBUG_CONTROLS)
1925 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
1927 ret = kvm_set_msr_common(vcpu, msr_info);
1930 case MSR_IA32_BNDCFGS:
1931 if (!kvm_mpx_supported() ||
1932 (!msr_info->host_initiated &&
1933 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1935 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
1936 (data & MSR_IA32_BNDCFGS_RSVD))
1938 vmcs_write64(GUEST_BNDCFGS, data);
1940 case MSR_IA32_UMWAIT_CONTROL:
1941 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1944 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
1945 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
1948 vmx->msr_ia32_umwait_control = data;
1950 case MSR_IA32_SPEC_CTRL:
1951 if (!msr_info->host_initiated &&
1952 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1955 /* The STIBP bit doesn't fault even if it's not advertised */
1956 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
1959 vmx->spec_ctrl = data;
1966 * When it's written (to non-zero) for the first time, pass
1970 * The handling of the MSR bitmap for L2 guests is done in
1971 * nested_vmx_merge_msr_bitmap. We should not touch the
1972 * vmcs02.msr_bitmap here since it gets completely overwritten
1973 * in the merging. We update the vmcs01 here for L1 as well
1974 * since it will end up touching the MSR anyway now.
1976 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
1980 case MSR_IA32_PRED_CMD:
1981 if (!msr_info->host_initiated &&
1982 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1985 if (data & ~PRED_CMD_IBPB)
1991 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
1995 * When it's written (to non-zero) for the first time, pass
1999 * The handling of the MSR bitmap for L2 guests is done in
2000 * nested_vmx_merge_msr_bitmap. We should not touch the
2001 * vmcs02.msr_bitmap here since it gets completely overwritten
2004 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
2007 case MSR_IA32_CR_PAT:
2008 if (!kvm_pat_valid(data))
2011 if (is_guest_mode(vcpu) &&
2012 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2013 get_vmcs12(vcpu)->guest_ia32_pat = data;
2015 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2016 vmcs_write64(GUEST_IA32_PAT, data);
2017 vcpu->arch.pat = data;
2020 ret = kvm_set_msr_common(vcpu, msr_info);
2022 case MSR_IA32_TSC_ADJUST:
2023 ret = kvm_set_msr_common(vcpu, msr_info);
2025 case MSR_IA32_MCG_EXT_CTL:
2026 if ((!msr_info->host_initiated &&
2027 !(to_vmx(vcpu)->msr_ia32_feature_control &
2028 FEATURE_CONTROL_LMCE)) ||
2029 (data & ~MCG_EXT_CTL_LMCE_EN))
2031 vcpu->arch.mcg_ext_ctl = data;
2033 case MSR_IA32_FEATURE_CONTROL:
2034 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2035 (to_vmx(vcpu)->msr_ia32_feature_control &
2036 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
2038 vmx->msr_ia32_feature_control = data;
2039 if (msr_info->host_initiated && data == 0)
2040 vmx_leave_nested(vcpu);
2042 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2043 if (!msr_info->host_initiated)
2044 return 1; /* they are read-only */
2045 if (!nested_vmx_allowed(vcpu))
2047 return vmx_set_vmx_msr(vcpu, msr_index, data);
2049 if (!vmx_xsaves_supported() ||
2050 (!msr_info->host_initiated &&
2051 !(guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
2052 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))))
2055 * The only supported bit as of Skylake is bit 8, but
2056 * it is not supported on KVM.
2060 vcpu->arch.ia32_xss = data;
2061 if (vcpu->arch.ia32_xss != host_xss)
2062 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
2063 vcpu->arch.ia32_xss, host_xss, false);
2065 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
2067 case MSR_IA32_RTIT_CTL:
2068 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2069 vmx_rtit_ctl_check(vcpu, data) ||
2072 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2073 vmx->pt_desc.guest.ctl = data;
2074 pt_update_intercept_for_msr(vmx);
2076 case MSR_IA32_RTIT_STATUS:
2077 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2078 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2079 (data & MSR_IA32_RTIT_STATUS_MASK))
2081 vmx->pt_desc.guest.status = data;
2083 case MSR_IA32_RTIT_CR3_MATCH:
2084 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2085 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2086 !intel_pt_validate_cap(vmx->pt_desc.caps,
2087 PT_CAP_cr3_filtering))
2089 vmx->pt_desc.guest.cr3_match = data;
2091 case MSR_IA32_RTIT_OUTPUT_BASE:
2092 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2093 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2094 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2095 PT_CAP_topa_output) &&
2096 !intel_pt_validate_cap(vmx->pt_desc.caps,
2097 PT_CAP_single_range_output)) ||
2098 (data & MSR_IA32_RTIT_OUTPUT_BASE_MASK))
2100 vmx->pt_desc.guest.output_base = data;
2102 case MSR_IA32_RTIT_OUTPUT_MASK:
2103 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2104 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2105 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2106 PT_CAP_topa_output) &&
2107 !intel_pt_validate_cap(vmx->pt_desc.caps,
2108 PT_CAP_single_range_output)))
2110 vmx->pt_desc.guest.output_mask = data;
2112 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2113 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2114 if ((pt_mode != PT_MODE_HOST_GUEST) ||
2115 (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
2116 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2117 PT_CAP_num_address_ranges)))
2119 if (is_noncanonical_address(data, vcpu))
2122 vmx->pt_desc.guest.addr_b[index / 2] = data;
2124 vmx->pt_desc.guest.addr_a[index / 2] = data;
2127 if (!msr_info->host_initiated &&
2128 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2130 /* Check reserved bit, higher 32 bits should be zero */
2131 if ((data >> 32) != 0)
2133 /* Else, falls through */
2135 msr = find_msr_entry(vmx, msr_index);
2137 u64 old_msr_data = msr->data;
2139 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2141 ret = kvm_set_shared_msr(msr->index, msr->data,
2145 msr->data = old_msr_data;
2149 ret = kvm_set_msr_common(vcpu, msr_info);
2155 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2157 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2160 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2163 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2165 case VCPU_EXREG_PDPTR:
2167 ept_save_pdptrs(vcpu);
2174 static __init int cpu_has_kvm_support(void)
2176 return cpu_has_vmx();
2179 static __init int vmx_disabled_by_bios(void)
2183 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2184 if (msr & FEATURE_CONTROL_LOCKED) {
2185 /* launched w/ TXT and VMX disabled */
2186 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2189 /* launched w/o TXT and VMX only enabled w/ TXT */
2190 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2191 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2192 && !tboot_enabled()) {
2193 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2194 "activate TXT before enabling KVM\n");
2197 /* launched w/o TXT and VMX disabled */
2198 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2199 && !tboot_enabled())
2206 static void kvm_cpu_vmxon(u64 addr)
2208 cr4_set_bits(X86_CR4_VMXE);
2209 intel_pt_handle_vmx(1);
2211 asm volatile ("vmxon %0" : : "m"(addr));
2214 static int hardware_enable(void)
2216 int cpu = raw_smp_processor_id();
2217 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2220 if (cr4_read_shadow() & X86_CR4_VMXE)
2224 * This can happen if we hot-added a CPU but failed to allocate
2225 * VP assist page for it.
2227 if (static_branch_unlikely(&enable_evmcs) &&
2228 !hv_get_vp_assist_page(cpu))
2231 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2232 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
2233 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
2235 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2237 test_bits = FEATURE_CONTROL_LOCKED;
2238 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2239 if (tboot_enabled())
2240 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2242 if ((old & test_bits) != test_bits) {
2243 /* enable and lock */
2244 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2246 kvm_cpu_vmxon(phys_addr);
2253 static void vmclear_local_loaded_vmcss(void)
2255 int cpu = raw_smp_processor_id();
2256 struct loaded_vmcs *v, *n;
2258 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2259 loaded_vmcss_on_cpu_link)
2260 __loaded_vmcs_clear(v);
2264 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2267 static void kvm_cpu_vmxoff(void)
2269 asm volatile (__ex("vmxoff"));
2271 intel_pt_handle_vmx(0);
2272 cr4_clear_bits(X86_CR4_VMXE);
2275 static void hardware_disable(void)
2277 vmclear_local_loaded_vmcss();
2281 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2282 u32 msr, u32 *result)
2284 u32 vmx_msr_low, vmx_msr_high;
2285 u32 ctl = ctl_min | ctl_opt;
2287 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2289 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2290 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2292 /* Ensure minimum (required) set of control bits are supported. */
2300 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2301 struct vmx_capability *vmx_cap)
2303 u32 vmx_msr_low, vmx_msr_high;
2304 u32 min, opt, min2, opt2;
2305 u32 _pin_based_exec_control = 0;
2306 u32 _cpu_based_exec_control = 0;
2307 u32 _cpu_based_2nd_exec_control = 0;
2308 u32 _vmexit_control = 0;
2309 u32 _vmentry_control = 0;
2311 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2312 min = CPU_BASED_HLT_EXITING |
2313 #ifdef CONFIG_X86_64
2314 CPU_BASED_CR8_LOAD_EXITING |
2315 CPU_BASED_CR8_STORE_EXITING |
2317 CPU_BASED_CR3_LOAD_EXITING |
2318 CPU_BASED_CR3_STORE_EXITING |
2319 CPU_BASED_UNCOND_IO_EXITING |
2320 CPU_BASED_MOV_DR_EXITING |
2321 CPU_BASED_USE_TSC_OFFSETING |
2322 CPU_BASED_MWAIT_EXITING |
2323 CPU_BASED_MONITOR_EXITING |
2324 CPU_BASED_INVLPG_EXITING |
2325 CPU_BASED_RDPMC_EXITING;
2327 opt = CPU_BASED_TPR_SHADOW |
2328 CPU_BASED_USE_MSR_BITMAPS |
2329 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2330 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2331 &_cpu_based_exec_control) < 0)
2333 #ifdef CONFIG_X86_64
2334 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2335 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2336 ~CPU_BASED_CR8_STORE_EXITING;
2338 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2340 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2341 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2342 SECONDARY_EXEC_WBINVD_EXITING |
2343 SECONDARY_EXEC_ENABLE_VPID |
2344 SECONDARY_EXEC_ENABLE_EPT |
2345 SECONDARY_EXEC_UNRESTRICTED_GUEST |
2346 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2347 SECONDARY_EXEC_DESC |
2348 SECONDARY_EXEC_RDTSCP |
2349 SECONDARY_EXEC_ENABLE_INVPCID |
2350 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2351 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2352 SECONDARY_EXEC_SHADOW_VMCS |
2353 SECONDARY_EXEC_XSAVES |
2354 SECONDARY_EXEC_RDSEED_EXITING |
2355 SECONDARY_EXEC_RDRAND_EXITING |
2356 SECONDARY_EXEC_ENABLE_PML |
2357 SECONDARY_EXEC_TSC_SCALING |
2358 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2359 SECONDARY_EXEC_PT_USE_GPA |
2360 SECONDARY_EXEC_PT_CONCEAL_VMX |
2361 SECONDARY_EXEC_ENABLE_VMFUNC |
2362 SECONDARY_EXEC_ENCLS_EXITING;
2363 if (adjust_vmx_controls(min2, opt2,
2364 MSR_IA32_VMX_PROCBASED_CTLS2,
2365 &_cpu_based_2nd_exec_control) < 0)
2368 #ifndef CONFIG_X86_64
2369 if (!(_cpu_based_2nd_exec_control &
2370 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2371 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2374 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2375 _cpu_based_2nd_exec_control &= ~(
2376 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2377 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2378 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2380 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2381 &vmx_cap->ept, &vmx_cap->vpid);
2383 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2384 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2386 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2387 CPU_BASED_CR3_STORE_EXITING |
2388 CPU_BASED_INVLPG_EXITING);
2389 } else if (vmx_cap->ept) {
2391 pr_warn_once("EPT CAP should not exist if not support "
2392 "1-setting enable EPT VM-execution control\n");
2394 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2397 pr_warn_once("VPID CAP should not exist if not support "
2398 "1-setting enable VPID VM-execution control\n");
2401 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2402 #ifdef CONFIG_X86_64
2403 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2405 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2406 VM_EXIT_LOAD_IA32_PAT |
2407 VM_EXIT_LOAD_IA32_EFER |
2408 VM_EXIT_CLEAR_BNDCFGS |
2409 VM_EXIT_PT_CONCEAL_PIP |
2410 VM_EXIT_CLEAR_IA32_RTIT_CTL;
2411 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2412 &_vmexit_control) < 0)
2415 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2416 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2417 PIN_BASED_VMX_PREEMPTION_TIMER;
2418 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2419 &_pin_based_exec_control) < 0)
2422 if (cpu_has_broken_vmx_preemption_timer())
2423 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2424 if (!(_cpu_based_2nd_exec_control &
2425 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2426 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2428 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2429 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2430 VM_ENTRY_LOAD_IA32_PAT |
2431 VM_ENTRY_LOAD_IA32_EFER |
2432 VM_ENTRY_LOAD_BNDCFGS |
2433 VM_ENTRY_PT_CONCEAL_PIP |
2434 VM_ENTRY_LOAD_IA32_RTIT_CTL;
2435 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2436 &_vmentry_control) < 0)
2440 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2441 * can't be used due to an errata where VM Exit may incorrectly clear
2442 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2443 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2445 if (boot_cpu_data.x86 == 0x6) {
2446 switch (boot_cpu_data.x86_model) {
2447 case 26: /* AAK155 */
2448 case 30: /* AAP115 */
2449 case 37: /* AAT100 */
2450 case 44: /* BC86,AAY89,BD102 */
2452 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2453 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2454 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2455 "does not work properly. Using workaround\n");
2463 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2465 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2466 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2469 #ifdef CONFIG_X86_64
2470 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2471 if (vmx_msr_high & (1u<<16))
2475 /* Require Write-Back (WB) memory type for VMCS accesses. */
2476 if (((vmx_msr_high >> 18) & 15) != 6)
2479 vmcs_conf->size = vmx_msr_high & 0x1fff;
2480 vmcs_conf->order = get_order(vmcs_conf->size);
2481 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2483 vmcs_conf->revision_id = vmx_msr_low;
2485 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2486 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2487 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2488 vmcs_conf->vmexit_ctrl = _vmexit_control;
2489 vmcs_conf->vmentry_ctrl = _vmentry_control;
2491 if (static_branch_unlikely(&enable_evmcs))
2492 evmcs_sanitize_exec_ctrls(vmcs_conf);
2497 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2499 int node = cpu_to_node(cpu);
2503 pages = __alloc_pages_node(node, flags, vmcs_config.order);
2506 vmcs = page_address(pages);
2507 memset(vmcs, 0, vmcs_config.size);
2509 /* KVM supports Enlightened VMCS v1 only */
2510 if (static_branch_unlikely(&enable_evmcs))
2511 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2513 vmcs->hdr.revision_id = vmcs_config.revision_id;
2516 vmcs->hdr.shadow_vmcs = 1;
2520 void free_vmcs(struct vmcs *vmcs)
2522 free_pages((unsigned long)vmcs, vmcs_config.order);
2526 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2528 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2530 if (!loaded_vmcs->vmcs)
2532 loaded_vmcs_clear(loaded_vmcs);
2533 free_vmcs(loaded_vmcs->vmcs);
2534 loaded_vmcs->vmcs = NULL;
2535 if (loaded_vmcs->msr_bitmap)
2536 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2537 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2540 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2542 loaded_vmcs->vmcs = alloc_vmcs(false);
2543 if (!loaded_vmcs->vmcs)
2546 loaded_vmcs->shadow_vmcs = NULL;
2547 loaded_vmcs->hv_timer_soft_disabled = false;
2548 loaded_vmcs_init(loaded_vmcs);
2550 if (cpu_has_vmx_msr_bitmap()) {
2551 loaded_vmcs->msr_bitmap = (unsigned long *)
2552 __get_free_page(GFP_KERNEL_ACCOUNT);
2553 if (!loaded_vmcs->msr_bitmap)
2555 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2557 if (IS_ENABLED(CONFIG_HYPERV) &&
2558 static_branch_unlikely(&enable_evmcs) &&
2559 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2560 struct hv_enlightened_vmcs *evmcs =
2561 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2563 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2567 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2568 memset(&loaded_vmcs->controls_shadow, 0,
2569 sizeof(struct vmcs_controls_shadow));
2574 free_loaded_vmcs(loaded_vmcs);
2578 static void free_kvm_area(void)
2582 for_each_possible_cpu(cpu) {
2583 free_vmcs(per_cpu(vmxarea, cpu));
2584 per_cpu(vmxarea, cpu) = NULL;
2588 static __init int alloc_kvm_area(void)
2592 for_each_possible_cpu(cpu) {
2595 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2602 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2603 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2604 * revision_id reported by MSR_IA32_VMX_BASIC.
2606 * However, even though not explicitly documented by
2607 * TLFS, VMXArea passed as VMXON argument should
2608 * still be marked with revision_id reported by
2611 if (static_branch_unlikely(&enable_evmcs))
2612 vmcs->hdr.revision_id = vmcs_config.revision_id;
2614 per_cpu(vmxarea, cpu) = vmcs;
2619 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2620 struct kvm_segment *save)
2622 if (!emulate_invalid_guest_state) {
2624 * CS and SS RPL should be equal during guest entry according
2625 * to VMX spec, but in reality it is not always so. Since vcpu
2626 * is in the middle of the transition from real mode to
2627 * protected mode it is safe to assume that RPL 0 is a good
2630 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2631 save->selector &= ~SEGMENT_RPL_MASK;
2632 save->dpl = save->selector & SEGMENT_RPL_MASK;
2635 vmx_set_segment(vcpu, save, seg);
2638 static void enter_pmode(struct kvm_vcpu *vcpu)
2640 unsigned long flags;
2641 struct vcpu_vmx *vmx = to_vmx(vcpu);
2644 * Update real mode segment cache. It may be not up-to-date if sement
2645 * register was written while vcpu was in a guest mode.
2647 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2648 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2649 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2650 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2651 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2652 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2654 vmx->rmode.vm86_active = 0;
2656 vmx_segment_cache_clear(vmx);
2658 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2660 flags = vmcs_readl(GUEST_RFLAGS);
2661 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2662 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2663 vmcs_writel(GUEST_RFLAGS, flags);
2665 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2666 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2668 update_exception_bitmap(vcpu);
2670 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2671 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2672 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2673 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2674 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2675 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2678 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2680 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2681 struct kvm_segment var = *save;
2684 if (seg == VCPU_SREG_CS)
2687 if (!emulate_invalid_guest_state) {
2688 var.selector = var.base >> 4;
2689 var.base = var.base & 0xffff0;
2699 if (save->base & 0xf)
2700 printk_once(KERN_WARNING "kvm: segment base is not "
2701 "paragraph aligned when entering "
2702 "protected mode (seg=%d)", seg);
2705 vmcs_write16(sf->selector, var.selector);
2706 vmcs_writel(sf->base, var.base);
2707 vmcs_write32(sf->limit, var.limit);
2708 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2711 static void enter_rmode(struct kvm_vcpu *vcpu)
2713 unsigned long flags;
2714 struct vcpu_vmx *vmx = to_vmx(vcpu);
2715 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2717 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2718 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2719 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2720 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2721 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2722 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2723 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2725 vmx->rmode.vm86_active = 1;
2728 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2729 * vcpu. Warn the user that an update is overdue.
2731 if (!kvm_vmx->tss_addr)
2732 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2733 "called before entering vcpu\n");
2735 vmx_segment_cache_clear(vmx);
2737 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2738 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2739 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2741 flags = vmcs_readl(GUEST_RFLAGS);
2742 vmx->rmode.save_rflags = flags;
2744 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2746 vmcs_writel(GUEST_RFLAGS, flags);
2747 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2748 update_exception_bitmap(vcpu);
2750 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2751 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2752 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2753 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2754 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2755 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2757 kvm_mmu_reset_context(vcpu);
2760 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2762 struct vcpu_vmx *vmx = to_vmx(vcpu);
2763 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2768 vcpu->arch.efer = efer;
2769 if (efer & EFER_LMA) {
2770 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2773 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2775 msr->data = efer & ~EFER_LME;
2780 #ifdef CONFIG_X86_64
2782 static void enter_lmode(struct kvm_vcpu *vcpu)
2786 vmx_segment_cache_clear(to_vmx(vcpu));
2788 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2789 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2790 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2792 vmcs_write32(GUEST_TR_AR_BYTES,
2793 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2794 | VMX_AR_TYPE_BUSY_64_TSS);
2796 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2799 static void exit_lmode(struct kvm_vcpu *vcpu)
2801 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2802 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2807 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2809 int vpid = to_vmx(vcpu)->vpid;
2811 if (!vpid_sync_vcpu_addr(vpid, addr))
2812 vpid_sync_context(vpid);
2815 * If VPIDs are not supported or enabled, then the above is a no-op.
2816 * But we don't really need a TLB flush in that case anyway, because
2817 * each VM entry/exit includes an implicit flush when VPID is 0.
2821 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2823 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2825 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
2826 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
2829 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2831 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
2832 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2833 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2836 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2838 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2840 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2841 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2844 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2846 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2848 if (!test_bit(VCPU_EXREG_PDPTR,
2849 (unsigned long *)&vcpu->arch.regs_dirty))
2852 if (is_pae_paging(vcpu)) {
2853 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2854 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2855 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2856 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2860 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2862 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2864 if (is_pae_paging(vcpu)) {
2865 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2866 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2867 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2868 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2871 __set_bit(VCPU_EXREG_PDPTR,
2872 (unsigned long *)&vcpu->arch.regs_avail);
2873 __set_bit(VCPU_EXREG_PDPTR,
2874 (unsigned long *)&vcpu->arch.regs_dirty);
2877 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2879 struct kvm_vcpu *vcpu)
2881 struct vcpu_vmx *vmx = to_vmx(vcpu);
2883 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2884 vmx_decache_cr3(vcpu);
2885 if (!(cr0 & X86_CR0_PG)) {
2886 /* From paging/starting to nonpaging */
2887 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
2888 CPU_BASED_CR3_STORE_EXITING);
2889 vcpu->arch.cr0 = cr0;
2890 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2891 } else if (!is_paging(vcpu)) {
2892 /* From nonpaging to paging */
2893 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
2894 CPU_BASED_CR3_STORE_EXITING);
2895 vcpu->arch.cr0 = cr0;
2896 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2899 if (!(cr0 & X86_CR0_WP))
2900 *hw_cr0 &= ~X86_CR0_WP;
2903 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2905 struct vcpu_vmx *vmx = to_vmx(vcpu);
2906 unsigned long hw_cr0;
2908 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
2909 if (enable_unrestricted_guest)
2910 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
2912 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
2914 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
2917 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
2921 #ifdef CONFIG_X86_64
2922 if (vcpu->arch.efer & EFER_LME) {
2923 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
2925 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
2930 if (enable_ept && !enable_unrestricted_guest)
2931 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
2933 vmcs_writel(CR0_READ_SHADOW, cr0);
2934 vmcs_writel(GUEST_CR0, hw_cr0);
2935 vcpu->arch.cr0 = cr0;
2937 /* depends on vcpu->arch.cr0 to be set to a new value */
2938 vmx->emulation_required = emulation_required(vcpu);
2941 static int get_ept_level(struct kvm_vcpu *vcpu)
2943 /* Nested EPT currently only supports 4-level walks. */
2944 if (is_guest_mode(vcpu) && nested_cpu_has_ept(get_vmcs12(vcpu)))
2946 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
2951 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
2953 u64 eptp = VMX_EPTP_MT_WB;
2955 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
2957 if (enable_ept_ad_bits &&
2958 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
2959 eptp |= VMX_EPTP_AD_ENABLE_BIT;
2960 eptp |= (root_hpa & PAGE_MASK);
2965 void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
2967 struct kvm *kvm = vcpu->kvm;
2968 bool update_guest_cr3 = true;
2969 unsigned long guest_cr3;
2974 eptp = construct_eptp(vcpu, cr3);
2975 vmcs_write64(EPT_POINTER, eptp);
2977 if (kvm_x86_ops->tlb_remote_flush) {
2978 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2979 to_vmx(vcpu)->ept_pointer = eptp;
2980 to_kvm_vmx(kvm)->ept_pointers_match
2981 = EPT_POINTERS_CHECK;
2982 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2985 /* Loading vmcs02.GUEST_CR3 is handled by nested VM-Enter. */
2986 if (is_guest_mode(vcpu))
2987 update_guest_cr3 = false;
2988 else if (enable_unrestricted_guest || is_paging(vcpu))
2989 guest_cr3 = kvm_read_cr3(vcpu);
2991 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
2992 ept_load_pdptrs(vcpu);
2995 if (update_guest_cr3)
2996 vmcs_writel(GUEST_CR3, guest_cr3);
2999 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3001 struct vcpu_vmx *vmx = to_vmx(vcpu);
3003 * Pass through host's Machine Check Enable value to hw_cr4, which
3004 * is in force while we are in guest mode. Do not let guests control
3005 * this bit, even if host CR4.MCE == 0.
3007 unsigned long hw_cr4;
3009 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3010 if (enable_unrestricted_guest)
3011 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3012 else if (vmx->rmode.vm86_active)
3013 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3015 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3017 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3018 if (cr4 & X86_CR4_UMIP) {
3019 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3020 hw_cr4 &= ~X86_CR4_UMIP;
3021 } else if (!is_guest_mode(vcpu) ||
3022 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3023 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3027 if (cr4 & X86_CR4_VMXE) {
3029 * To use VMXON (and later other VMX instructions), a guest
3030 * must first be able to turn on cr4.VMXE (see handle_vmon()).
3031 * So basically the check on whether to allow nested VMX
3032 * is here. We operate under the default treatment of SMM,
3033 * so VMX cannot be enabled under SMM.
3035 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
3039 if (vmx->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3042 vcpu->arch.cr4 = cr4;
3044 if (!enable_unrestricted_guest) {
3046 if (!is_paging(vcpu)) {
3047 hw_cr4 &= ~X86_CR4_PAE;
3048 hw_cr4 |= X86_CR4_PSE;
3049 } else if (!(cr4 & X86_CR4_PAE)) {
3050 hw_cr4 &= ~X86_CR4_PAE;
3055 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3056 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3057 * to be manually disabled when guest switches to non-paging
3060 * If !enable_unrestricted_guest, the CPU is always running
3061 * with CR0.PG=1 and CR4 needs to be modified.
3062 * If enable_unrestricted_guest, the CPU automatically
3063 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3065 if (!is_paging(vcpu))
3066 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3069 vmcs_writel(CR4_READ_SHADOW, cr4);
3070 vmcs_writel(GUEST_CR4, hw_cr4);
3074 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3076 struct vcpu_vmx *vmx = to_vmx(vcpu);
3079 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3080 *var = vmx->rmode.segs[seg];
3081 if (seg == VCPU_SREG_TR
3082 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3084 var->base = vmx_read_guest_seg_base(vmx, seg);
3085 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3088 var->base = vmx_read_guest_seg_base(vmx, seg);
3089 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3090 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3091 ar = vmx_read_guest_seg_ar(vmx, seg);
3092 var->unusable = (ar >> 16) & 1;
3093 var->type = ar & 15;
3094 var->s = (ar >> 4) & 1;
3095 var->dpl = (ar >> 5) & 3;
3097 * Some userspaces do not preserve unusable property. Since usable
3098 * segment has to be present according to VMX spec we can use present
3099 * property to amend userspace bug by making unusable segment always
3100 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3101 * segment as unusable.
3103 var->present = !var->unusable;
3104 var->avl = (ar >> 12) & 1;
3105 var->l = (ar >> 13) & 1;
3106 var->db = (ar >> 14) & 1;
3107 var->g = (ar >> 15) & 1;
3110 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3112 struct kvm_segment s;
3114 if (to_vmx(vcpu)->rmode.vm86_active) {
3115 vmx_get_segment(vcpu, &s, seg);
3118 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3121 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3123 struct vcpu_vmx *vmx = to_vmx(vcpu);
3125 if (unlikely(vmx->rmode.vm86_active))
3128 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3129 return VMX_AR_DPL(ar);
3133 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3137 if (var->unusable || !var->present)
3140 ar = var->type & 15;
3141 ar |= (var->s & 1) << 4;
3142 ar |= (var->dpl & 3) << 5;
3143 ar |= (var->present & 1) << 7;
3144 ar |= (var->avl & 1) << 12;
3145 ar |= (var->l & 1) << 13;
3146 ar |= (var->db & 1) << 14;
3147 ar |= (var->g & 1) << 15;
3153 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3155 struct vcpu_vmx *vmx = to_vmx(vcpu);
3156 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3158 vmx_segment_cache_clear(vmx);
3160 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3161 vmx->rmode.segs[seg] = *var;
3162 if (seg == VCPU_SREG_TR)
3163 vmcs_write16(sf->selector, var->selector);
3165 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3169 vmcs_writel(sf->base, var->base);
3170 vmcs_write32(sf->limit, var->limit);
3171 vmcs_write16(sf->selector, var->selector);
3174 * Fix the "Accessed" bit in AR field of segment registers for older
3176 * IA32 arch specifies that at the time of processor reset the
3177 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3178 * is setting it to 0 in the userland code. This causes invalid guest
3179 * state vmexit when "unrestricted guest" mode is turned on.
3180 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3181 * tree. Newer qemu binaries with that qemu fix would not need this
3184 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3185 var->type |= 0x1; /* Accessed */
3187 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3190 vmx->emulation_required = emulation_required(vcpu);
3193 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3195 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3197 *db = (ar >> 14) & 1;
3198 *l = (ar >> 13) & 1;
3201 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3203 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3204 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3207 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3209 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3210 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3213 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3215 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3216 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3219 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3221 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3222 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3225 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3227 struct kvm_segment var;
3230 vmx_get_segment(vcpu, &var, seg);
3232 if (seg == VCPU_SREG_CS)
3234 ar = vmx_segment_access_rights(&var);
3236 if (var.base != (var.selector << 4))
3238 if (var.limit != 0xffff)
3246 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3248 struct kvm_segment cs;
3249 unsigned int cs_rpl;
3251 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3252 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3256 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3260 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3261 if (cs.dpl > cs_rpl)
3264 if (cs.dpl != cs_rpl)
3270 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3274 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3276 struct kvm_segment ss;
3277 unsigned int ss_rpl;
3279 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3280 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3284 if (ss.type != 3 && ss.type != 7)
3288 if (ss.dpl != ss_rpl) /* DPL != RPL */
3296 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3298 struct kvm_segment var;
3301 vmx_get_segment(vcpu, &var, seg);
3302 rpl = var.selector & SEGMENT_RPL_MASK;
3310 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3311 if (var.dpl < rpl) /* DPL < RPL */
3315 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3321 static bool tr_valid(struct kvm_vcpu *vcpu)
3323 struct kvm_segment tr;
3325 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3329 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3331 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3339 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3341 struct kvm_segment ldtr;
3343 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3347 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3357 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3359 struct kvm_segment cs, ss;
3361 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3362 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3364 return ((cs.selector & SEGMENT_RPL_MASK) ==
3365 (ss.selector & SEGMENT_RPL_MASK));
3369 * Check if guest state is valid. Returns true if valid, false if
3371 * We assume that registers are always usable
3373 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3375 if (enable_unrestricted_guest)
3378 /* real mode guest state checks */
3379 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3380 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3382 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3384 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3386 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3388 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3390 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3393 /* protected mode guest state checks */
3394 if (!cs_ss_rpl_check(vcpu))
3396 if (!code_segment_valid(vcpu))
3398 if (!stack_segment_valid(vcpu))
3400 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3402 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3404 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3406 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3408 if (!tr_valid(vcpu))
3410 if (!ldtr_valid(vcpu))
3414 * - Add checks on RIP
3415 * - Add checks on RFLAGS
3421 static int init_rmode_tss(struct kvm *kvm)
3427 idx = srcu_read_lock(&kvm->srcu);
3428 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3429 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3432 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3433 r = kvm_write_guest_page(kvm, fn++, &data,
3434 TSS_IOPB_BASE_OFFSET, sizeof(u16));
3437 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3440 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3444 r = kvm_write_guest_page(kvm, fn, &data,
3445 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3448 srcu_read_unlock(&kvm->srcu, idx);
3452 static int init_rmode_identity_map(struct kvm *kvm)
3454 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3456 kvm_pfn_t identity_map_pfn;
3459 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3460 mutex_lock(&kvm->slots_lock);
3462 if (likely(kvm_vmx->ept_identity_pagetable_done))
3465 if (!kvm_vmx->ept_identity_map_addr)
3466 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3467 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3469 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3470 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3474 idx = srcu_read_lock(&kvm->srcu);
3475 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3478 /* Set up identity-mapping pagetable for EPT in real mode */
3479 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3480 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3481 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3482 r = kvm_write_guest_page(kvm, identity_map_pfn,
3483 &tmp, i * sizeof(tmp), sizeof(tmp));
3487 kvm_vmx->ept_identity_pagetable_done = true;
3490 srcu_read_unlock(&kvm->srcu, idx);
3493 mutex_unlock(&kvm->slots_lock);
3497 static void seg_setup(int seg)
3499 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3502 vmcs_write16(sf->selector, 0);
3503 vmcs_writel(sf->base, 0);
3504 vmcs_write32(sf->limit, 0xffff);
3506 if (seg == VCPU_SREG_CS)
3507 ar |= 0x08; /* code segment */
3509 vmcs_write32(sf->ar_bytes, ar);
3512 static int alloc_apic_access_page(struct kvm *kvm)
3517 mutex_lock(&kvm->slots_lock);
3518 if (kvm->arch.apic_access_page_done)
3520 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3521 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3525 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3526 if (is_error_page(page)) {
3532 * Do not pin the page in memory, so that memory hot-unplug
3533 * is able to migrate it.
3536 kvm->arch.apic_access_page_done = true;
3538 mutex_unlock(&kvm->slots_lock);
3542 int allocate_vpid(void)
3548 spin_lock(&vmx_vpid_lock);
3549 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3550 if (vpid < VMX_NR_VPIDS)
3551 __set_bit(vpid, vmx_vpid_bitmap);
3554 spin_unlock(&vmx_vpid_lock);
3558 void free_vpid(int vpid)
3560 if (!enable_vpid || vpid == 0)
3562 spin_lock(&vmx_vpid_lock);
3563 __clear_bit(vpid, vmx_vpid_bitmap);
3564 spin_unlock(&vmx_vpid_lock);
3567 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3570 int f = sizeof(unsigned long);
3572 if (!cpu_has_vmx_msr_bitmap())
3575 if (static_branch_unlikely(&enable_evmcs))
3576 evmcs_touch_msr_bitmap();
3579 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3580 * have the write-low and read-high bitmap offsets the wrong way round.
3581 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3583 if (msr <= 0x1fff) {
3584 if (type & MSR_TYPE_R)
3586 __clear_bit(msr, msr_bitmap + 0x000 / f);
3588 if (type & MSR_TYPE_W)
3590 __clear_bit(msr, msr_bitmap + 0x800 / f);
3592 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3594 if (type & MSR_TYPE_R)
3596 __clear_bit(msr, msr_bitmap + 0x400 / f);
3598 if (type & MSR_TYPE_W)
3600 __clear_bit(msr, msr_bitmap + 0xc00 / f);
3605 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3608 int f = sizeof(unsigned long);
3610 if (!cpu_has_vmx_msr_bitmap())
3613 if (static_branch_unlikely(&enable_evmcs))
3614 evmcs_touch_msr_bitmap();
3617 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3618 * have the write-low and read-high bitmap offsets the wrong way round.
3619 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3621 if (msr <= 0x1fff) {
3622 if (type & MSR_TYPE_R)
3624 __set_bit(msr, msr_bitmap + 0x000 / f);
3626 if (type & MSR_TYPE_W)
3628 __set_bit(msr, msr_bitmap + 0x800 / f);
3630 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3632 if (type & MSR_TYPE_R)
3634 __set_bit(msr, msr_bitmap + 0x400 / f);
3636 if (type & MSR_TYPE_W)
3638 __set_bit(msr, msr_bitmap + 0xc00 / f);
3643 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3644 u32 msr, int type, bool value)
3647 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3649 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3652 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3656 if (cpu_has_secondary_exec_ctrls() &&
3657 (secondary_exec_controls_get(to_vmx(vcpu)) &
3658 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3659 mode |= MSR_BITMAP_MODE_X2APIC;
3660 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3661 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3667 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3672 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3673 unsigned word = msr / BITS_PER_LONG;
3674 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3675 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3678 if (mode & MSR_BITMAP_MODE_X2APIC) {
3680 * TPR reads and writes can be virtualized even if virtual interrupt
3681 * delivery is not in use.
3683 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3684 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3685 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3686 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3687 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3692 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3694 struct vcpu_vmx *vmx = to_vmx(vcpu);
3695 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3696 u8 mode = vmx_msr_bitmap_mode(vcpu);
3697 u8 changed = mode ^ vmx->msr_bitmap_mode;
3702 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3703 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3705 vmx->msr_bitmap_mode = mode;
3708 void pt_update_intercept_for_msr(struct vcpu_vmx *vmx)
3710 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3711 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3714 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_STATUS,
3716 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_BASE,
3718 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_MASK,
3720 vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_CR3_MATCH,
3722 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3723 vmx_set_intercept_for_msr(msr_bitmap,
3724 MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3725 vmx_set_intercept_for_msr(msr_bitmap,
3726 MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3730 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
3732 return enable_apicv;
3735 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3737 struct vcpu_vmx *vmx = to_vmx(vcpu);
3742 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3743 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3744 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3747 rvi = vmx_get_rvi();
3749 vapic_page = vmx->nested.virtual_apic_map.hva;
3750 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3752 return ((rvi & 0xf0) > (vppr & 0xf0));
3755 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3759 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3761 if (vcpu->mode == IN_GUEST_MODE) {
3763 * The vector of interrupt to be delivered to vcpu had
3764 * been set in PIR before this function.
3766 * Following cases will be reached in this block, and
3767 * we always send a notification event in all cases as
3770 * Case 1: vcpu keeps in non-root mode. Sending a
3771 * notification event posts the interrupt to vcpu.
3773 * Case 2: vcpu exits to root mode and is still
3774 * runnable. PIR will be synced to vIRR before the
3775 * next vcpu entry. Sending a notification event in
3776 * this case has no effect, as vcpu is not in root
3779 * Case 3: vcpu exits to root mode and is blocked.
3780 * vcpu_block() has already synced PIR to vIRR and
3781 * never blocks vcpu if vIRR is not cleared. Therefore,
3782 * a blocked vcpu here does not wait for any requested
3783 * interrupts in PIR, and sending a notification event
3784 * which has no effect is safe here.
3787 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3794 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3797 struct vcpu_vmx *vmx = to_vmx(vcpu);
3799 if (is_guest_mode(vcpu) &&
3800 vector == vmx->nested.posted_intr_nv) {
3802 * If a posted intr is not recognized by hardware,
3803 * we will accomplish it in the next vmentry.
3805 vmx->nested.pi_pending = true;
3806 kvm_make_request(KVM_REQ_EVENT, vcpu);
3807 /* the PIR and ON have been set by L1. */
3808 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3809 kvm_vcpu_kick(vcpu);
3815 * Send interrupt to vcpu via posted interrupt way.
3816 * 1. If target vcpu is running(non-root mode), send posted interrupt
3817 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3818 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3819 * interrupt from PIR in next vmentry.
3821 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3823 struct vcpu_vmx *vmx = to_vmx(vcpu);
3826 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3830 if (!vcpu->arch.apicv_active)
3833 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3836 /* If a previous notification has sent the IPI, nothing to do. */
3837 if (pi_test_and_set_on(&vmx->pi_desc))
3840 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3841 kvm_vcpu_kick(vcpu);
3847 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3848 * will not change in the lifetime of the guest.
3849 * Note that host-state that does change is set elsewhere. E.g., host-state
3850 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3852 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3856 unsigned long cr0, cr3, cr4;
3859 WARN_ON(cr0 & X86_CR0_TS);
3860 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
3863 * Save the most likely value for this task's CR3 in the VMCS.
3864 * We can't use __get_current_cr3_fast() because we're not atomic.
3867 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
3868 vmx->loaded_vmcs->host_state.cr3 = cr3;
3870 /* Save the most likely value for this task's CR4 in the VMCS. */
3871 cr4 = cr4_read_shadow();
3872 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
3873 vmx->loaded_vmcs->host_state.cr4 = cr4;
3875 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
3876 #ifdef CONFIG_X86_64
3878 * Load null selectors, so we can avoid reloading them in
3879 * vmx_prepare_switch_to_host(), in case userspace uses
3880 * the null selectors too (the expected case).
3882 vmcs_write16(HOST_DS_SELECTOR, 0);
3883 vmcs_write16(HOST_ES_SELECTOR, 0);
3885 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3886 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3888 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
3889 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
3891 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
3893 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
3895 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3896 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3897 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
3898 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
3900 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
3901 rdmsr(MSR_IA32_CR_PAT, low32, high32);
3902 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
3905 if (cpu_has_load_ia32_efer())
3906 vmcs_write64(HOST_IA32_EFER, host_efer);
3909 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
3911 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
3913 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
3914 if (is_guest_mode(&vmx->vcpu))
3915 vmx->vcpu.arch.cr4_guest_owned_bits &=
3916 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
3917 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
3920 u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
3922 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
3924 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
3925 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
3928 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
3930 if (!enable_preemption_timer)
3931 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3933 return pin_based_exec_ctrl;
3936 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
3938 struct vcpu_vmx *vmx = to_vmx(vcpu);
3940 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
3941 if (cpu_has_secondary_exec_ctrls()) {
3942 if (kvm_vcpu_apicv_active(vcpu))
3943 secondary_exec_controls_setbit(vmx,
3944 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3945 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3947 secondary_exec_controls_clearbit(vmx,
3948 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3949 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3952 if (cpu_has_vmx_msr_bitmap())
3953 vmx_update_msr_bitmap(vcpu);
3956 u32 vmx_exec_control(struct vcpu_vmx *vmx)
3958 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
3960 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
3961 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
3963 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
3964 exec_control &= ~CPU_BASED_TPR_SHADOW;
3965 #ifdef CONFIG_X86_64
3966 exec_control |= CPU_BASED_CR8_STORE_EXITING |
3967 CPU_BASED_CR8_LOAD_EXITING;
3971 exec_control |= CPU_BASED_CR3_STORE_EXITING |
3972 CPU_BASED_CR3_LOAD_EXITING |
3973 CPU_BASED_INVLPG_EXITING;
3974 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
3975 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
3976 CPU_BASED_MONITOR_EXITING);
3977 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
3978 exec_control &= ~CPU_BASED_HLT_EXITING;
3979 return exec_control;
3983 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
3985 struct kvm_vcpu *vcpu = &vmx->vcpu;
3987 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
3989 if (pt_mode == PT_MODE_SYSTEM)
3990 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
3991 if (!cpu_need_virtualize_apic_accesses(vcpu))
3992 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3994 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
3996 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
3997 enable_unrestricted_guest = 0;
3999 if (!enable_unrestricted_guest)
4000 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4001 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4002 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4003 if (!kvm_vcpu_apicv_active(vcpu))
4004 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4005 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4006 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4008 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4009 * in vmx_set_cr4. */
4010 exec_control &= ~SECONDARY_EXEC_DESC;
4012 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4014 We can NOT enable shadow_vmcs here because we don't have yet
4017 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4020 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4022 if (vmx_xsaves_supported()) {
4023 /* Exposing XSAVES only when XSAVE is exposed */
4024 bool xsaves_enabled =
4025 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4026 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4028 if (!xsaves_enabled)
4029 exec_control &= ~SECONDARY_EXEC_XSAVES;
4033 vmx->nested.msrs.secondary_ctls_high |=
4034 SECONDARY_EXEC_XSAVES;
4036 vmx->nested.msrs.secondary_ctls_high &=
4037 ~SECONDARY_EXEC_XSAVES;
4041 if (vmx_rdtscp_supported()) {
4042 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
4043 if (!rdtscp_enabled)
4044 exec_control &= ~SECONDARY_EXEC_RDTSCP;
4048 vmx->nested.msrs.secondary_ctls_high |=
4049 SECONDARY_EXEC_RDTSCP;
4051 vmx->nested.msrs.secondary_ctls_high &=
4052 ~SECONDARY_EXEC_RDTSCP;
4056 if (vmx_invpcid_supported()) {
4057 /* Exposing INVPCID only when PCID is exposed */
4058 bool invpcid_enabled =
4059 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
4060 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
4062 if (!invpcid_enabled) {
4063 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
4064 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
4068 if (invpcid_enabled)
4069 vmx->nested.msrs.secondary_ctls_high |=
4070 SECONDARY_EXEC_ENABLE_INVPCID;
4072 vmx->nested.msrs.secondary_ctls_high &=
4073 ~SECONDARY_EXEC_ENABLE_INVPCID;
4077 if (vmx_rdrand_supported()) {
4078 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
4080 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
4084 vmx->nested.msrs.secondary_ctls_high |=
4085 SECONDARY_EXEC_RDRAND_EXITING;
4087 vmx->nested.msrs.secondary_ctls_high &=
4088 ~SECONDARY_EXEC_RDRAND_EXITING;
4092 if (vmx_rdseed_supported()) {
4093 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
4095 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
4099 vmx->nested.msrs.secondary_ctls_high |=
4100 SECONDARY_EXEC_RDSEED_EXITING;
4102 vmx->nested.msrs.secondary_ctls_high &=
4103 ~SECONDARY_EXEC_RDSEED_EXITING;
4107 if (vmx_waitpkg_supported()) {
4108 bool waitpkg_enabled =
4109 guest_cpuid_has(vcpu, X86_FEATURE_WAITPKG);
4111 if (!waitpkg_enabled)
4112 exec_control &= ~SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4115 if (waitpkg_enabled)
4116 vmx->nested.msrs.secondary_ctls_high |=
4117 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4119 vmx->nested.msrs.secondary_ctls_high &=
4120 ~SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE;
4124 vmx->secondary_exec_control = exec_control;
4127 static void ept_set_mmio_spte_mask(void)
4130 * EPT Misconfigurations can be generated if the value of bits 2:0
4131 * of an EPT paging-structure entry is 110b (write/execute).
4133 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
4134 VMX_EPT_MISCONFIG_WX_VALUE, 0);
4137 #define VMX_XSS_EXIT_BITMAP 0
4140 * Sets up the vmcs for emulated real mode.
4142 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
4147 nested_vmx_vcpu_setup();
4149 if (cpu_has_vmx_msr_bitmap())
4150 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4152 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4155 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4156 vmx->hv_deadline_tsc = -1;
4158 exec_controls_set(vmx, vmx_exec_control(vmx));
4160 if (cpu_has_secondary_exec_ctrls()) {
4161 vmx_compute_secondary_exec_control(vmx);
4162 secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
4165 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4166 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4167 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4168 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4169 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4171 vmcs_write16(GUEST_INTR_STATUS, 0);
4173 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4174 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4177 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4178 vmcs_write32(PLE_GAP, ple_gap);
4179 vmx->ple_window = ple_window;
4180 vmx->ple_window_dirty = true;
4183 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4184 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4185 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4187 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4188 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4189 vmx_set_constant_host_state(vmx);
4190 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4191 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4193 if (cpu_has_vmx_vmfunc())
4194 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4196 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4197 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4198 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4199 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4200 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4202 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4203 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4205 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
4206 u32 index = vmx_msr_index[i];
4207 u32 data_low, data_high;
4210 if (rdmsr_safe(index, &data_low, &data_high) < 0)
4212 if (wrmsr_safe(index, data_low, data_high) < 0)
4214 vmx->guest_msrs[j].index = i;
4215 vmx->guest_msrs[j].data = 0;
4216 vmx->guest_msrs[j].mask = -1ull;
4220 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4222 /* 22.2.1, 20.8.1 */
4223 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4225 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
4226 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
4228 set_cr4_guest_host_mask(vmx);
4230 if (vmx_xsaves_supported())
4231 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4234 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4235 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4238 if (cpu_has_vmx_encls_vmexit())
4239 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
4241 if (pt_mode == PT_MODE_HOST_GUEST) {
4242 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4243 /* Bit[6~0] are forced to 1, writes are ignored. */
4244 vmx->pt_desc.guest.output_mask = 0x7F;
4245 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4249 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4251 struct vcpu_vmx *vmx = to_vmx(vcpu);
4252 struct msr_data apic_base_msr;
4255 vmx->rmode.vm86_active = 0;
4258 vmx->msr_ia32_umwait_control = 0;
4260 vcpu->arch.microcode_version = 0x100000000ULL;
4261 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4262 vmx->hv_deadline_tsc = -1;
4263 kvm_set_cr8(vcpu, 0);
4266 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4267 MSR_IA32_APICBASE_ENABLE;
4268 if (kvm_vcpu_is_reset_bsp(vcpu))
4269 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4270 apic_base_msr.host_initiated = true;
4271 kvm_set_apic_base(vcpu, &apic_base_msr);
4274 vmx_segment_cache_clear(vmx);
4276 seg_setup(VCPU_SREG_CS);
4277 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4278 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4280 seg_setup(VCPU_SREG_DS);
4281 seg_setup(VCPU_SREG_ES);
4282 seg_setup(VCPU_SREG_FS);
4283 seg_setup(VCPU_SREG_GS);
4284 seg_setup(VCPU_SREG_SS);
4286 vmcs_write16(GUEST_TR_SELECTOR, 0);
4287 vmcs_writel(GUEST_TR_BASE, 0);
4288 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4289 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4291 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4292 vmcs_writel(GUEST_LDTR_BASE, 0);
4293 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4294 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4297 vmcs_write32(GUEST_SYSENTER_CS, 0);
4298 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4299 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4300 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4303 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4304 kvm_rip_write(vcpu, 0xfff0);
4306 vmcs_writel(GUEST_GDTR_BASE, 0);
4307 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4309 vmcs_writel(GUEST_IDTR_BASE, 0);
4310 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4312 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4313 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4314 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4315 if (kvm_mpx_supported())
4316 vmcs_write64(GUEST_BNDCFGS, 0);
4320 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4322 if (cpu_has_vmx_tpr_shadow() && !init_event) {
4323 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4324 if (cpu_need_tpr_shadow(vcpu))
4325 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4326 __pa(vcpu->arch.apic->regs));
4327 vmcs_write32(TPR_THRESHOLD, 0);
4330 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4333 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4335 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4336 vmx->vcpu.arch.cr0 = cr0;
4337 vmx_set_cr0(vcpu, cr0); /* enter rmode */
4338 vmx_set_cr4(vcpu, 0);
4339 vmx_set_efer(vcpu, 0);
4341 update_exception_bitmap(vcpu);
4343 vpid_sync_context(vmx->vpid);
4345 vmx_clear_hlt(vcpu);
4348 static void enable_irq_window(struct kvm_vcpu *vcpu)
4350 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_VIRTUAL_INTR_PENDING);
4353 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4356 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4357 enable_irq_window(vcpu);
4361 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_VIRTUAL_NMI_PENDING);
4364 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4366 struct vcpu_vmx *vmx = to_vmx(vcpu);
4368 int irq = vcpu->arch.interrupt.nr;
4370 trace_kvm_inj_virq(irq);
4372 ++vcpu->stat.irq_injections;
4373 if (vmx->rmode.vm86_active) {
4375 if (vcpu->arch.interrupt.soft)
4376 inc_eip = vcpu->arch.event_exit_inst_len;
4377 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4380 intr = irq | INTR_INFO_VALID_MASK;
4381 if (vcpu->arch.interrupt.soft) {
4382 intr |= INTR_TYPE_SOFT_INTR;
4383 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4384 vmx->vcpu.arch.event_exit_inst_len);
4386 intr |= INTR_TYPE_EXT_INTR;
4387 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4389 vmx_clear_hlt(vcpu);
4392 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4394 struct vcpu_vmx *vmx = to_vmx(vcpu);
4398 * Tracking the NMI-blocked state in software is built upon
4399 * finding the next open IRQ window. This, in turn, depends on
4400 * well-behaving guests: They have to keep IRQs disabled at
4401 * least as long as the NMI handler runs. Otherwise we may
4402 * cause NMI nesting, maybe breaking the guest. But as this is
4403 * highly unlikely, we can live with the residual risk.
4405 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4406 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4409 ++vcpu->stat.nmi_injections;
4410 vmx->loaded_vmcs->nmi_known_unmasked = false;
4412 if (vmx->rmode.vm86_active) {
4413 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4417 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4418 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4420 vmx_clear_hlt(vcpu);
4423 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4425 struct vcpu_vmx *vmx = to_vmx(vcpu);
4429 return vmx->loaded_vmcs->soft_vnmi_blocked;
4430 if (vmx->loaded_vmcs->nmi_known_unmasked)
4432 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4433 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4437 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4439 struct vcpu_vmx *vmx = to_vmx(vcpu);
4442 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4443 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4444 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4447 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4449 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4450 GUEST_INTR_STATE_NMI);
4452 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4453 GUEST_INTR_STATE_NMI);
4457 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4459 if (to_vmx(vcpu)->nested.nested_run_pending)
4463 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4466 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4467 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4468 | GUEST_INTR_STATE_NMI));
4471 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4473 if (to_vmx(vcpu)->nested.nested_run_pending)
4476 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4479 return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4480 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4481 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4484 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4488 if (enable_unrestricted_guest)
4491 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4495 to_kvm_vmx(kvm)->tss_addr = addr;
4496 return init_rmode_tss(kvm);
4499 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4501 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4505 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4510 * Update instruction length as we may reinject the exception
4511 * from user space while in guest debugging mode.
4513 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4514 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4515 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4519 if (vcpu->guest_debug &
4520 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4537 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4538 int vec, u32 err_code)
4541 * Instruction with address size override prefix opcode 0x67
4542 * Cause the #SS fault with 0 error code in VM86 mode.
4544 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4545 if (kvm_emulate_instruction(vcpu, 0)) {
4546 if (vcpu->arch.halt_request) {
4547 vcpu->arch.halt_request = 0;
4548 return kvm_vcpu_halt(vcpu);
4556 * Forward all other exceptions that are valid in real mode.
4557 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4558 * the required debugging infrastructure rework.
4560 kvm_queue_exception(vcpu, vec);
4565 * Trigger machine check on the host. We assume all the MSRs are already set up
4566 * by the CPU and that we still run on the same CPU as the MCE occurred on.
4567 * We pass a fake environment to the machine check handler because we want
4568 * the guest to be always treated like user space, no matter what context
4569 * it used internally.
4571 static void kvm_machine_check(void)
4573 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4574 struct pt_regs regs = {
4575 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4576 .flags = X86_EFLAGS_IF,
4579 do_machine_check(®s, 0);
4583 static int handle_machine_check(struct kvm_vcpu *vcpu)
4585 /* handled by vmx_vcpu_run() */
4589 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4591 struct vcpu_vmx *vmx = to_vmx(vcpu);
4592 struct kvm_run *kvm_run = vcpu->run;
4593 u32 intr_info, ex_no, error_code;
4594 unsigned long cr2, rip, dr6;
4597 vect_info = vmx->idt_vectoring_info;
4598 intr_info = vmx->exit_intr_info;
4600 if (is_machine_check(intr_info) || is_nmi(intr_info))
4601 return 1; /* handled by handle_exception_nmi_irqoff() */
4603 if (is_invalid_opcode(intr_info))
4604 return handle_ud(vcpu);
4607 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4608 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4610 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4611 WARN_ON_ONCE(!enable_vmware_backdoor);
4614 * VMware backdoor emulation on #GP interception only handles
4615 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4616 * error code on #GP.
4619 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4622 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4626 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4627 * MMIO, it is better to report an internal error.
4628 * See the comments in vmx_handle_exit.
4630 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4631 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4632 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4633 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4634 vcpu->run->internal.ndata = 3;
4635 vcpu->run->internal.data[0] = vect_info;
4636 vcpu->run->internal.data[1] = intr_info;
4637 vcpu->run->internal.data[2] = error_code;
4641 if (is_page_fault(intr_info)) {
4642 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4643 /* EPT won't cause page fault directly */
4644 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
4645 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4648 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4650 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4651 return handle_rmode_exception(vcpu, ex_no, error_code);
4655 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4658 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4659 if (!(vcpu->guest_debug &
4660 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4661 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
4662 vcpu->arch.dr6 |= dr6 | DR6_RTM;
4663 if (is_icebp(intr_info))
4664 WARN_ON(!skip_emulated_instruction(vcpu));
4666 kvm_queue_exception(vcpu, DB_VECTOR);
4669 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4670 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4674 * Update instruction length as we may reinject #BP from
4675 * user space while in guest debugging mode. Reading it for
4676 * #DB as well causes no harm, it is not used in that case.
4678 vmx->vcpu.arch.event_exit_inst_len =
4679 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4680 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4681 rip = kvm_rip_read(vcpu);
4682 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4683 kvm_run->debug.arch.exception = ex_no;
4686 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4687 kvm_run->ex.exception = ex_no;
4688 kvm_run->ex.error_code = error_code;
4694 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4696 ++vcpu->stat.irq_exits;
4700 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4702 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4703 vcpu->mmio_needed = 0;
4707 static int handle_io(struct kvm_vcpu *vcpu)
4709 unsigned long exit_qualification;
4710 int size, in, string;
4713 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4714 string = (exit_qualification & 16) != 0;
4716 ++vcpu->stat.io_exits;
4719 return kvm_emulate_instruction(vcpu, 0);
4721 port = exit_qualification >> 16;
4722 size = (exit_qualification & 7) + 1;
4723 in = (exit_qualification & 8) != 0;
4725 return kvm_fast_pio(vcpu, size, port, in);
4729 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4732 * Patch in the VMCALL instruction:
4734 hypercall[0] = 0x0f;
4735 hypercall[1] = 0x01;
4736 hypercall[2] = 0xc1;
4739 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4740 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4742 if (is_guest_mode(vcpu)) {
4743 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4744 unsigned long orig_val = val;
4747 * We get here when L2 changed cr0 in a way that did not change
4748 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4749 * but did change L0 shadowed bits. So we first calculate the
4750 * effective cr0 value that L1 would like to write into the
4751 * hardware. It consists of the L2-owned bits from the new
4752 * value combined with the L1-owned bits from L1's guest_cr0.
4754 val = (val & ~vmcs12->cr0_guest_host_mask) |
4755 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4757 if (!nested_guest_cr0_valid(vcpu, val))
4760 if (kvm_set_cr0(vcpu, val))
4762 vmcs_writel(CR0_READ_SHADOW, orig_val);
4765 if (to_vmx(vcpu)->nested.vmxon &&
4766 !nested_host_cr0_valid(vcpu, val))
4769 return kvm_set_cr0(vcpu, val);
4773 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4775 if (is_guest_mode(vcpu)) {
4776 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4777 unsigned long orig_val = val;
4779 /* analogously to handle_set_cr0 */
4780 val = (val & ~vmcs12->cr4_guest_host_mask) |
4781 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4782 if (kvm_set_cr4(vcpu, val))
4784 vmcs_writel(CR4_READ_SHADOW, orig_val);
4787 return kvm_set_cr4(vcpu, val);
4790 static int handle_desc(struct kvm_vcpu *vcpu)
4792 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4793 return kvm_emulate_instruction(vcpu, 0);
4796 static int handle_cr(struct kvm_vcpu *vcpu)
4798 unsigned long exit_qualification, val;
4804 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4805 cr = exit_qualification & 15;
4806 reg = (exit_qualification >> 8) & 15;
4807 switch ((exit_qualification >> 4) & 3) {
4808 case 0: /* mov to cr */
4809 val = kvm_register_readl(vcpu, reg);
4810 trace_kvm_cr_write(cr, val);
4813 err = handle_set_cr0(vcpu, val);
4814 return kvm_complete_insn_gp(vcpu, err);
4816 WARN_ON_ONCE(enable_unrestricted_guest);
4817 err = kvm_set_cr3(vcpu, val);
4818 return kvm_complete_insn_gp(vcpu, err);
4820 err = handle_set_cr4(vcpu, val);
4821 return kvm_complete_insn_gp(vcpu, err);
4823 u8 cr8_prev = kvm_get_cr8(vcpu);
4825 err = kvm_set_cr8(vcpu, cr8);
4826 ret = kvm_complete_insn_gp(vcpu, err);
4827 if (lapic_in_kernel(vcpu))
4829 if (cr8_prev <= cr8)
4832 * TODO: we might be squashing a
4833 * KVM_GUESTDBG_SINGLESTEP-triggered
4834 * KVM_EXIT_DEBUG here.
4836 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4842 WARN_ONCE(1, "Guest should always own CR0.TS");
4843 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4844 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4845 return kvm_skip_emulated_instruction(vcpu);
4846 case 1: /*mov from cr*/
4849 WARN_ON_ONCE(enable_unrestricted_guest);
4850 val = kvm_read_cr3(vcpu);
4851 kvm_register_write(vcpu, reg, val);
4852 trace_kvm_cr_read(cr, val);
4853 return kvm_skip_emulated_instruction(vcpu);
4855 val = kvm_get_cr8(vcpu);
4856 kvm_register_write(vcpu, reg, val);
4857 trace_kvm_cr_read(cr, val);
4858 return kvm_skip_emulated_instruction(vcpu);
4862 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4863 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4864 kvm_lmsw(vcpu, val);
4866 return kvm_skip_emulated_instruction(vcpu);
4870 vcpu->run->exit_reason = 0;
4871 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4872 (int)(exit_qualification >> 4) & 3, cr);
4876 static int handle_dr(struct kvm_vcpu *vcpu)
4878 unsigned long exit_qualification;
4881 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4882 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
4884 /* First, if DR does not exist, trigger UD */
4885 if (!kvm_require_dr(vcpu, dr))
4888 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
4889 if (!kvm_require_cpl(vcpu, 0))
4891 dr7 = vmcs_readl(GUEST_DR7);
4894 * As the vm-exit takes precedence over the debug trap, we
4895 * need to emulate the latter, either for the host or the
4896 * guest debugging itself.
4898 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
4899 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
4900 vcpu->run->debug.arch.dr7 = dr7;
4901 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
4902 vcpu->run->debug.arch.exception = DB_VECTOR;
4903 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
4906 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
4907 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
4908 kvm_queue_exception(vcpu, DB_VECTOR);
4913 if (vcpu->guest_debug == 0) {
4914 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
4917 * No more DR vmexits; force a reload of the debug registers
4918 * and reenter on this instruction. The next vmexit will
4919 * retrieve the full state of the debug registers.
4921 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4925 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
4926 if (exit_qualification & TYPE_MOV_FROM_DR) {
4929 if (kvm_get_dr(vcpu, dr, &val))
4931 kvm_register_write(vcpu, reg, val);
4933 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
4936 return kvm_skip_emulated_instruction(vcpu);
4939 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
4941 return vcpu->arch.dr6;
4944 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
4948 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
4950 get_debugreg(vcpu->arch.db[0], 0);
4951 get_debugreg(vcpu->arch.db[1], 1);
4952 get_debugreg(vcpu->arch.db[2], 2);
4953 get_debugreg(vcpu->arch.db[3], 3);
4954 get_debugreg(vcpu->arch.dr6, 6);
4955 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
4957 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
4958 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
4961 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
4963 vmcs_writel(GUEST_DR7, val);
4966 static int handle_cpuid(struct kvm_vcpu *vcpu)
4968 return kvm_emulate_cpuid(vcpu);
4971 static int handle_rdmsr(struct kvm_vcpu *vcpu)
4973 return kvm_emulate_rdmsr(vcpu);
4976 static int handle_wrmsr(struct kvm_vcpu *vcpu)
4978 return kvm_emulate_wrmsr(vcpu);
4981 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
4983 kvm_apic_update_ppr(vcpu);
4987 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
4989 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_VIRTUAL_INTR_PENDING);
4991 kvm_make_request(KVM_REQ_EVENT, vcpu);
4993 ++vcpu->stat.irq_window_exits;
4997 static int handle_halt(struct kvm_vcpu *vcpu)
4999 return kvm_emulate_halt(vcpu);
5002 static int handle_vmcall(struct kvm_vcpu *vcpu)
5004 return kvm_emulate_hypercall(vcpu);
5007 static int handle_invd(struct kvm_vcpu *vcpu)
5009 return kvm_emulate_instruction(vcpu, 0);
5012 static int handle_invlpg(struct kvm_vcpu *vcpu)
5014 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5016 kvm_mmu_invlpg(vcpu, exit_qualification);
5017 return kvm_skip_emulated_instruction(vcpu);
5020 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5024 err = kvm_rdpmc(vcpu);
5025 return kvm_complete_insn_gp(vcpu, err);
5028 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5030 return kvm_emulate_wbinvd(vcpu);
5033 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5035 u64 new_bv = kvm_read_edx_eax(vcpu);
5036 u32 index = kvm_rcx_read(vcpu);
5038 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5039 return kvm_skip_emulated_instruction(vcpu);
5043 static int handle_apic_access(struct kvm_vcpu *vcpu)
5045 if (likely(fasteoi)) {
5046 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5047 int access_type, offset;
5049 access_type = exit_qualification & APIC_ACCESS_TYPE;
5050 offset = exit_qualification & APIC_ACCESS_OFFSET;
5052 * Sane guest uses MOV to write EOI, with written value
5053 * not cared. So make a short-circuit here by avoiding
5054 * heavy instruction emulation.
5056 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5057 (offset == APIC_EOI)) {
5058 kvm_lapic_set_eoi(vcpu);
5059 return kvm_skip_emulated_instruction(vcpu);
5062 return kvm_emulate_instruction(vcpu, 0);
5065 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5067 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5068 int vector = exit_qualification & 0xff;
5070 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5071 kvm_apic_set_eoi_accelerated(vcpu, vector);
5075 static int handle_apic_write(struct kvm_vcpu *vcpu)
5077 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5078 u32 offset = exit_qualification & 0xfff;
5080 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5081 kvm_apic_write_nodecode(vcpu, offset);
5085 static int handle_task_switch(struct kvm_vcpu *vcpu)
5087 struct vcpu_vmx *vmx = to_vmx(vcpu);
5088 unsigned long exit_qualification;
5089 bool has_error_code = false;
5092 int reason, type, idt_v, idt_index;
5094 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5095 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5096 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5098 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5100 reason = (u32)exit_qualification >> 30;
5101 if (reason == TASK_SWITCH_GATE && idt_v) {
5103 case INTR_TYPE_NMI_INTR:
5104 vcpu->arch.nmi_injected = false;
5105 vmx_set_nmi_mask(vcpu, true);
5107 case INTR_TYPE_EXT_INTR:
5108 case INTR_TYPE_SOFT_INTR:
5109 kvm_clear_interrupt_queue(vcpu);
5111 case INTR_TYPE_HARD_EXCEPTION:
5112 if (vmx->idt_vectoring_info &
5113 VECTORING_INFO_DELIVER_CODE_MASK) {
5114 has_error_code = true;
5116 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5119 case INTR_TYPE_SOFT_EXCEPTION:
5120 kvm_clear_exception_queue(vcpu);
5126 tss_selector = exit_qualification;
5128 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5129 type != INTR_TYPE_EXT_INTR &&
5130 type != INTR_TYPE_NMI_INTR))
5131 WARN_ON(!skip_emulated_instruction(vcpu));
5134 * TODO: What about debug traps on tss switch?
5135 * Are we supposed to inject them and update dr6?
5137 return kvm_task_switch(vcpu, tss_selector,
5138 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5139 reason, has_error_code, error_code);
5142 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5144 unsigned long exit_qualification;
5148 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5151 * EPT violation happened while executing iret from NMI,
5152 * "blocked by NMI" bit has to be set before next VM entry.
5153 * There are errata that may cause this bit to not be set:
5156 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5158 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5159 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5161 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5162 trace_kvm_page_fault(gpa, exit_qualification);
5164 /* Is it a read fault? */
5165 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5166 ? PFERR_USER_MASK : 0;
5167 /* Is it a write fault? */
5168 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5169 ? PFERR_WRITE_MASK : 0;
5170 /* Is it a fetch fault? */
5171 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5172 ? PFERR_FETCH_MASK : 0;
5173 /* ept page table entry is present? */
5174 error_code |= (exit_qualification &
5175 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5176 EPT_VIOLATION_EXECUTABLE))
5177 ? PFERR_PRESENT_MASK : 0;
5179 error_code |= (exit_qualification & 0x100) != 0 ?
5180 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5182 vcpu->arch.exit_qualification = exit_qualification;
5183 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5186 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5191 * A nested guest cannot optimize MMIO vmexits, because we have an
5192 * nGPA here instead of the required GPA.
5194 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5195 if (!is_guest_mode(vcpu) &&
5196 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5197 trace_kvm_fast_mmio(gpa);
5198 return kvm_skip_emulated_instruction(vcpu);
5201 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5204 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5206 WARN_ON_ONCE(!enable_vnmi);
5207 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_VIRTUAL_NMI_PENDING);
5208 ++vcpu->stat.nmi_window_exits;
5209 kvm_make_request(KVM_REQ_EVENT, vcpu);
5214 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5216 struct vcpu_vmx *vmx = to_vmx(vcpu);
5217 bool intr_window_requested;
5218 unsigned count = 130;
5221 * We should never reach the point where we are emulating L2
5222 * due to invalid guest state as that means we incorrectly
5223 * allowed a nested VMEntry with an invalid vmcs12.
5225 WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
5227 intr_window_requested = exec_controls_get(vmx) &
5228 CPU_BASED_VIRTUAL_INTR_PENDING;
5230 while (vmx->emulation_required && count-- != 0) {
5231 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5232 return handle_interrupt_window(&vmx->vcpu);
5234 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5237 if (!kvm_emulate_instruction(vcpu, 0))
5240 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5241 vcpu->arch.exception.pending) {
5242 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5243 vcpu->run->internal.suberror =
5244 KVM_INTERNAL_ERROR_EMULATION;
5245 vcpu->run->internal.ndata = 0;
5249 if (vcpu->arch.halt_request) {
5250 vcpu->arch.halt_request = 0;
5251 return kvm_vcpu_halt(vcpu);
5255 * Note, return 1 and not 0, vcpu_run() is responsible for
5256 * morphing the pending signal into the proper return code.
5258 if (signal_pending(current))
5268 static void grow_ple_window(struct kvm_vcpu *vcpu)
5270 struct vcpu_vmx *vmx = to_vmx(vcpu);
5271 unsigned int old = vmx->ple_window;
5273 vmx->ple_window = __grow_ple_window(old, ple_window,
5277 if (vmx->ple_window != old) {
5278 vmx->ple_window_dirty = true;
5279 trace_kvm_ple_window_update(vcpu->vcpu_id,
5280 vmx->ple_window, old);
5284 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5286 struct vcpu_vmx *vmx = to_vmx(vcpu);
5287 unsigned int old = vmx->ple_window;
5289 vmx->ple_window = __shrink_ple_window(old, ple_window,
5293 if (vmx->ple_window != old) {
5294 vmx->ple_window_dirty = true;
5295 trace_kvm_ple_window_update(vcpu->vcpu_id,
5296 vmx->ple_window, old);
5301 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5303 static void wakeup_handler(void)
5305 struct kvm_vcpu *vcpu;
5306 int cpu = smp_processor_id();
5308 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5309 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5310 blocked_vcpu_list) {
5311 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5313 if (pi_test_on(pi_desc) == 1)
5314 kvm_vcpu_kick(vcpu);
5316 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5319 static void vmx_enable_tdp(void)
5321 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5322 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5323 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5324 0ull, VMX_EPT_EXECUTABLE_MASK,
5325 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5326 VMX_EPT_RWX_MASK, 0ull);
5328 ept_set_mmio_spte_mask();
5333 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5334 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5336 static int handle_pause(struct kvm_vcpu *vcpu)
5338 if (!kvm_pause_in_guest(vcpu->kvm))
5339 grow_ple_window(vcpu);
5342 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5343 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5344 * never set PAUSE_EXITING and just set PLE if supported,
5345 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5347 kvm_vcpu_on_spin(vcpu, true);
5348 return kvm_skip_emulated_instruction(vcpu);
5351 static int handle_nop(struct kvm_vcpu *vcpu)
5353 return kvm_skip_emulated_instruction(vcpu);
5356 static int handle_mwait(struct kvm_vcpu *vcpu)
5358 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5359 return handle_nop(vcpu);
5362 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5364 kvm_queue_exception(vcpu, UD_VECTOR);
5368 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5373 static int handle_monitor(struct kvm_vcpu *vcpu)
5375 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5376 return handle_nop(vcpu);
5379 static int handle_invpcid(struct kvm_vcpu *vcpu)
5381 u32 vmx_instruction_info;
5385 struct x86_exception e;
5387 unsigned long roots_to_free = 0;
5393 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5394 kvm_queue_exception(vcpu, UD_VECTOR);
5398 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5399 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5402 kvm_inject_gp(vcpu, 0);
5406 /* According to the Intel instruction reference, the memory operand
5407 * is read even if it isn't needed (e.g., for type==all)
5409 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5410 vmx_instruction_info, false,
5411 sizeof(operand), &gva))
5414 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5415 kvm_inject_page_fault(vcpu, &e);
5419 if (operand.pcid >> 12 != 0) {
5420 kvm_inject_gp(vcpu, 0);
5424 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5427 case INVPCID_TYPE_INDIV_ADDR:
5428 if ((!pcid_enabled && (operand.pcid != 0)) ||
5429 is_noncanonical_address(operand.gla, vcpu)) {
5430 kvm_inject_gp(vcpu, 0);
5433 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5434 return kvm_skip_emulated_instruction(vcpu);
5436 case INVPCID_TYPE_SINGLE_CTXT:
5437 if (!pcid_enabled && (operand.pcid != 0)) {
5438 kvm_inject_gp(vcpu, 0);
5442 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5443 kvm_mmu_sync_roots(vcpu);
5444 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5447 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5448 if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
5450 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5452 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5454 * If neither the current cr3 nor any of the prev_roots use the
5455 * given PCID, then nothing needs to be done here because a
5456 * resync will happen anyway before switching to any other CR3.
5459 return kvm_skip_emulated_instruction(vcpu);
5461 case INVPCID_TYPE_ALL_NON_GLOBAL:
5463 * Currently, KVM doesn't mark global entries in the shadow
5464 * page tables, so a non-global flush just degenerates to a
5465 * global flush. If needed, we could optimize this later by
5466 * keeping track of global entries in shadow page tables.
5470 case INVPCID_TYPE_ALL_INCL_GLOBAL:
5471 kvm_mmu_unload(vcpu);
5472 return kvm_skip_emulated_instruction(vcpu);
5475 BUG(); /* We have already checked above that type <= 3 */
5479 static int handle_pml_full(struct kvm_vcpu *vcpu)
5481 unsigned long exit_qualification;
5483 trace_kvm_pml_full(vcpu->vcpu_id);
5485 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5488 * PML buffer FULL happened while executing iret from NMI,
5489 * "blocked by NMI" bit has to be set before next VM entry.
5491 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5493 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5494 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5495 GUEST_INTR_STATE_NMI);
5498 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5499 * here.., and there's no userspace involvement needed for PML.
5504 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5506 struct vcpu_vmx *vmx = to_vmx(vcpu);
5508 if (!vmx->req_immediate_exit &&
5509 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled))
5510 kvm_lapic_expired_hv_timer(vcpu);
5516 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5517 * are overwritten by nested_vmx_setup() when nested=1.
5519 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5521 kvm_queue_exception(vcpu, UD_VECTOR);
5525 static int handle_encls(struct kvm_vcpu *vcpu)
5528 * SGX virtualization is not yet supported. There is no software
5529 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5530 * to prevent the guest from executing ENCLS.
5532 kvm_queue_exception(vcpu, UD_VECTOR);
5537 * The exit handlers return 1 if the exit was handled fully and guest execution
5538 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5539 * to be done to userspace and return 0.
5541 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5542 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
5543 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5544 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5545 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5546 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5547 [EXIT_REASON_CR_ACCESS] = handle_cr,
5548 [EXIT_REASON_DR_ACCESS] = handle_dr,
5549 [EXIT_REASON_CPUID] = handle_cpuid,
5550 [EXIT_REASON_MSR_READ] = handle_rdmsr,
5551 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
5552 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
5553 [EXIT_REASON_HLT] = handle_halt,
5554 [EXIT_REASON_INVD] = handle_invd,
5555 [EXIT_REASON_INVLPG] = handle_invlpg,
5556 [EXIT_REASON_RDPMC] = handle_rdpmc,
5557 [EXIT_REASON_VMCALL] = handle_vmcall,
5558 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5559 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5560 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5561 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5562 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5563 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5564 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5565 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5566 [EXIT_REASON_VMON] = handle_vmx_instruction,
5567 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5568 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5569 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5570 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5571 [EXIT_REASON_WBINVD] = handle_wbinvd,
5572 [EXIT_REASON_XSETBV] = handle_xsetbv,
5573 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5574 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5575 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5576 [EXIT_REASON_LDTR_TR] = handle_desc,
5577 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5578 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5579 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5580 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5581 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5582 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5583 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5584 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5585 [EXIT_REASON_RDRAND] = handle_invalid_op,
5586 [EXIT_REASON_RDSEED] = handle_invalid_op,
5587 [EXIT_REASON_PML_FULL] = handle_pml_full,
5588 [EXIT_REASON_INVPCID] = handle_invpcid,
5589 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5590 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5591 [EXIT_REASON_ENCLS] = handle_encls,
5594 static const int kvm_vmx_max_exit_handlers =
5595 ARRAY_SIZE(kvm_vmx_exit_handlers);
5597 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5599 *info1 = vmcs_readl(EXIT_QUALIFICATION);
5600 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
5603 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5606 __free_page(vmx->pml_pg);
5611 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5613 struct vcpu_vmx *vmx = to_vmx(vcpu);
5617 pml_idx = vmcs_read16(GUEST_PML_INDEX);
5619 /* Do nothing if PML buffer is empty */
5620 if (pml_idx == (PML_ENTITY_NUM - 1))
5623 /* PML index always points to next available PML buffer entity */
5624 if (pml_idx >= PML_ENTITY_NUM)
5629 pml_buf = page_address(vmx->pml_pg);
5630 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5633 gpa = pml_buf[pml_idx];
5634 WARN_ON(gpa & (PAGE_SIZE - 1));
5635 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5638 /* reset PML index */
5639 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5643 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5644 * Called before reporting dirty_bitmap to userspace.
5646 static void kvm_flush_pml_buffers(struct kvm *kvm)
5649 struct kvm_vcpu *vcpu;
5651 * We only need to kick vcpu out of guest mode here, as PML buffer
5652 * is flushed at beginning of all VMEXITs, and it's obvious that only
5653 * vcpus running in guest are possible to have unflushed GPAs in PML
5656 kvm_for_each_vcpu(i, vcpu, kvm)
5657 kvm_vcpu_kick(vcpu);
5660 static void vmx_dump_sel(char *name, uint32_t sel)
5662 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5663 name, vmcs_read16(sel),
5664 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5665 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5666 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5669 static void vmx_dump_dtsel(char *name, uint32_t limit)
5671 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5672 name, vmcs_read32(limit),
5673 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5676 void dump_vmcs(void)
5678 u32 vmentry_ctl, vmexit_ctl;
5679 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5684 if (!dump_invalid_vmcs) {
5685 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5689 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5690 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5691 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5692 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5693 cr4 = vmcs_readl(GUEST_CR4);
5694 efer = vmcs_read64(GUEST_IA32_EFER);
5695 secondary_exec_control = 0;
5696 if (cpu_has_secondary_exec_ctrls())
5697 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5699 pr_err("*** Guest State ***\n");
5700 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5701 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5702 vmcs_readl(CR0_GUEST_HOST_MASK));
5703 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5704 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5705 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5706 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5707 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5709 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5710 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5711 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5712 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5714 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5715 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5716 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5717 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5718 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5719 vmcs_readl(GUEST_SYSENTER_ESP),
5720 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5721 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5722 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5723 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5724 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5725 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5726 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5727 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5728 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5729 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5730 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5731 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5732 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5733 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5734 efer, vmcs_read64(GUEST_IA32_PAT));
5735 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5736 vmcs_read64(GUEST_IA32_DEBUGCTL),
5737 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5738 if (cpu_has_load_perf_global_ctrl() &&
5739 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5740 pr_err("PerfGlobCtl = 0x%016llx\n",
5741 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5742 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5743 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5744 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5745 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5746 vmcs_read32(GUEST_ACTIVITY_STATE));
5747 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5748 pr_err("InterruptStatus = %04x\n",
5749 vmcs_read16(GUEST_INTR_STATUS));
5751 pr_err("*** Host State ***\n");
5752 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5753 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5754 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5755 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5756 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5757 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5758 vmcs_read16(HOST_TR_SELECTOR));
5759 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5760 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5761 vmcs_readl(HOST_TR_BASE));
5762 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5763 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5764 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5765 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5766 vmcs_readl(HOST_CR4));
5767 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5768 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5769 vmcs_read32(HOST_IA32_SYSENTER_CS),
5770 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5771 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5772 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5773 vmcs_read64(HOST_IA32_EFER),
5774 vmcs_read64(HOST_IA32_PAT));
5775 if (cpu_has_load_perf_global_ctrl() &&
5776 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5777 pr_err("PerfGlobCtl = 0x%016llx\n",
5778 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5780 pr_err("*** Control State ***\n");
5781 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5782 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5783 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5784 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5785 vmcs_read32(EXCEPTION_BITMAP),
5786 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5787 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5788 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5789 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5790 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5791 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5792 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5793 vmcs_read32(VM_EXIT_INTR_INFO),
5794 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5795 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5796 pr_err(" reason=%08x qualification=%016lx\n",
5797 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5798 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5799 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5800 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5801 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5802 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5803 pr_err("TSC Multiplier = 0x%016llx\n",
5804 vmcs_read64(TSC_MULTIPLIER));
5805 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5806 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5807 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5808 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5810 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5811 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5812 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5813 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5815 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5816 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5817 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5818 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5819 n = vmcs_read32(CR3_TARGET_COUNT);
5820 for (i = 0; i + 1 < n; i += 4)
5821 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
5822 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
5823 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
5825 pr_err("CR3 target%u=%016lx\n",
5826 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
5827 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5828 pr_err("PLE Gap=%08x Window=%08x\n",
5829 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5830 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5831 pr_err("Virtual processor ID = 0x%04x\n",
5832 vmcs_read16(VIRTUAL_PROCESSOR_ID));
5836 * The guest has exited. See if we can fix it or if we need userspace
5839 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
5841 struct vcpu_vmx *vmx = to_vmx(vcpu);
5842 u32 exit_reason = vmx->exit_reason;
5843 u32 vectoring_info = vmx->idt_vectoring_info;
5845 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
5848 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5849 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5850 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5851 * mode as if vcpus is in root mode, the PML buffer must has been
5855 vmx_flush_pml_buffer(vcpu);
5857 /* If guest state is invalid, start emulating */
5858 if (vmx->emulation_required)
5859 return handle_invalid_guest_state(vcpu);
5861 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
5862 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
5864 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5866 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5867 vcpu->run->fail_entry.hardware_entry_failure_reason
5872 if (unlikely(vmx->fail)) {
5874 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5875 vcpu->run->fail_entry.hardware_entry_failure_reason
5876 = vmcs_read32(VM_INSTRUCTION_ERROR);
5882 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5883 * delivery event since it indicates guest is accessing MMIO.
5884 * The vm-exit can be triggered again after return to guest that
5885 * will cause infinite loop.
5887 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5888 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5889 exit_reason != EXIT_REASON_EPT_VIOLATION &&
5890 exit_reason != EXIT_REASON_PML_FULL &&
5891 exit_reason != EXIT_REASON_TASK_SWITCH)) {
5892 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5893 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
5894 vcpu->run->internal.ndata = 3;
5895 vcpu->run->internal.data[0] = vectoring_info;
5896 vcpu->run->internal.data[1] = exit_reason;
5897 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
5898 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
5899 vcpu->run->internal.ndata++;
5900 vcpu->run->internal.data[3] =
5901 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5906 if (unlikely(!enable_vnmi &&
5907 vmx->loaded_vmcs->soft_vnmi_blocked)) {
5908 if (vmx_interrupt_allowed(vcpu)) {
5909 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5910 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
5911 vcpu->arch.nmi_pending) {
5913 * This CPU don't support us in finding the end of an
5914 * NMI-blocked window if the guest runs with IRQs
5915 * disabled. So we pull the trigger after 1 s of
5916 * futile waiting, but inform the user about this.
5918 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
5919 "state on VCPU %d after 1 s timeout\n",
5920 __func__, vcpu->vcpu_id);
5921 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5925 if (exit_reason < kvm_vmx_max_exit_handlers
5926 && kvm_vmx_exit_handlers[exit_reason])
5927 return kvm_vmx_exit_handlers[exit_reason](vcpu);
5929 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
5932 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5933 vcpu->run->internal.suberror =
5934 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
5935 vcpu->run->internal.ndata = 1;
5936 vcpu->run->internal.data[0] = exit_reason;
5942 * Software based L1D cache flush which is used when microcode providing
5943 * the cache control MSR is not loaded.
5945 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
5946 * flush it is required to read in 64 KiB because the replacement algorithm
5947 * is not exactly LRU. This could be sized at runtime via topology
5948 * information but as all relevant affected CPUs have 32KiB L1D cache size
5949 * there is no point in doing so.
5951 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
5953 int size = PAGE_SIZE << L1D_CACHE_ORDER;
5956 * This code is only executed when the the flush mode is 'cond' or
5959 if (static_branch_likely(&vmx_l1d_flush_cond)) {
5963 * Clear the per-vcpu flush bit, it gets set again
5964 * either from vcpu_run() or from one of the unsafe
5967 flush_l1d = vcpu->arch.l1tf_flush_l1d;
5968 vcpu->arch.l1tf_flush_l1d = false;
5971 * Clear the per-cpu flush bit, it gets set again from
5972 * the interrupt handlers.
5974 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
5975 kvm_clear_cpu_l1tf_flush_l1d();
5981 vcpu->stat.l1d_flush++;
5983 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
5984 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
5989 /* First ensure the pages are in the TLB */
5990 "xorl %%eax, %%eax\n"
5991 ".Lpopulate_tlb:\n\t"
5992 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5993 "addl $4096, %%eax\n\t"
5994 "cmpl %%eax, %[size]\n\t"
5995 "jne .Lpopulate_tlb\n\t"
5996 "xorl %%eax, %%eax\n\t"
5998 /* Now fill the cache */
5999 "xorl %%eax, %%eax\n"
6001 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6002 "addl $64, %%eax\n\t"
6003 "cmpl %%eax, %[size]\n\t"
6004 "jne .Lfill_cache\n\t"
6006 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6008 : "eax", "ebx", "ecx", "edx");
6011 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6013 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6015 if (is_guest_mode(vcpu) &&
6016 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6019 if (irr == -1 || tpr < irr) {
6020 vmcs_write32(TPR_THRESHOLD, 0);
6024 vmcs_write32(TPR_THRESHOLD, irr);
6027 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6029 struct vcpu_vmx *vmx = to_vmx(vcpu);
6030 u32 sec_exec_control;
6032 if (!lapic_in_kernel(vcpu))
6035 if (!flexpriority_enabled &&
6036 !cpu_has_vmx_virtualize_x2apic_mode())
6039 /* Postpone execution until vmcs01 is the current VMCS. */
6040 if (is_guest_mode(vcpu)) {
6041 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6045 sec_exec_control = secondary_exec_controls_get(vmx);
6046 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6047 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6049 switch (kvm_get_apic_mode(vcpu)) {
6050 case LAPIC_MODE_INVALID:
6051 WARN_ONCE(true, "Invalid local APIC state");
6052 case LAPIC_MODE_DISABLED:
6054 case LAPIC_MODE_XAPIC:
6055 if (flexpriority_enabled) {
6057 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6058 vmx_flush_tlb(vcpu, true);
6061 case LAPIC_MODE_X2APIC:
6062 if (cpu_has_vmx_virtualize_x2apic_mode())
6064 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6067 secondary_exec_controls_set(vmx, sec_exec_control);
6069 vmx_update_msr_bitmap(vcpu);
6072 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
6074 if (!is_guest_mode(vcpu)) {
6075 vmcs_write64(APIC_ACCESS_ADDR, hpa);
6076 vmx_flush_tlb(vcpu, true);
6080 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6088 status = vmcs_read16(GUEST_INTR_STATUS);
6090 if (max_isr != old) {
6092 status |= max_isr << 8;
6093 vmcs_write16(GUEST_INTR_STATUS, status);
6097 static void vmx_set_rvi(int vector)
6105 status = vmcs_read16(GUEST_INTR_STATUS);
6106 old = (u8)status & 0xff;
6107 if ((u8)vector != old) {
6109 status |= (u8)vector;
6110 vmcs_write16(GUEST_INTR_STATUS, status);
6114 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6117 * When running L2, updating RVI is only relevant when
6118 * vmcs12 virtual-interrupt-delivery enabled.
6119 * However, it can be enabled only when L1 also
6120 * intercepts external-interrupts and in that case
6121 * we should not update vmcs02 RVI but instead intercept
6122 * interrupt. Therefore, do nothing when running L2.
6124 if (!is_guest_mode(vcpu))
6125 vmx_set_rvi(max_irr);
6128 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6130 struct vcpu_vmx *vmx = to_vmx(vcpu);
6132 bool max_irr_updated;
6134 WARN_ON(!vcpu->arch.apicv_active);
6135 if (pi_test_on(&vmx->pi_desc)) {
6136 pi_clear_on(&vmx->pi_desc);
6138 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6139 * But on x86 this is just a compiler barrier anyway.
6141 smp_mb__after_atomic();
6143 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6146 * If we are running L2 and L1 has a new pending interrupt
6147 * which can be injected, we should re-evaluate
6148 * what should be done with this new L1 interrupt.
6149 * If L1 intercepts external-interrupts, we should
6150 * exit from L2 to L1. Otherwise, interrupt should be
6151 * delivered directly to L2.
6153 if (is_guest_mode(vcpu) && max_irr_updated) {
6154 if (nested_exit_on_intr(vcpu))
6155 kvm_vcpu_exiting_guest_mode(vcpu);
6157 kvm_make_request(KVM_REQ_EVENT, vcpu);
6160 max_irr = kvm_lapic_find_highest_irr(vcpu);
6162 vmx_hwapic_irr_update(vcpu, max_irr);
6166 static bool vmx_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
6168 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6170 return pi_test_on(pi_desc) ||
6171 (pi_test_sn(pi_desc) && !pi_is_pir_empty(pi_desc));
6174 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6176 if (!kvm_vcpu_apicv_active(vcpu))
6179 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6180 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6181 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6182 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6185 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6187 struct vcpu_vmx *vmx = to_vmx(vcpu);
6189 pi_clear_on(&vmx->pi_desc);
6190 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6193 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6195 vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6197 /* if exit due to PF check for async PF */
6198 if (is_page_fault(vmx->exit_intr_info))
6199 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
6201 /* Handle machine checks before interrupts are enabled */
6202 if (is_machine_check(vmx->exit_intr_info))
6203 kvm_machine_check();
6205 /* We need to handle NMIs before interrupts are enabled */
6206 if (is_nmi(vmx->exit_intr_info)) {
6207 kvm_before_interrupt(&vmx->vcpu);
6209 kvm_after_interrupt(&vmx->vcpu);
6213 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6215 unsigned int vector;
6216 unsigned long entry;
6217 #ifdef CONFIG_X86_64
6223 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6224 if (WARN_ONCE(!is_external_intr(intr_info),
6225 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6228 vector = intr_info & INTR_INFO_VECTOR_MASK;
6229 desc = (gate_desc *)host_idt_base + vector;
6230 entry = gate_offset(desc);
6232 kvm_before_interrupt(vcpu);
6235 #ifdef CONFIG_X86_64
6236 "mov %%" _ASM_SP ", %[sp]\n\t"
6237 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
6242 __ASM_SIZE(push) " $%c[cs]\n\t"
6245 #ifdef CONFIG_X86_64
6250 THUNK_TARGET(entry),
6251 [ss]"i"(__KERNEL_DS),
6252 [cs]"i"(__KERNEL_CS)
6255 kvm_after_interrupt(vcpu);
6257 STACK_FRAME_NON_STANDARD(handle_external_interrupt_irqoff);
6259 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6261 struct vcpu_vmx *vmx = to_vmx(vcpu);
6263 if (vmx->exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6264 handle_external_interrupt_irqoff(vcpu);
6265 else if (vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)
6266 handle_exception_nmi_irqoff(vmx);
6269 static bool vmx_has_emulated_msr(int index)
6272 case MSR_IA32_SMBASE:
6274 * We cannot do SMM unless we can run the guest in big
6277 return enable_unrestricted_guest || emulate_invalid_guest_state;
6278 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6280 case MSR_AMD64_VIRT_SPEC_CTRL:
6281 /* This is AMD only. */
6288 static bool vmx_pt_supported(void)
6290 return pt_mode == PT_MODE_HOST_GUEST;
6293 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6298 bool idtv_info_valid;
6300 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6303 if (vmx->loaded_vmcs->nmi_known_unmasked)
6306 * Can't use vmx->exit_intr_info since we're not sure what
6307 * the exit reason is.
6309 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6310 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6311 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6313 * SDM 3: 27.7.1.2 (September 2008)
6314 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6315 * a guest IRET fault.
6316 * SDM 3: 23.2.2 (September 2008)
6317 * Bit 12 is undefined in any of the following cases:
6318 * If the VM exit sets the valid bit in the IDT-vectoring
6319 * information field.
6320 * If the VM exit is due to a double fault.
6322 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6323 vector != DF_VECTOR && !idtv_info_valid)
6324 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6325 GUEST_INTR_STATE_NMI);
6327 vmx->loaded_vmcs->nmi_known_unmasked =
6328 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6329 & GUEST_INTR_STATE_NMI);
6330 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6331 vmx->loaded_vmcs->vnmi_blocked_time +=
6332 ktime_to_ns(ktime_sub(ktime_get(),
6333 vmx->loaded_vmcs->entry_time));
6336 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6337 u32 idt_vectoring_info,
6338 int instr_len_field,
6339 int error_code_field)
6343 bool idtv_info_valid;
6345 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6347 vcpu->arch.nmi_injected = false;
6348 kvm_clear_exception_queue(vcpu);
6349 kvm_clear_interrupt_queue(vcpu);
6351 if (!idtv_info_valid)
6354 kvm_make_request(KVM_REQ_EVENT, vcpu);
6356 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6357 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6360 case INTR_TYPE_NMI_INTR:
6361 vcpu->arch.nmi_injected = true;
6363 * SDM 3: 27.7.1.2 (September 2008)
6364 * Clear bit "block by NMI" before VM entry if a NMI
6367 vmx_set_nmi_mask(vcpu, false);
6369 case INTR_TYPE_SOFT_EXCEPTION:
6370 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6372 case INTR_TYPE_HARD_EXCEPTION:
6373 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6374 u32 err = vmcs_read32(error_code_field);
6375 kvm_requeue_exception_e(vcpu, vector, err);
6377 kvm_requeue_exception(vcpu, vector);
6379 case INTR_TYPE_SOFT_INTR:
6380 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6382 case INTR_TYPE_EXT_INTR:
6383 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6390 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6392 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6393 VM_EXIT_INSTRUCTION_LEN,
6394 IDT_VECTORING_ERROR_CODE);
6397 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6399 __vmx_complete_interrupts(vcpu,
6400 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6401 VM_ENTRY_INSTRUCTION_LEN,
6402 VM_ENTRY_EXCEPTION_ERROR_CODE);
6404 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6407 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6410 struct perf_guest_switch_msr *msrs;
6412 msrs = perf_guest_get_msrs(&nr_msrs);
6417 for (i = 0; i < nr_msrs; i++)
6418 if (msrs[i].host == msrs[i].guest)
6419 clear_atomic_switch_msr(vmx, msrs[i].msr);
6421 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6422 msrs[i].host, false);
6425 static void atomic_switch_umwait_control_msr(struct vcpu_vmx *vmx)
6427 u32 host_umwait_control;
6429 if (!vmx_has_waitpkg(vmx))
6432 host_umwait_control = get_umwait_control_msr();
6434 if (vmx->msr_ia32_umwait_control != host_umwait_control)
6435 add_atomic_switch_msr(vmx, MSR_IA32_UMWAIT_CONTROL,
6436 vmx->msr_ia32_umwait_control,
6437 host_umwait_control, false);
6439 clear_atomic_switch_msr(vmx, MSR_IA32_UMWAIT_CONTROL);
6442 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6444 struct vcpu_vmx *vmx = to_vmx(vcpu);
6448 if (vmx->req_immediate_exit) {
6449 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6450 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6451 } else if (vmx->hv_deadline_tsc != -1) {
6453 if (vmx->hv_deadline_tsc > tscl)
6454 /* set_hv_timer ensures the delta fits in 32-bits */
6455 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6456 cpu_preemption_timer_multi);
6460 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6461 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6462 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6463 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6464 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6468 void vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6470 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6471 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6472 vmcs_writel(HOST_RSP, host_rsp);
6476 bool __vmx_vcpu_run(struct vcpu_vmx *vmx, unsigned long *regs, bool launched);
6478 static void vmx_vcpu_run(struct kvm_vcpu *vcpu)
6480 struct vcpu_vmx *vmx = to_vmx(vcpu);
6481 unsigned long cr3, cr4;
6483 /* Record the guest's net vcpu time for enforced NMI injections. */
6484 if (unlikely(!enable_vnmi &&
6485 vmx->loaded_vmcs->soft_vnmi_blocked))
6486 vmx->loaded_vmcs->entry_time = ktime_get();
6488 /* Don't enter VMX if guest state is invalid, let the exit handler
6489 start emulation until we arrive back to a valid state */
6490 if (vmx->emulation_required)
6493 if (vmx->ple_window_dirty) {
6494 vmx->ple_window_dirty = false;
6495 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6498 if (vmx->nested.need_vmcs12_to_shadow_sync)
6499 nested_sync_vmcs12_to_shadow(vcpu);
6501 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
6502 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6503 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
6504 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6506 cr3 = __get_current_cr3_fast();
6507 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6508 vmcs_writel(HOST_CR3, cr3);
6509 vmx->loaded_vmcs->host_state.cr3 = cr3;
6512 cr4 = cr4_read_shadow();
6513 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6514 vmcs_writel(HOST_CR4, cr4);
6515 vmx->loaded_vmcs->host_state.cr4 = cr4;
6518 /* When single-stepping over STI and MOV SS, we must clear the
6519 * corresponding interruptibility bits in the guest state. Otherwise
6520 * vmentry fails as it then expects bit 14 (BS) in pending debug
6521 * exceptions being set, but that's not correct for the guest debugging
6523 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6524 vmx_set_interrupt_shadow(vcpu, 0);
6526 kvm_load_guest_xcr0(vcpu);
6528 if (static_cpu_has(X86_FEATURE_PKU) &&
6529 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
6530 vcpu->arch.pkru != vmx->host_pkru)
6531 __write_pkru(vcpu->arch.pkru);
6533 pt_guest_enter(vmx);
6535 atomic_switch_perf_msrs(vmx);
6536 atomic_switch_umwait_control_msr(vmx);
6538 if (enable_preemption_timer)
6539 vmx_update_hv_timer(vcpu);
6541 if (lapic_in_kernel(vcpu) &&
6542 vcpu->arch.apic->lapic_timer.timer_advance_ns)
6543 kvm_wait_lapic_expire(vcpu);
6546 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6547 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6548 * is no need to worry about the conditional branch over the wrmsr
6549 * being speculatively taken.
6551 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6553 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6554 if (static_branch_unlikely(&vmx_l1d_should_flush))
6555 vmx_l1d_flush(vcpu);
6556 else if (static_branch_unlikely(&mds_user_clear))
6557 mds_clear_cpu_buffers();
6559 if (vcpu->arch.cr2 != read_cr2())
6560 write_cr2(vcpu->arch.cr2);
6562 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6563 vmx->loaded_vmcs->launched);
6565 vcpu->arch.cr2 = read_cr2();
6568 * We do not use IBRS in the kernel. If this vCPU has used the
6569 * SPEC_CTRL MSR it may have left it on; save the value and
6570 * turn it off. This is much more efficient than blindly adding
6571 * it to the atomic save/restore list. Especially as the former
6572 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6574 * For non-nested case:
6575 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6579 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6582 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6583 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6585 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6587 /* All fields are clean at this point */
6588 if (static_branch_unlikely(&enable_evmcs))
6589 current_evmcs->hv_clean_fields |=
6590 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6592 if (static_branch_unlikely(&enable_evmcs))
6593 current_evmcs->hv_vp_id = vcpu->arch.hyperv.vp_index;
6595 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6596 if (vmx->host_debugctlmsr)
6597 update_debugctlmsr(vmx->host_debugctlmsr);
6599 #ifndef CONFIG_X86_64
6601 * The sysexit path does not restore ds/es, so we must set them to
6602 * a reasonable value ourselves.
6604 * We can't defer this to vmx_prepare_switch_to_host() since that
6605 * function may be executed in interrupt context, which saves and
6606 * restore segments around it, nullifying its effect.
6608 loadsegment(ds, __USER_DS);
6609 loadsegment(es, __USER_DS);
6612 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
6613 | (1 << VCPU_EXREG_RFLAGS)
6614 | (1 << VCPU_EXREG_PDPTR)
6615 | (1 << VCPU_EXREG_SEGMENTS)
6616 | (1 << VCPU_EXREG_CR3));
6617 vcpu->arch.regs_dirty = 0;
6622 * eager fpu is enabled if PKEY is supported and CR4 is switched
6623 * back on host, so it is safe to read guest PKRU from current
6626 if (static_cpu_has(X86_FEATURE_PKU) &&
6627 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
6628 vcpu->arch.pkru = rdpkru();
6629 if (vcpu->arch.pkru != vmx->host_pkru)
6630 __write_pkru(vmx->host_pkru);
6633 kvm_put_guest_xcr0(vcpu);
6635 vmx->nested.nested_run_pending = 0;
6636 vmx->idt_vectoring_info = 0;
6638 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
6639 if ((u16)vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY)
6640 kvm_machine_check();
6642 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6645 vmx->loaded_vmcs->launched = 1;
6646 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6648 vmx_recover_nmi_blocking(vmx);
6649 vmx_complete_interrupts(vmx);
6652 static struct kvm *vmx_vm_alloc(void)
6654 struct kvm_vmx *kvm_vmx = __vmalloc(sizeof(struct kvm_vmx),
6655 GFP_KERNEL_ACCOUNT | __GFP_ZERO,
6657 return &kvm_vmx->kvm;
6660 static void vmx_vm_free(struct kvm *kvm)
6662 kfree(kvm->arch.hyperv.hv_pa_pg);
6663 vfree(to_kvm_vmx(kvm));
6666 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6668 struct vcpu_vmx *vmx = to_vmx(vcpu);
6671 vmx_destroy_pml_buffer(vmx);
6672 free_vpid(vmx->vpid);
6673 nested_vmx_free_vcpu(vcpu);
6674 free_loaded_vmcs(vmx->loaded_vmcs);
6675 kfree(vmx->guest_msrs);
6676 kvm_vcpu_uninit(vcpu);
6677 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.user_fpu);
6678 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6679 kmem_cache_free(kvm_vcpu_cache, vmx);
6682 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
6685 struct vcpu_vmx *vmx;
6686 unsigned long *msr_bitmap;
6689 BUILD_BUG_ON_MSG(offsetof(struct vcpu_vmx, vcpu) != 0,
6690 "struct kvm_vcpu must be at offset 0 for arch usercopy region");
6692 vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
6694 return ERR_PTR(-ENOMEM);
6696 vmx->vcpu.arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
6697 GFP_KERNEL_ACCOUNT);
6698 if (!vmx->vcpu.arch.user_fpu) {
6699 printk(KERN_ERR "kvm: failed to allocate kvm userspace's fpu\n");
6701 goto free_partial_vcpu;
6704 vmx->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
6705 GFP_KERNEL_ACCOUNT);
6706 if (!vmx->vcpu.arch.guest_fpu) {
6707 printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
6712 vmx->vpid = allocate_vpid();
6714 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
6721 * If PML is turned on, failure on enabling PML just results in failure
6722 * of creating the vcpu, therefore we can simplify PML logic (by
6723 * avoiding dealing with cases, such as enabling PML partially on vcpus
6724 * for the guest, etc.
6727 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6732 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
6733 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
6736 if (!vmx->guest_msrs)
6739 err = alloc_loaded_vmcs(&vmx->vmcs01);
6743 msr_bitmap = vmx->vmcs01.msr_bitmap;
6744 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6745 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6746 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6747 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6748 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6749 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6750 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6751 if (kvm_cstate_in_guest(kvm)) {
6752 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C1_RES, MSR_TYPE_R);
6753 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6754 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6755 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6757 vmx->msr_bitmap_mode = 0;
6759 vmx->loaded_vmcs = &vmx->vmcs01;
6761 vmx_vcpu_load(&vmx->vcpu, cpu);
6762 vmx->vcpu.cpu = cpu;
6763 vmx_vcpu_setup(vmx);
6764 vmx_vcpu_put(&vmx->vcpu);
6766 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
6767 err = alloc_apic_access_page(kvm);
6772 if (enable_ept && !enable_unrestricted_guest) {
6773 err = init_rmode_identity_map(kvm);
6779 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
6780 vmx_capability.ept);
6782 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6784 vmx->nested.posted_intr_nv = -1;
6785 vmx->nested.current_vmptr = -1ull;
6787 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
6790 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6791 * or POSTED_INTR_WAKEUP_VECTOR.
6793 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6794 vmx->pi_desc.sn = 1;
6796 vmx->ept_pointer = INVALID_PAGE;
6801 free_loaded_vmcs(vmx->loaded_vmcs);
6803 kfree(vmx->guest_msrs);
6805 vmx_destroy_pml_buffer(vmx);
6807 kvm_vcpu_uninit(&vmx->vcpu);
6809 free_vpid(vmx->vpid);
6810 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
6812 kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.user_fpu);
6814 kmem_cache_free(kvm_vcpu_cache, vmx);
6815 return ERR_PTR(err);
6818 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
6819 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
6821 static int vmx_vm_init(struct kvm *kvm)
6823 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
6826 kvm->arch.pause_in_guest = true;
6828 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6829 switch (l1tf_mitigation) {
6830 case L1TF_MITIGATION_OFF:
6831 case L1TF_MITIGATION_FLUSH_NOWARN:
6832 /* 'I explicitly don't care' is set */
6834 case L1TF_MITIGATION_FLUSH:
6835 case L1TF_MITIGATION_FLUSH_NOSMT:
6836 case L1TF_MITIGATION_FULL:
6838 * Warn upon starting the first VM in a potentially
6839 * insecure environment.
6841 if (sched_smt_active())
6842 pr_warn_once(L1TF_MSG_SMT);
6843 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6844 pr_warn_once(L1TF_MSG_L1D);
6846 case L1TF_MITIGATION_FULL_FORCE:
6847 /* Flush is enforced */
6854 static int __init vmx_check_processor_compat(void)
6856 struct vmcs_config vmcs_conf;
6857 struct vmx_capability vmx_cap;
6859 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
6862 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
6863 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
6864 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
6865 smp_processor_id());
6871 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6876 /* For VT-d and EPT combination
6877 * 1. MMIO: always map as UC
6879 * a. VT-d without snooping control feature: can't guarantee the
6880 * result, try to trust guest.
6881 * b. VT-d with snooping control feature: snooping control feature of
6882 * VT-d engine can guarantee the cache correctness. Just set it
6883 * to WB to keep consistent with host. So the same as item 3.
6884 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
6885 * consistent with host MTRR
6888 cache = MTRR_TYPE_UNCACHABLE;
6892 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
6893 ipat = VMX_EPT_IPAT_BIT;
6894 cache = MTRR_TYPE_WRBACK;
6898 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
6899 ipat = VMX_EPT_IPAT_BIT;
6900 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
6901 cache = MTRR_TYPE_WRBACK;
6903 cache = MTRR_TYPE_UNCACHABLE;
6907 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
6910 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
6913 static int vmx_get_lpage_level(void)
6915 if (enable_ept && !cpu_has_vmx_ept_1g_page())
6916 return PT_DIRECTORY_LEVEL;
6918 /* For shadow and EPT supported 1GB page */
6919 return PT_PDPE_LEVEL;
6922 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
6925 * These bits in the secondary execution controls field
6926 * are dynamic, the others are mostly based on the hypervisor
6927 * architecture and the guest's CPUID. Do not touch the
6931 SECONDARY_EXEC_SHADOW_VMCS |
6932 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
6933 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6934 SECONDARY_EXEC_DESC;
6936 u32 new_ctl = vmx->secondary_exec_control;
6937 u32 cur_ctl = secondary_exec_controls_get(vmx);
6939 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
6943 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
6944 * (indicating "allowed-1") if they are supported in the guest's CPUID.
6946 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
6948 struct vcpu_vmx *vmx = to_vmx(vcpu);
6949 struct kvm_cpuid_entry2 *entry;
6951 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
6952 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
6954 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
6955 if (entry && (entry->_reg & (_cpuid_mask))) \
6956 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
6959 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
6960 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
6961 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
6962 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
6963 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
6964 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
6965 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
6966 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
6967 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
6968 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
6969 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
6970 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
6971 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
6972 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
6973 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
6975 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
6976 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
6977 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
6978 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
6979 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
6980 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
6982 #undef cr4_fixed1_update
6985 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
6987 struct vcpu_vmx *vmx = to_vmx(vcpu);
6989 if (kvm_mpx_supported()) {
6990 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
6993 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
6994 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
6996 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
6997 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7002 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7004 struct vcpu_vmx *vmx = to_vmx(vcpu);
7005 struct kvm_cpuid_entry2 *best = NULL;
7008 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7009 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7012 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7013 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7014 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7015 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7018 /* Get the number of configurable Address Ranges for filtering */
7019 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7020 PT_CAP_num_address_ranges);
7022 /* Initialize and clear the no dependency bits */
7023 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7024 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7027 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7028 * will inject an #GP
7030 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7031 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7034 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7035 * PSBFreq can be set
7037 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7038 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7039 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7042 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7043 * MTCFreq can be set
7045 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7046 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7047 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7049 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7050 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7051 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7054 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7055 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7056 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7058 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7059 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7060 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7062 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
7063 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7064 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7066 /* unmask address range configure area */
7067 for (i = 0; i < vmx->pt_desc.addr_range; i++)
7068 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7071 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
7073 struct vcpu_vmx *vmx = to_vmx(vcpu);
7075 if (cpu_has_secondary_exec_ctrls()) {
7076 vmx_compute_secondary_exec_control(vmx);
7077 vmcs_set_secondary_exec_control(vmx);
7080 if (nested_vmx_allowed(vcpu))
7081 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7082 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7084 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7085 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7087 if (nested_vmx_allowed(vcpu)) {
7088 nested_vmx_cr_fixed1_bits_update(vcpu);
7089 nested_vmx_entry_exit_ctls_update(vcpu);
7092 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7093 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7094 update_intel_pt_cfg(vcpu);
7097 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
7099 if (func == 1 && nested)
7100 entry->ecx |= bit(X86_FEATURE_VMX);
7103 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7105 to_vmx(vcpu)->req_immediate_exit = true;
7108 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7109 struct x86_instruction_info *info)
7111 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7112 unsigned short port;
7116 if (info->intercept == x86_intercept_in ||
7117 info->intercept == x86_intercept_ins) {
7118 port = info->src_val;
7119 size = info->dst_bytes;
7121 port = info->dst_val;
7122 size = info->src_bytes;
7126 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7127 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7130 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7132 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7133 intercept = nested_cpu_has(vmcs12,
7134 CPU_BASED_UNCOND_IO_EXITING);
7136 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7138 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7139 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7142 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7143 struct x86_instruction_info *info,
7144 enum x86_intercept_stage stage)
7146 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7147 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
7149 switch (info->intercept) {
7151 * RDPID causes #UD if disabled through secondary execution controls.
7152 * Because it is marked as EmulateOnUD, we need to intercept it here.
7154 case x86_intercept_rdtscp:
7155 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
7156 ctxt->exception.vector = UD_VECTOR;
7157 ctxt->exception.error_code_valid = false;
7158 return X86EMUL_PROPAGATE_FAULT;
7162 case x86_intercept_in:
7163 case x86_intercept_ins:
7164 case x86_intercept_out:
7165 case x86_intercept_outs:
7166 return vmx_check_intercept_io(vcpu, info);
7168 case x86_intercept_lgdt:
7169 case x86_intercept_lidt:
7170 case x86_intercept_lldt:
7171 case x86_intercept_ltr:
7172 case x86_intercept_sgdt:
7173 case x86_intercept_sidt:
7174 case x86_intercept_sldt:
7175 case x86_intercept_str:
7176 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7177 return X86EMUL_CONTINUE;
7179 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7182 /* TODO: check more intercepts... */
7187 return X86EMUL_UNHANDLEABLE;
7190 #ifdef CONFIG_X86_64
7191 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7192 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7193 u64 divisor, u64 *result)
7195 u64 low = a << shift, high = a >> (64 - shift);
7197 /* To avoid the overflow on divq */
7198 if (high >= divisor)
7201 /* Low hold the result, high hold rem which is discarded */
7202 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7203 "rm" (divisor), "0" (low), "1" (high));
7209 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7212 struct vcpu_vmx *vmx;
7213 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7214 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7216 if (kvm_mwait_in_guest(vcpu->kvm) ||
7217 kvm_can_post_timer_interrupt(vcpu))
7222 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7223 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7224 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7225 ktimer->timer_advance_ns);
7227 if (delta_tsc > lapic_timer_advance_cycles)
7228 delta_tsc -= lapic_timer_advance_cycles;
7232 /* Convert to host delta tsc if tsc scaling is enabled */
7233 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7234 delta_tsc && u64_shl_div_u64(delta_tsc,
7235 kvm_tsc_scaling_ratio_frac_bits,
7236 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7240 * If the delta tsc can't fit in the 32 bit after the multi shift,
7241 * we can't use the preemption timer.
7242 * It's possible that it fits on later vmentries, but checking
7243 * on every vmentry is costly so we just use an hrtimer.
7245 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7248 vmx->hv_deadline_tsc = tscl + delta_tsc;
7249 *expired = !delta_tsc;
7253 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7255 to_vmx(vcpu)->hv_deadline_tsc = -1;
7259 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7261 if (!kvm_pause_in_guest(vcpu->kvm))
7262 shrink_ple_window(vcpu);
7265 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7266 struct kvm_memory_slot *slot)
7268 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7269 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7272 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7273 struct kvm_memory_slot *slot)
7275 kvm_mmu_slot_set_dirty(kvm, slot);
7278 static void vmx_flush_log_dirty(struct kvm *kvm)
7280 kvm_flush_pml_buffers(kvm);
7283 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
7285 struct vmcs12 *vmcs12;
7286 struct vcpu_vmx *vmx = to_vmx(vcpu);
7289 if (is_guest_mode(vcpu)) {
7290 WARN_ON_ONCE(vmx->nested.pml_full);
7293 * Check if PML is enabled for the nested guest.
7294 * Whether eptp bit 6 is set is already checked
7295 * as part of A/D emulation.
7297 vmcs12 = get_vmcs12(vcpu);
7298 if (!nested_cpu_has_pml(vmcs12))
7301 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
7302 vmx->nested.pml_full = true;
7306 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
7307 dst = vmcs12->pml_address + sizeof(u64) * vmcs12->guest_pml_index;
7309 if (kvm_write_guest_page(vcpu->kvm, gpa_to_gfn(dst), &gpa,
7310 offset_in_page(dst), sizeof(gpa)))
7313 vmcs12->guest_pml_index--;
7319 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7320 struct kvm_memory_slot *memslot,
7321 gfn_t offset, unsigned long mask)
7323 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7326 static void __pi_post_block(struct kvm_vcpu *vcpu)
7328 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7329 struct pi_desc old, new;
7333 old.control = new.control = pi_desc->control;
7334 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
7335 "Wakeup handler not enabled while the VCPU is blocked\n");
7337 dest = cpu_physical_id(vcpu->cpu);
7339 if (x2apic_enabled())
7342 new.ndst = (dest << 8) & 0xFF00;
7344 /* set 'NV' to 'notification vector' */
7345 new.nv = POSTED_INTR_VECTOR;
7346 } while (cmpxchg64(&pi_desc->control, old.control,
7347 new.control) != old.control);
7349 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
7350 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7351 list_del(&vcpu->blocked_vcpu_list);
7352 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7353 vcpu->pre_pcpu = -1;
7358 * This routine does the following things for vCPU which is going
7359 * to be blocked if VT-d PI is enabled.
7360 * - Store the vCPU to the wakeup list, so when interrupts happen
7361 * we can find the right vCPU to wake up.
7362 * - Change the Posted-interrupt descriptor as below:
7363 * 'NDST' <-- vcpu->pre_pcpu
7364 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
7365 * - If 'ON' is set during this process, which means at least one
7366 * interrupt is posted for this vCPU, we cannot block it, in
7367 * this case, return 1, otherwise, return 0.
7370 static int pi_pre_block(struct kvm_vcpu *vcpu)
7373 struct pi_desc old, new;
7374 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7376 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
7377 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7378 !kvm_vcpu_apicv_active(vcpu))
7381 WARN_ON(irqs_disabled());
7382 local_irq_disable();
7383 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
7384 vcpu->pre_pcpu = vcpu->cpu;
7385 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7386 list_add_tail(&vcpu->blocked_vcpu_list,
7387 &per_cpu(blocked_vcpu_on_cpu,
7389 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7393 old.control = new.control = pi_desc->control;
7395 WARN((pi_desc->sn == 1),
7396 "Warning: SN field of posted-interrupts "
7397 "is set before blocking\n");
7400 * Since vCPU can be preempted during this process,
7401 * vcpu->cpu could be different with pre_pcpu, we
7402 * need to set pre_pcpu as the destination of wakeup
7403 * notification event, then we can find the right vCPU
7404 * to wakeup in wakeup handler if interrupts happen
7405 * when the vCPU is in blocked state.
7407 dest = cpu_physical_id(vcpu->pre_pcpu);
7409 if (x2apic_enabled())
7412 new.ndst = (dest << 8) & 0xFF00;
7414 /* set 'NV' to 'wakeup vector' */
7415 new.nv = POSTED_INTR_WAKEUP_VECTOR;
7416 } while (cmpxchg64(&pi_desc->control, old.control,
7417 new.control) != old.control);
7419 /* We should not block the vCPU if an interrupt is posted for it. */
7420 if (pi_test_on(pi_desc) == 1)
7421 __pi_post_block(vcpu);
7424 return (vcpu->pre_pcpu == -1);
7427 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7429 if (pi_pre_block(vcpu))
7432 if (kvm_lapic_hv_timer_in_use(vcpu))
7433 kvm_lapic_switch_to_sw_timer(vcpu);
7438 static void pi_post_block(struct kvm_vcpu *vcpu)
7440 if (vcpu->pre_pcpu == -1)
7443 WARN_ON(irqs_disabled());
7444 local_irq_disable();
7445 __pi_post_block(vcpu);
7449 static void vmx_post_block(struct kvm_vcpu *vcpu)
7451 if (kvm_x86_ops->set_hv_timer)
7452 kvm_lapic_switch_to_hv_timer(vcpu);
7454 pi_post_block(vcpu);
7458 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
7461 * @host_irq: host irq of the interrupt
7462 * @guest_irq: gsi of the interrupt
7463 * @set: set or unset PI
7464 * returns 0 on success, < 0 on failure
7466 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7467 uint32_t guest_irq, bool set)
7469 struct kvm_kernel_irq_routing_entry *e;
7470 struct kvm_irq_routing_table *irq_rt;
7471 struct kvm_lapic_irq irq;
7472 struct kvm_vcpu *vcpu;
7473 struct vcpu_data vcpu_info;
7476 if (!kvm_arch_has_assigned_device(kvm) ||
7477 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7478 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7481 idx = srcu_read_lock(&kvm->irq_srcu);
7482 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7483 if (guest_irq >= irq_rt->nr_rt_entries ||
7484 hlist_empty(&irq_rt->map[guest_irq])) {
7485 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7486 guest_irq, irq_rt->nr_rt_entries);
7490 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7491 if (e->type != KVM_IRQ_ROUTING_MSI)
7494 * VT-d PI cannot support posting multicast/broadcast
7495 * interrupts to a vCPU, we still use interrupt remapping
7496 * for these kind of interrupts.
7498 * For lowest-priority interrupts, we only support
7499 * those with single CPU as the destination, e.g. user
7500 * configures the interrupts via /proc/irq or uses
7501 * irqbalance to make the interrupts single-CPU.
7503 * We will support full lowest-priority interrupt later.
7505 * In addition, we can only inject generic interrupts using
7506 * the PI mechanism, refuse to route others through it.
7509 kvm_set_msi_irq(kvm, e, &irq);
7510 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
7511 !kvm_irq_is_postable(&irq)) {
7513 * Make sure the IRTE is in remapped mode if
7514 * we don't handle it in posted mode.
7516 ret = irq_set_vcpu_affinity(host_irq, NULL);
7519 "failed to back to remapped mode, irq: %u\n",
7527 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7528 vcpu_info.vector = irq.vector;
7530 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7531 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7534 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7536 ret = irq_set_vcpu_affinity(host_irq, NULL);
7539 printk(KERN_INFO "%s: failed to update PI IRTE\n",
7547 srcu_read_unlock(&kvm->irq_srcu, idx);
7551 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7553 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7554 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7555 FEATURE_CONTROL_LMCE;
7557 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7558 ~FEATURE_CONTROL_LMCE;
7561 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
7563 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7564 if (to_vmx(vcpu)->nested.nested_run_pending)
7569 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7571 struct vcpu_vmx *vmx = to_vmx(vcpu);
7573 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7574 if (vmx->nested.smm.guest_mode)
7575 nested_vmx_vmexit(vcpu, -1, 0, 0);
7577 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7578 vmx->nested.vmxon = false;
7579 vmx_clear_hlt(vcpu);
7583 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7585 struct vcpu_vmx *vmx = to_vmx(vcpu);
7588 if (vmx->nested.smm.vmxon) {
7589 vmx->nested.vmxon = true;
7590 vmx->nested.smm.vmxon = false;
7593 if (vmx->nested.smm.guest_mode) {
7594 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7598 vmx->nested.smm.guest_mode = false;
7603 static int enable_smi_window(struct kvm_vcpu *vcpu)
7608 static bool vmx_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7613 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7615 return to_vmx(vcpu)->nested.vmxon;
7618 static __init int hardware_setup(void)
7620 unsigned long host_bndcfgs;
7624 rdmsrl_safe(MSR_EFER, &host_efer);
7627 host_idt_base = dt.address;
7629 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7630 kvm_define_shared_msr(i, vmx_msr_index[i]);
7632 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7635 if (boot_cpu_has(X86_FEATURE_NX))
7636 kvm_enable_efer_bits(EFER_NX);
7638 if (boot_cpu_has(X86_FEATURE_MPX)) {
7639 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7640 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7643 if (boot_cpu_has(X86_FEATURE_XSAVES))
7644 rdmsrl(MSR_IA32_XSS, host_xss);
7646 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7647 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7650 if (!cpu_has_vmx_ept() ||
7651 !cpu_has_vmx_ept_4levels() ||
7652 !cpu_has_vmx_ept_mt_wb() ||
7653 !cpu_has_vmx_invept_global())
7656 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7657 enable_ept_ad_bits = 0;
7659 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7660 enable_unrestricted_guest = 0;
7662 if (!cpu_has_vmx_flexpriority())
7663 flexpriority_enabled = 0;
7665 if (!cpu_has_virtual_nmis())
7669 * set_apic_access_page_addr() is used to reload apic access
7670 * page upon invalidation. No need to do anything if not
7671 * using the APIC_ACCESS_ADDR VMCS field.
7673 if (!flexpriority_enabled)
7674 kvm_x86_ops->set_apic_access_page_addr = NULL;
7676 if (!cpu_has_vmx_tpr_shadow())
7677 kvm_x86_ops->update_cr8_intercept = NULL;
7679 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7680 kvm_disable_largepages();
7682 #if IS_ENABLED(CONFIG_HYPERV)
7683 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7685 kvm_x86_ops->tlb_remote_flush = hv_remote_flush_tlb;
7686 kvm_x86_ops->tlb_remote_flush_with_range =
7687 hv_remote_flush_tlb_with_range;
7691 if (!cpu_has_vmx_ple()) {
7694 ple_window_grow = 0;
7696 ple_window_shrink = 0;
7699 if (!cpu_has_vmx_apicv()) {
7701 kvm_x86_ops->sync_pir_to_irr = NULL;
7704 if (cpu_has_vmx_tsc_scaling()) {
7705 kvm_has_tsc_control = true;
7706 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7707 kvm_tsc_scaling_ratio_frac_bits = 48;
7710 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7718 * Only enable PML when hardware supports PML feature, and both EPT
7719 * and EPT A/D bit features are enabled -- PML depends on them to work.
7721 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7725 kvm_x86_ops->slot_enable_log_dirty = NULL;
7726 kvm_x86_ops->slot_disable_log_dirty = NULL;
7727 kvm_x86_ops->flush_log_dirty = NULL;
7728 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7731 if (!cpu_has_vmx_preemption_timer())
7732 enable_preemption_timer = false;
7734 if (enable_preemption_timer) {
7735 u64 use_timer_freq = 5000ULL * 1000 * 1000;
7738 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7739 cpu_preemption_timer_multi =
7740 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7743 use_timer_freq = (u64)tsc_khz * 1000;
7744 use_timer_freq >>= cpu_preemption_timer_multi;
7747 * KVM "disables" the preemption timer by setting it to its max
7748 * value. Don't use the timer if it might cause spurious exits
7749 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
7751 if (use_timer_freq > 0xffffffffu / 10)
7752 enable_preemption_timer = false;
7755 if (!enable_preemption_timer) {
7756 kvm_x86_ops->set_hv_timer = NULL;
7757 kvm_x86_ops->cancel_hv_timer = NULL;
7758 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7761 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7763 kvm_mce_cap_supported |= MCG_LMCE_P;
7765 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7767 if (!enable_ept || !cpu_has_vmx_intel_pt())
7768 pt_mode = PT_MODE_SYSTEM;
7771 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
7772 vmx_capability.ept);
7774 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
7779 r = alloc_kvm_area();
7781 nested_vmx_hardware_unsetup();
7785 static __exit void hardware_unsetup(void)
7788 nested_vmx_hardware_unsetup();
7793 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
7794 .cpu_has_kvm_support = cpu_has_kvm_support,
7795 .disabled_by_bios = vmx_disabled_by_bios,
7796 .hardware_setup = hardware_setup,
7797 .hardware_unsetup = hardware_unsetup,
7798 .check_processor_compatibility = vmx_check_processor_compat,
7799 .hardware_enable = hardware_enable,
7800 .hardware_disable = hardware_disable,
7801 .cpu_has_accelerated_tpr = report_flexpriority,
7802 .has_emulated_msr = vmx_has_emulated_msr,
7804 .vm_init = vmx_vm_init,
7805 .vm_alloc = vmx_vm_alloc,
7806 .vm_free = vmx_vm_free,
7808 .vcpu_create = vmx_create_vcpu,
7809 .vcpu_free = vmx_free_vcpu,
7810 .vcpu_reset = vmx_vcpu_reset,
7812 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7813 .vcpu_load = vmx_vcpu_load,
7814 .vcpu_put = vmx_vcpu_put,
7816 .update_bp_intercept = update_exception_bitmap,
7817 .get_msr_feature = vmx_get_msr_feature,
7818 .get_msr = vmx_get_msr,
7819 .set_msr = vmx_set_msr,
7820 .get_segment_base = vmx_get_segment_base,
7821 .get_segment = vmx_get_segment,
7822 .set_segment = vmx_set_segment,
7823 .get_cpl = vmx_get_cpl,
7824 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7825 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
7826 .decache_cr3 = vmx_decache_cr3,
7827 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
7828 .set_cr0 = vmx_set_cr0,
7829 .set_cr3 = vmx_set_cr3,
7830 .set_cr4 = vmx_set_cr4,
7831 .set_efer = vmx_set_efer,
7832 .get_idt = vmx_get_idt,
7833 .set_idt = vmx_set_idt,
7834 .get_gdt = vmx_get_gdt,
7835 .set_gdt = vmx_set_gdt,
7836 .get_dr6 = vmx_get_dr6,
7837 .set_dr6 = vmx_set_dr6,
7838 .set_dr7 = vmx_set_dr7,
7839 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7840 .cache_reg = vmx_cache_reg,
7841 .get_rflags = vmx_get_rflags,
7842 .set_rflags = vmx_set_rflags,
7844 .tlb_flush = vmx_flush_tlb,
7845 .tlb_flush_gva = vmx_flush_tlb_gva,
7847 .run = vmx_vcpu_run,
7848 .handle_exit = vmx_handle_exit,
7849 .skip_emulated_instruction = skip_emulated_instruction,
7850 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7851 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7852 .patch_hypercall = vmx_patch_hypercall,
7853 .set_irq = vmx_inject_irq,
7854 .set_nmi = vmx_inject_nmi,
7855 .queue_exception = vmx_queue_exception,
7856 .cancel_injection = vmx_cancel_injection,
7857 .interrupt_allowed = vmx_interrupt_allowed,
7858 .nmi_allowed = vmx_nmi_allowed,
7859 .get_nmi_mask = vmx_get_nmi_mask,
7860 .set_nmi_mask = vmx_set_nmi_mask,
7861 .enable_nmi_window = enable_nmi_window,
7862 .enable_irq_window = enable_irq_window,
7863 .update_cr8_intercept = update_cr8_intercept,
7864 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7865 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7866 .get_enable_apicv = vmx_get_enable_apicv,
7867 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7868 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7869 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7870 .hwapic_irr_update = vmx_hwapic_irr_update,
7871 .hwapic_isr_update = vmx_hwapic_isr_update,
7872 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7873 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7874 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7875 .dy_apicv_has_pending_interrupt = vmx_dy_apicv_has_pending_interrupt,
7877 .set_tss_addr = vmx_set_tss_addr,
7878 .set_identity_map_addr = vmx_set_identity_map_addr,
7879 .get_tdp_level = get_ept_level,
7880 .get_mt_mask = vmx_get_mt_mask,
7882 .get_exit_info = vmx_get_exit_info,
7884 .get_lpage_level = vmx_get_lpage_level,
7886 .cpuid_update = vmx_cpuid_update,
7888 .rdtscp_supported = vmx_rdtscp_supported,
7889 .invpcid_supported = vmx_invpcid_supported,
7891 .set_supported_cpuid = vmx_set_supported_cpuid,
7893 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7895 .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
7896 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7898 .set_tdp_cr3 = vmx_set_cr3,
7900 .check_intercept = vmx_check_intercept,
7901 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7902 .mpx_supported = vmx_mpx_supported,
7903 .xsaves_supported = vmx_xsaves_supported,
7904 .umip_emulated = vmx_umip_emulated,
7905 .pt_supported = vmx_pt_supported,
7906 .pku_supported = vmx_pku_supported,
7908 .request_immediate_exit = vmx_request_immediate_exit,
7910 .sched_in = vmx_sched_in,
7912 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7913 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7914 .flush_log_dirty = vmx_flush_log_dirty,
7915 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7916 .write_log_dirty = vmx_write_pml_buffer,
7918 .pre_block = vmx_pre_block,
7919 .post_block = vmx_post_block,
7921 .pmu_ops = &intel_pmu_ops,
7923 .update_pi_irte = vmx_update_pi_irte,
7925 #ifdef CONFIG_X86_64
7926 .set_hv_timer = vmx_set_hv_timer,
7927 .cancel_hv_timer = vmx_cancel_hv_timer,
7930 .setup_mce = vmx_setup_mce,
7932 .smi_allowed = vmx_smi_allowed,
7933 .pre_enter_smm = vmx_pre_enter_smm,
7934 .pre_leave_smm = vmx_pre_leave_smm,
7935 .enable_smi_window = enable_smi_window,
7937 .check_nested_events = NULL,
7938 .get_nested_state = NULL,
7939 .set_nested_state = NULL,
7940 .get_vmcs12_pages = NULL,
7941 .nested_enable_evmcs = NULL,
7942 .nested_get_evmcs_version = NULL,
7943 .need_emulation_on_page_fault = vmx_need_emulation_on_page_fault,
7944 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7947 static void vmx_cleanup_l1d_flush(void)
7949 if (vmx_l1d_flush_pages) {
7950 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7951 vmx_l1d_flush_pages = NULL;
7953 /* Restore state so sysfs ignores VMX */
7954 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
7957 static void vmx_exit(void)
7959 #ifdef CONFIG_KEXEC_CORE
7960 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
7966 #if IS_ENABLED(CONFIG_HYPERV)
7967 if (static_branch_unlikely(&enable_evmcs)) {
7969 struct hv_vp_assist_page *vp_ap;
7971 * Reset everything to support using non-enlightened VMCS
7972 * access later (e.g. when we reload the module with
7973 * enlightened_vmcs=0)
7975 for_each_online_cpu(cpu) {
7976 vp_ap = hv_get_vp_assist_page(cpu);
7981 vp_ap->nested_control.features.directhypercall = 0;
7982 vp_ap->current_nested_vmcs = 0;
7983 vp_ap->enlighten_vmentry = 0;
7986 static_branch_disable(&enable_evmcs);
7989 vmx_cleanup_l1d_flush();
7991 module_exit(vmx_exit);
7993 static int __init vmx_init(void)
7997 #if IS_ENABLED(CONFIG_HYPERV)
7999 * Enlightened VMCS usage should be recommended and the host needs
8000 * to support eVMCS v1 or above. We can also disable eVMCS support
8001 * with module parameter.
8003 if (enlightened_vmcs &&
8004 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8005 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8006 KVM_EVMCS_VERSION) {
8009 /* Check that we have assist pages on all online CPUs */
8010 for_each_online_cpu(cpu) {
8011 if (!hv_get_vp_assist_page(cpu)) {
8012 enlightened_vmcs = false;
8017 if (enlightened_vmcs) {
8018 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8019 static_branch_enable(&enable_evmcs);
8022 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8023 vmx_x86_ops.enable_direct_tlbflush
8024 = hv_enable_direct_tlbflush;
8027 enlightened_vmcs = false;
8031 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
8032 __alignof__(struct vcpu_vmx), THIS_MODULE);
8037 * Must be called after kvm_init() so enable_ept is properly set
8038 * up. Hand the parameter mitigation value in which was stored in
8039 * the pre module init parser. If no parameter was given, it will
8040 * contain 'auto' which will be turned into the default 'cond'
8043 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8049 #ifdef CONFIG_KEXEC_CORE
8050 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8051 crash_vmclear_local_loaded_vmcss);
8053 vmx_check_vmcs12_offsets();
8057 module_init(vmx_init);