]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - arch/x86/kvm/vmx/vmx.c
KVM: x86: dump_vmcs should not assume GUEST_IA32_EFER is valid
[mirror_ubuntu-hirsute-kernel.git] / arch / x86 / kvm / vmx / vmx.c
CommitLineData
20c8ccb1 1// SPDX-License-Identifier: GPL-2.0-only
6aa8b732
AK
2/*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
7 *
8 * Copyright (C) 2006 Qumranet, Inc.
9611c187 9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
6aa8b732
AK
10 *
11 * Authors:
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
6aa8b732
AK
14 */
15
199b118a
SC
16#include <linux/highmem.h>
17#include <linux/hrtimer.h>
18#include <linux/kernel.h>
edf88417 19#include <linux/kvm_host.h>
6aa8b732 20#include <linux/module.h>
c7addb90 21#include <linux/moduleparam.h>
e9bda3b3 22#include <linux/mod_devicetable.h>
199b118a 23#include <linux/mm.h>
00089c04 24#include <linux/objtool.h>
199b118a 25#include <linux/sched.h>
b284909a 26#include <linux/sched/smt.h>
5a0e3ad6 27#include <linux/slab.h>
cafd6659 28#include <linux/tboot.h>
199b118a 29#include <linux/trace_events.h>
72c3c0fe 30#include <linux/entry-kvm.h>
e495606d 31
199b118a 32#include <asm/apic.h>
fd8ca6da 33#include <asm/asm.h>
28b835d6 34#include <asm/cpu.h>
ba5bade4 35#include <asm/cpu_device_id.h>
199b118a 36#include <asm/debugreg.h>
3b3be0d1 37#include <asm/desc.h>
952f07ec 38#include <asm/fpu/internal.h>
199b118a 39#include <asm/io.h>
efc64404 40#include <asm/irq_remapping.h>
199b118a
SC
41#include <asm/kexec.h>
42#include <asm/perf_event.h>
d6e41f11 43#include <asm/mmu_context.h>
773e8a04 44#include <asm/mshyperv.h>
b10c307f 45#include <asm/mwait.h>
199b118a
SC
46#include <asm/spec-ctrl.h>
47#include <asm/virtext.h>
48#include <asm/vmx.h>
6aa8b732 49
3077c191 50#include "capabilities.h"
199b118a 51#include "cpuid.h"
4cebd747 52#include "evmcs.h"
199b118a
SC
53#include "irq.h"
54#include "kvm_cache_regs.h"
55#include "lapic.h"
56#include "mmu.h"
55d2375e 57#include "nested.h"
25462f7f 58#include "pmu.h"
199b118a 59#include "trace.h"
cb1d474b 60#include "vmcs.h"
609363cf 61#include "vmcs12.h"
89b0c9f5 62#include "vmx.h"
199b118a 63#include "x86.h"
229456fc 64
6aa8b732
AK
65MODULE_AUTHOR("Qumranet");
66MODULE_LICENSE("GPL");
67
575b255c 68#ifdef MODULE
e9bda3b3 69static const struct x86_cpu_id vmx_cpu_id[] = {
320debe5 70 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
e9bda3b3
JT
71 {}
72};
73MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
575b255c 74#endif
e9bda3b3 75
2c4fd91d 76bool __read_mostly enable_vpid = 1;
736caefe 77module_param_named(vpid, enable_vpid, bool, 0444);
2384d2b3 78
d02fcf50
PB
79static bool __read_mostly enable_vnmi = 1;
80module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
81
2c4fd91d 82bool __read_mostly flexpriority_enabled = 1;
736caefe 83module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
4c9fc8ef 84
2c4fd91d 85bool __read_mostly enable_ept = 1;
736caefe 86module_param_named(ept, enable_ept, bool, S_IRUGO);
d56f546d 87
2c4fd91d 88bool __read_mostly enable_unrestricted_guest = 1;
3a624e29
NK
89module_param_named(unrestricted_guest,
90 enable_unrestricted_guest, bool, S_IRUGO);
91
2c4fd91d 92bool __read_mostly enable_ept_ad_bits = 1;
83c3a331
XH
93module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
94
a27685c3 95static bool __read_mostly emulate_invalid_guest_state = true;
c1f8bc04 96module_param(emulate_invalid_guest_state, bool, S_IRUGO);
04fa4d32 97
476bc001 98static bool __read_mostly fasteoi = 1;
58fbbf26
KT
99module_param(fasteoi, bool, S_IRUGO);
100
a4443267 101bool __read_mostly enable_apicv = 1;
01e439be 102module_param(enable_apicv, bool, S_IRUGO);
83d4c286 103
801d3424
NHE
104/*
105 * If nested=1, nested virtualization is supported, i.e., guests may use
106 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
107 * use VMX instructions.
108 */
1e58e5e5 109static bool __read_mostly nested = 1;
801d3424
NHE
110module_param(nested, bool, S_IRUGO);
111
2c4fd91d 112bool __read_mostly enable_pml = 1;
843e4330
KH
113module_param_named(pml, enable_pml, bool, S_IRUGO);
114
6f2f8453
PB
115static bool __read_mostly dump_invalid_vmcs = 0;
116module_param(dump_invalid_vmcs, bool, 0644);
117
904e14fb
PB
118#define MSR_BITMAP_MODE_X2APIC 1
119#define MSR_BITMAP_MODE_X2APIC_APICV 2
904e14fb 120
64903d61
HZ
121#define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
122
64672c95
YJ
123/* Guest_tsc -> host_tsc conversion requires 64-bit division. */
124static int __read_mostly cpu_preemption_timer_multi;
125static bool __read_mostly enable_preemption_timer = 1;
126#ifdef CONFIG_X86_64
127module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
128#endif
129
b96e6506
MG
130extern bool __read_mostly allow_smaller_maxphyaddr;
131module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
132
3de6347b 133#define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
1706bd0c
SC
134#define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
135#define KVM_VM_CR0_ALWAYS_ON \
136 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
137 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
4c38609a 138
5dc1f044 139#define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
cdc0e244
AK
140#define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
141#define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
142
78ac8b47
AK
143#define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
144
bf8c55d8
CP
145#define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
146 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
147 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
148 RTIT_STATUS_BYTECNT))
149
3eb90017
AG
150/*
151 * List of MSRs that can be directly passed to the guest.
152 * In addition to these x2apic and PT MSRs are handled specially.
153 */
154static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
155 MSR_IA32_SPEC_CTRL,
156 MSR_IA32_PRED_CMD,
157 MSR_IA32_TSC,
158 MSR_FS_BASE,
159 MSR_GS_BASE,
160 MSR_KERNEL_GS_BASE,
161 MSR_IA32_SYSENTER_CS,
162 MSR_IA32_SYSENTER_ESP,
163 MSR_IA32_SYSENTER_EIP,
164 MSR_CORE_C1_RES,
165 MSR_CORE_C3_RESIDENCY,
166 MSR_CORE_C6_RESIDENCY,
167 MSR_CORE_C7_RESIDENCY,
168};
bf8c55d8 169
4b8d54f9
ZE
170/*
171 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
172 * ple_gap: upper bound on the amount of time between two successive
173 * executions of PAUSE in a loop. Also indicate if ple enabled.
00c25bce 174 * According to test, this time is usually smaller than 128 cycles.
4b8d54f9
ZE
175 * ple_window: upper bound on the amount of time a guest is allowed to execute
176 * in a PAUSE loop. Tests indicate that most spinlocks are held for
177 * less than 2^12 cycles
178 * Time is measured based on a counter that runs at the same rate as the TSC,
179 * refer SDM volume 3b section 21.6.13 & 22.1.3.
180 */
c8e88717 181static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
a87c99e6 182module_param(ple_gap, uint, 0444);
b4a2d31d 183
7fbc85a5
BM
184static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
185module_param(ple_window, uint, 0444);
4b8d54f9 186
b4a2d31d 187/* Default doubles per-vcpu window every exit. */
c8e88717 188static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
7fbc85a5 189module_param(ple_window_grow, uint, 0444);
b4a2d31d
RK
190
191/* Default resets per-vcpu window every exit to ple_window. */
c8e88717 192static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
7fbc85a5 193module_param(ple_window_shrink, uint, 0444);
b4a2d31d
RK
194
195/* Default is to compute the maximum so we can never overflow. */
7fbc85a5
BM
196static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
197module_param(ple_window_max, uint, 0444);
b4a2d31d 198
f99e3daf
CP
199/* Default is SYSTEM mode, 1 for host-guest mode */
200int __read_mostly pt_mode = PT_MODE_SYSTEM;
201module_param(pt_mode, int, S_IRUGO);
202
a399477e 203static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
427362a1 204static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
dd4bfa73 205static DEFINE_MUTEX(vmx_l1d_flush_mutex);
a399477e 206
7db92e16
TG
207/* Storage for pre module init parameter parsing */
208static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
a399477e
KRW
209
210static const struct {
211 const char *option;
0027ff2a 212 bool for_parse;
a399477e 213} vmentry_l1d_param[] = {
0027ff2a
PB
214 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
215 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
216 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
217 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
218 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
219 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
a399477e
KRW
220};
221
7db92e16
TG
222#define L1D_CACHE_ORDER 4
223static void *vmx_l1d_flush_pages;
224
225static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
a399477e 226{
7db92e16 227 struct page *page;
288d152c 228 unsigned int i;
a399477e 229
19a36d32
WL
230 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
231 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
232 return 0;
233 }
234
7db92e16
TG
235 if (!enable_ept) {
236 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
237 return 0;
a399477e
KRW
238 }
239
d806afa4
YW
240 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
241 u64 msr;
242
243 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
244 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
245 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
246 return 0;
247 }
248 }
8e0b2b91 249
d90a7a0e
JK
250 /* If set to auto use the default l1tf mitigation method */
251 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
252 switch (l1tf_mitigation) {
253 case L1TF_MITIGATION_OFF:
254 l1tf = VMENTER_L1D_FLUSH_NEVER;
255 break;
256 case L1TF_MITIGATION_FLUSH_NOWARN:
257 case L1TF_MITIGATION_FLUSH:
258 case L1TF_MITIGATION_FLUSH_NOSMT:
259 l1tf = VMENTER_L1D_FLUSH_COND;
260 break;
261 case L1TF_MITIGATION_FULL:
262 case L1TF_MITIGATION_FULL_FORCE:
263 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
264 break;
265 }
266 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
267 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
268 }
269
7db92e16
TG
270 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
271 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
41836839
BG
272 /*
273 * This allocation for vmx_l1d_flush_pages is not tied to a VM
274 * lifetime and so should not be charged to a memcg.
275 */
7db92e16
TG
276 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
277 if (!page)
278 return -ENOMEM;
279 vmx_l1d_flush_pages = page_address(page);
288d152c
NS
280
281 /*
282 * Initialize each page with a different pattern in
283 * order to protect against KSM in the nested
284 * virtualization case.
285 */
286 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
287 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
288 PAGE_SIZE);
289 }
7db92e16
TG
290 }
291
292 l1tf_vmx_mitigation = l1tf;
293
895ae47f
TG
294 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
295 static_branch_enable(&vmx_l1d_should_flush);
296 else
297 static_branch_disable(&vmx_l1d_should_flush);
4c6523ec 298
427362a1
NS
299 if (l1tf == VMENTER_L1D_FLUSH_COND)
300 static_branch_enable(&vmx_l1d_flush_cond);
895ae47f 301 else
427362a1 302 static_branch_disable(&vmx_l1d_flush_cond);
7db92e16
TG
303 return 0;
304}
305
306static int vmentry_l1d_flush_parse(const char *s)
307{
308 unsigned int i;
309
310 if (s) {
311 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
0027ff2a
PB
312 if (vmentry_l1d_param[i].for_parse &&
313 sysfs_streq(s, vmentry_l1d_param[i].option))
314 return i;
7db92e16
TG
315 }
316 }
a399477e
KRW
317 return -EINVAL;
318}
319
7db92e16
TG
320static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
321{
dd4bfa73 322 int l1tf, ret;
7db92e16 323
7db92e16
TG
324 l1tf = vmentry_l1d_flush_parse(s);
325 if (l1tf < 0)
326 return l1tf;
327
0027ff2a
PB
328 if (!boot_cpu_has(X86_BUG_L1TF))
329 return 0;
330
7db92e16
TG
331 /*
332 * Has vmx_init() run already? If not then this is the pre init
333 * parameter parsing. In that case just store the value and let
334 * vmx_init() do the proper setup after enable_ept has been
335 * established.
336 */
337 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
338 vmentry_l1d_flush_param = l1tf;
339 return 0;
340 }
341
dd4bfa73
TG
342 mutex_lock(&vmx_l1d_flush_mutex);
343 ret = vmx_setup_l1d_flush(l1tf);
344 mutex_unlock(&vmx_l1d_flush_mutex);
345 return ret;
7db92e16
TG
346}
347
a399477e
KRW
348static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
349{
0027ff2a
PB
350 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
351 return sprintf(s, "???\n");
352
7db92e16 353 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
a399477e
KRW
354}
355
356static const struct kernel_param_ops vmentry_l1d_flush_ops = {
357 .set = vmentry_l1d_flush_set,
358 .get = vmentry_l1d_flush_get,
359};
895ae47f 360module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
a399477e 361
d99e4152 362static u32 vmx_segment_access_rights(struct kvm_segment *var);
476c9bd8 363static __always_inline void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu,
15d45071 364 u32 msr, int type);
75880a01 365
453eafbe
SC
366void vmx_vmexit(void);
367
52a9fcbc
SC
368#define vmx_insn_failed(fmt...) \
369do { \
370 WARN_ONCE(1, fmt); \
371 pr_warn_ratelimited(fmt); \
372} while (0)
373
6e202097
SC
374asmlinkage void vmread_error(unsigned long field, bool fault)
375{
376 if (fault)
377 kvm_spurious_fault();
378 else
379 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
380}
381
52a9fcbc
SC
382noinline void vmwrite_error(unsigned long field, unsigned long value)
383{
384 vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
385 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
386}
387
388noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
389{
390 vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
391}
392
393noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
394{
395 vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
396}
397
398noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
399{
400 vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
401 ext, vpid, gva);
402}
403
404noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
405{
406 vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
407 ext, eptp, gpa);
408}
409
6aa8b732 410static DEFINE_PER_CPU(struct vmcs *, vmxarea);
75edce8a 411DEFINE_PER_CPU(struct vmcs *, current_vmcs);
d462b819
NHE
412/*
413 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
414 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
415 */
416static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
6aa8b732 417
2384d2b3
SY
418static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
419static DEFINE_SPINLOCK(vmx_vpid_lock);
420
3077c191
SC
421struct vmcs_config vmcs_config;
422struct vmx_capability vmx_capability;
d56f546d 423
6aa8b732
AK
424#define VMX_SEGMENT_FIELD(seg) \
425 [VCPU_SREG_##seg] = { \
426 .selector = GUEST_##seg##_SELECTOR, \
427 .base = GUEST_##seg##_BASE, \
428 .limit = GUEST_##seg##_LIMIT, \
429 .ar_bytes = GUEST_##seg##_AR_BYTES, \
430 }
431
772e0318 432static const struct kvm_vmx_segment_field {
6aa8b732
AK
433 unsigned selector;
434 unsigned base;
435 unsigned limit;
436 unsigned ar_bytes;
437} kvm_vmx_segment_fields[] = {
438 VMX_SEGMENT_FIELD(CS),
439 VMX_SEGMENT_FIELD(DS),
440 VMX_SEGMENT_FIELD(ES),
441 VMX_SEGMENT_FIELD(FS),
442 VMX_SEGMENT_FIELD(GS),
443 VMX_SEGMENT_FIELD(SS),
444 VMX_SEGMENT_FIELD(TR),
445 VMX_SEGMENT_FIELD(LDTR),
446};
447
ec0241f3
SC
448static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
449{
450 vmx->segment_cache.bitmask = 0;
451}
452
2342080c 453static unsigned long host_idt_base;
26bb0981 454
4d56c8a7 455/*
898a811f
JM
456 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
457 * will emulate SYSCALL in legacy mode if the vendor string in guest
458 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
459 * support this emulation, IA32_STAR must always be included in
14a61b64 460 * vmx_uret_msrs_list[], even in i386 builds.
4d56c8a7 461 */
6a2e0923 462static const u32 vmx_uret_msrs_list[] = {
05b3e0c2 463#ifdef CONFIG_X86_64
44ea2b17 464 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
6aa8b732 465#endif
8c06585d 466 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
c11f83e0 467 MSR_IA32_TSX_CTRL,
6aa8b732 468};
6aa8b732 469
773e8a04
VK
470#if IS_ENABLED(CONFIG_HYPERV)
471static bool __read_mostly enlightened_vmcs = true;
472module_param(enlightened_vmcs, bool, 0444);
473
877ad952
TL
474/* check_ept_pointer() should be under protection of ept_pointer_lock. */
475static void check_ept_pointer_match(struct kvm *kvm)
476{
477 struct kvm_vcpu *vcpu;
478 u64 tmp_eptp = INVALID_PAGE;
479 int i;
480
481 kvm_for_each_vcpu(i, vcpu, kvm) {
482 if (!VALID_PAGE(tmp_eptp)) {
483 tmp_eptp = to_vmx(vcpu)->ept_pointer;
484 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
485 to_kvm_vmx(kvm)->ept_pointers_match
486 = EPT_POINTERS_MISMATCH;
487 return;
488 }
489 }
490
491 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
492}
493
8997f657 494static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
1f3a3e46
LT
495 void *data)
496{
497 struct kvm_tlb_range *range = data;
498
499 return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
500 range->pages);
501}
502
503static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
504 struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
505{
506 u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
507
508 /*
509 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
510 * of the base of EPT PML4 table, strip off EPT configuration
511 * information.
512 */
513 if (range)
514 return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
515 kvm_fill_hv_flush_list_func, (void *)range);
516 else
517 return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
518}
519
520static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
521 struct kvm_tlb_range *range)
877ad952 522{
a5c214da 523 struct kvm_vcpu *vcpu;
b7c1c226 524 int ret = 0, i;
877ad952
TL
525
526 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
527
528 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
529 check_ept_pointer_match(kvm);
530
531 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
53963a70 532 kvm_for_each_vcpu(i, vcpu, kvm) {
1f3a3e46
LT
533 /* If ept_pointer is invalid pointer, bypass flush request. */
534 if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
535 ret |= __hv_remote_flush_tlb_with_range(
536 kvm, vcpu, range);
53963a70 537 }
a5c214da 538 } else {
1f3a3e46
LT
539 ret = __hv_remote_flush_tlb_with_range(kvm,
540 kvm_get_vcpu(kvm, 0), range);
877ad952 541 }
877ad952 542
877ad952
TL
543 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
544 return ret;
545}
1f3a3e46
LT
546static int hv_remote_flush_tlb(struct kvm *kvm)
547{
548 return hv_remote_flush_tlb_with_range(kvm, NULL);
549}
550
6f6a657c
VK
551static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
552{
553 struct hv_enlightened_vmcs *evmcs;
554 struct hv_partition_assist_pg **p_hv_pa_pg =
555 &vcpu->kvm->arch.hyperv.hv_pa_pg;
556 /*
557 * Synthetic VM-Exit is not enabled in current code and so All
558 * evmcs in singe VM shares same assist page.
559 */
cab01850 560 if (!*p_hv_pa_pg)
6f6a657c 561 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL);
cab01850
VK
562
563 if (!*p_hv_pa_pg)
564 return -ENOMEM;
6f6a657c
VK
565
566 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
567
568 evmcs->partition_assist_page =
569 __pa(*p_hv_pa_pg);
cab01850 570 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
6f6a657c
VK
571 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
572
6f6a657c
VK
573 return 0;
574}
575
773e8a04
VK
576#endif /* IS_ENABLED(CONFIG_HYPERV) */
577
64672c95
YJ
578/*
579 * Comment's format: document - errata name - stepping - processor name.
580 * Refer from
581 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
582 */
583static u32 vmx_preemption_cpu_tfms[] = {
584/* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
5850x000206E6,
586/* 323056.pdf - AAX65 - C2 - Xeon L3406 */
587/* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
588/* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
5890x00020652,
590/* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
5910x00020655,
592/* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
593/* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
594/*
595 * 320767.pdf - AAP86 - B1 -
596 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
597 */
5980x000106E5,
599/* 321333.pdf - AAM126 - C0 - Xeon 3500 */
6000x000106A0,
601/* 321333.pdf - AAM126 - C1 - Xeon 3500 */
6020x000106A1,
603/* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
6040x000106A4,
605 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
606 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
607 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
6080x000106A5,
3d82c565
WH
609 /* Xeon E3-1220 V2 */
6100x000306A8,
64672c95
YJ
611};
612
613static inline bool cpu_has_broken_vmx_preemption_timer(void)
614{
615 u32 eax = cpuid_eax(0x00000001), i;
616
617 /* Clear the reserved bits */
618 eax &= ~(0x3U << 14 | 0xfU << 28);
03f6a22a 619 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
64672c95
YJ
620 if (eax == vmx_preemption_cpu_tfms[i])
621 return true;
622
623 return false;
624}
625
35754c98 626static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
f78e0e2e 627{
35754c98 628 return flexpriority_enabled && lapic_in_kernel(vcpu);
f78e0e2e
SY
629}
630
04547156
SY
631static inline bool report_flexpriority(void)
632{
633 return flexpriority_enabled;
634}
635
3eb90017
AG
636static int possible_passthrough_msr_slot(u32 msr)
637{
638 u32 i;
639
640 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
641 if (vmx_possible_passthrough_msrs[i] == msr)
642 return i;
643
644 return -ENOENT;
645}
646
647static bool is_valid_passthrough_msr(u32 msr)
648{
649 bool r;
650
651 switch (msr) {
652 case 0x800 ... 0x8ff:
653 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
654 return true;
655 case MSR_IA32_RTIT_STATUS:
656 case MSR_IA32_RTIT_OUTPUT_BASE:
657 case MSR_IA32_RTIT_OUTPUT_MASK:
658 case MSR_IA32_RTIT_CR3_MATCH:
659 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
660 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
661 return true;
662 }
663
664 r = possible_passthrough_msr_slot(msr) != -ENOENT;
665
666 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
667
668 return r;
669}
670
1e7a4830 671static inline int __vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
7725f0ba
AK
672{
673 int i;
674
fbc18007 675 for (i = 0; i < vmx->nr_uret_msrs; ++i)
802145c5 676 if (vmx_uret_msrs_list[vmx->guest_uret_msrs[i].slot] == msr)
a75beee6
ED
677 return i;
678 return -1;
679}
680
d85a8034 681struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
a75beee6
ED
682{
683 int i;
684
1e7a4830 685 i = __vmx_find_uret_msr(vmx, msr);
a75beee6 686 if (i >= 0)
eb3db1b1 687 return &vmx->guest_uret_msrs[i];
8b6d44c7 688 return NULL;
7725f0ba
AK
689}
690
7bf662bb
SC
691static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
692 struct vmx_uret_msr *msr, u64 data)
b07a5c53
PB
693{
694 int ret = 0;
695
696 u64 old_msr_data = msr->data;
697 msr->data = data;
e9bb1ae9 698 if (msr - vmx->guest_uret_msrs < vmx->nr_active_uret_msrs) {
b07a5c53 699 preempt_disable();
802145c5 700 ret = kvm_set_user_return_msr(msr->slot, msr->data, msr->mask);
b07a5c53
PB
701 preempt_enable();
702 if (ret)
703 msr->data = old_msr_data;
704 }
705 return ret;
706}
707
2965faa5 708#ifdef CONFIG_KEXEC_CORE
8f536b76
ZY
709static void crash_vmclear_local_loaded_vmcss(void)
710{
711 int cpu = raw_smp_processor_id();
712 struct loaded_vmcs *v;
713
8f536b76
ZY
714 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
715 loaded_vmcss_on_cpu_link)
716 vmcs_clear(v->vmcs);
717}
2965faa5 718#endif /* CONFIG_KEXEC_CORE */
8f536b76 719
d462b819 720static void __loaded_vmcs_clear(void *arg)
6aa8b732 721{
d462b819 722 struct loaded_vmcs *loaded_vmcs = arg;
d3b2c338 723 int cpu = raw_smp_processor_id();
6aa8b732 724
d462b819
NHE
725 if (loaded_vmcs->cpu != cpu)
726 return; /* vcpu migration can race with cpu offline */
727 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
6aa8b732 728 per_cpu(current_vmcs, cpu) = NULL;
31603d4f
SC
729
730 vmcs_clear(loaded_vmcs->vmcs);
731 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
732 vmcs_clear(loaded_vmcs->shadow_vmcs);
733
d462b819 734 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
5a560f8b
XG
735
736 /*
31603d4f
SC
737 * Ensure all writes to loaded_vmcs, including deleting it from its
738 * current percpu list, complete before setting loaded_vmcs->vcpu to
739 * -1, otherwise a different cpu can see vcpu == -1 first and add
740 * loaded_vmcs to its percpu list before it's deleted from this cpu's
741 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
5a560f8b
XG
742 */
743 smp_wmb();
744
31603d4f
SC
745 loaded_vmcs->cpu = -1;
746 loaded_vmcs->launched = 0;
6aa8b732
AK
747}
748
89b0c9f5 749void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
8d0be2b3 750{
e6c7d321
XG
751 int cpu = loaded_vmcs->cpu;
752
753 if (cpu != -1)
754 smp_call_function_single(cpu,
755 __loaded_vmcs_clear, loaded_vmcs, 1);
8d0be2b3
AK
756}
757
2fb92db1
AK
758static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
759 unsigned field)
760{
761 bool ret;
762 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
763
cb3c1e2f
SC
764 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
765 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
2fb92db1
AK
766 vmx->segment_cache.bitmask = 0;
767 }
768 ret = vmx->segment_cache.bitmask & mask;
769 vmx->segment_cache.bitmask |= mask;
770 return ret;
771}
772
773static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
774{
775 u16 *p = &vmx->segment_cache.seg[seg].selector;
776
777 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
778 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
779 return *p;
780}
781
782static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
783{
784 ulong *p = &vmx->segment_cache.seg[seg].base;
785
786 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
787 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
788 return *p;
789}
790
791static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
792{
793 u32 *p = &vmx->segment_cache.seg[seg].limit;
794
795 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
796 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
797 return *p;
798}
799
800static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
801{
802 u32 *p = &vmx->segment_cache.seg[seg].ar;
803
804 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
805 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
806 return *p;
807}
808
97b7ead3 809void update_exception_bitmap(struct kvm_vcpu *vcpu)
abd3f2d6
AK
810{
811 u32 eb;
812
fd7373cc 813 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
bd7e5b08 814 (1u << DB_VECTOR) | (1u << AC_VECTOR);
9e869480
LA
815 /*
816 * Guest access to VMware backdoor ports could legitimately
817 * trigger #GP because of TSS I/O permission bitmap.
818 * We intercept those #GP and allow access to them anyway
819 * as VMware does.
820 */
821 if (enable_vmware_backdoor)
822 eb |= (1u << GP_VECTOR);
fd7373cc
JK
823 if ((vcpu->guest_debug &
824 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
825 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
826 eb |= 1u << BP_VECTOR;
7ffd92c5 827 if (to_vmx(vcpu)->rmode.vm86_active)
abd3f2d6 828 eb = ~0;
a0c13434 829 if (!vmx_need_pf_intercept(vcpu))
49f933d4 830 eb &= ~(1u << PF_VECTOR);
36cf24e0
NHE
831
832 /* When we are running a nested L2 guest and L1 specified for it a
833 * certain exception bitmap, we must trap the same exceptions and pass
834 * them to L1. When running L2, we will only handle the exceptions
835 * specified above if L1 did not want them.
836 */
837 if (is_guest_mode(vcpu))
838 eb |= get_vmcs12(vcpu)->exception_bitmap;
b502e6ec
PB
839 else {
840 /*
841 * If EPT is enabled, #PF is only trapped if MAXPHYADDR is mismatched
842 * between guest and host. In that case we only care about present
843 * faults. For vmcs02, however, PFEC_MASK and PFEC_MATCH are set in
844 * prepare_vmcs02_rare.
845 */
846 bool selective_pf_trap = enable_ept && (eb & (1u << PF_VECTOR));
847 int mask = selective_pf_trap ? PFERR_PRESENT_MASK : 0;
848 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
849 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, mask);
850 }
36cf24e0 851
abd3f2d6
AK
852 vmcs_write32(EXCEPTION_BITMAP, eb);
853}
854
d28b387f
KA
855/*
856 * Check if MSR is intercepted for currently loaded MSR bitmap.
857 */
858static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
859{
860 unsigned long *msr_bitmap;
861 int f = sizeof(unsigned long);
862
863 if (!cpu_has_vmx_msr_bitmap())
864 return true;
865
866 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
867
868 if (msr <= 0x1fff) {
869 return !!test_bit(msr, msr_bitmap + 0x800 / f);
870 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
871 msr &= 0x1fff;
872 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
873 }
874
875 return true;
876}
877
2961e876
GN
878static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
879 unsigned long entry, unsigned long exit)
8bf00a52 880{
2961e876
GN
881 vm_entry_controls_clearbit(vmx, entry);
882 vm_exit_controls_clearbit(vmx, exit);
8bf00a52
GN
883}
884
a128a934 885int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
ca83b4a7
KRW
886{
887 unsigned int i;
888
889 for (i = 0; i < m->nr; ++i) {
890 if (m->val[i].index == msr)
891 return i;
892 }
893 return -ENOENT;
894}
895
61d2ef2c
AK
896static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
897{
ca83b4a7 898 int i;
61d2ef2c
AK
899 struct msr_autoload *m = &vmx->msr_autoload;
900
8bf00a52
GN
901 switch (msr) {
902 case MSR_EFER:
c73da3fc 903 if (cpu_has_load_ia32_efer()) {
2961e876
GN
904 clear_atomic_switch_msr_special(vmx,
905 VM_ENTRY_LOAD_IA32_EFER,
8bf00a52
GN
906 VM_EXIT_LOAD_IA32_EFER);
907 return;
908 }
909 break;
910 case MSR_CORE_PERF_GLOBAL_CTRL:
c73da3fc 911 if (cpu_has_load_perf_global_ctrl()) {
2961e876 912 clear_atomic_switch_msr_special(vmx,
8bf00a52
GN
913 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
914 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
915 return;
916 }
917 break;
110312c8 918 }
a128a934 919 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
ca83b4a7 920 if (i < 0)
31907093 921 goto skip_guest;
33966dd6 922 --m->guest.nr;
33966dd6 923 m->guest.val[i] = m->guest.val[m->guest.nr];
33966dd6 924 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
110312c8 925
31907093 926skip_guest:
a128a934 927 i = vmx_find_loadstore_msr_slot(&m->host, msr);
31907093 928 if (i < 0)
61d2ef2c 929 return;
31907093
KRW
930
931 --m->host.nr;
932 m->host.val[i] = m->host.val[m->host.nr];
33966dd6 933 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
61d2ef2c
AK
934}
935
2961e876
GN
936static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
937 unsigned long entry, unsigned long exit,
938 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
939 u64 guest_val, u64 host_val)
8bf00a52
GN
940{
941 vmcs_write64(guest_val_vmcs, guest_val);
5a5e8a15
SC
942 if (host_val_vmcs != HOST_IA32_EFER)
943 vmcs_write64(host_val_vmcs, host_val);
2961e876
GN
944 vm_entry_controls_setbit(vmx, entry);
945 vm_exit_controls_setbit(vmx, exit);
8bf00a52
GN
946}
947
61d2ef2c 948static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
989e3992 949 u64 guest_val, u64 host_val, bool entry_only)
61d2ef2c 950{
989e3992 951 int i, j = 0;
61d2ef2c
AK
952 struct msr_autoload *m = &vmx->msr_autoload;
953
8bf00a52
GN
954 switch (msr) {
955 case MSR_EFER:
c73da3fc 956 if (cpu_has_load_ia32_efer()) {
2961e876
GN
957 add_atomic_switch_msr_special(vmx,
958 VM_ENTRY_LOAD_IA32_EFER,
8bf00a52
GN
959 VM_EXIT_LOAD_IA32_EFER,
960 GUEST_IA32_EFER,
961 HOST_IA32_EFER,
962 guest_val, host_val);
963 return;
964 }
965 break;
966 case MSR_CORE_PERF_GLOBAL_CTRL:
c73da3fc 967 if (cpu_has_load_perf_global_ctrl()) {
2961e876 968 add_atomic_switch_msr_special(vmx,
8bf00a52
GN
969 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
970 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
971 GUEST_IA32_PERF_GLOBAL_CTRL,
972 HOST_IA32_PERF_GLOBAL_CTRL,
973 guest_val, host_val);
974 return;
975 }
976 break;
7099e2e1
RK
977 case MSR_IA32_PEBS_ENABLE:
978 /* PEBS needs a quiescent period after being disabled (to write
979 * a record). Disabling PEBS through VMX MSR swapping doesn't
980 * provide that period, so a CPU could write host's record into
981 * guest's memory.
982 */
983 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
110312c8
AK
984 }
985
a128a934 986 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
989e3992 987 if (!entry_only)
a128a934 988 j = vmx_find_loadstore_msr_slot(&m->host, msr);
61d2ef2c 989
ce833b23
SC
990 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
991 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
60266204 992 printk_once(KERN_WARNING "Not enough msr switch entries. "
e7fc6f93
GN
993 "Can't add msr %x\n", msr);
994 return;
61d2ef2c 995 }
31907093 996 if (i < 0) {
ca83b4a7 997 i = m->guest.nr++;
33966dd6 998 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
31907093 999 }
989e3992
KRW
1000 m->guest.val[i].index = msr;
1001 m->guest.val[i].value = guest_val;
1002
1003 if (entry_only)
1004 return;
61d2ef2c 1005
31907093
KRW
1006 if (j < 0) {
1007 j = m->host.nr++;
33966dd6 1008 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
61d2ef2c 1009 }
31907093
KRW
1010 m->host.val[j].index = msr;
1011 m->host.val[j].value = host_val;
61d2ef2c
AK
1012}
1013
86e3e494 1014static bool update_transition_efer(struct vcpu_vmx *vmx)
2cc51560 1015{
844a5fe2
PB
1016 u64 guest_efer = vmx->vcpu.arch.efer;
1017 u64 ignore_bits = 0;
86e3e494 1018 int i;
844a5fe2 1019
9167ab79
PB
1020 /* Shadow paging assumes NX to be available. */
1021 if (!enable_ept)
1022 guest_efer |= EFER_NX;
3a34a881 1023
51c6cf66 1024 /*
844a5fe2 1025 * LMA and LME handled by hardware; SCE meaningless outside long mode.
51c6cf66 1026 */
844a5fe2 1027 ignore_bits |= EFER_SCE;
51c6cf66
AK
1028#ifdef CONFIG_X86_64
1029 ignore_bits |= EFER_LMA | EFER_LME;
1030 /* SCE is meaningful only in long mode on Intel */
1031 if (guest_efer & EFER_LMA)
1032 ignore_bits &= ~(u64)EFER_SCE;
1033#endif
84ad33ef 1034
f6577a5f
AL
1035 /*
1036 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1037 * On CPUs that support "load IA32_EFER", always switch EFER
1038 * atomically, since it's faster than switching it manually.
1039 */
c73da3fc 1040 if (cpu_has_load_ia32_efer() ||
f6577a5f 1041 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
84ad33ef
AK
1042 if (!(guest_efer & EFER_LMA))
1043 guest_efer &= ~EFER_LME;
54b98bff
AL
1044 if (guest_efer != host_efer)
1045 add_atomic_switch_msr(vmx, MSR_EFER,
989e3992 1046 guest_efer, host_efer, false);
02343cf2
SC
1047 else
1048 clear_atomic_switch_msr(vmx, MSR_EFER);
84ad33ef 1049 return false;
86e3e494 1050 }
02343cf2 1051
86e3e494
SC
1052 i = __vmx_find_uret_msr(vmx, MSR_EFER);
1053 if (i < 0)
1054 return false;
02343cf2 1055
86e3e494 1056 clear_atomic_switch_msr(vmx, MSR_EFER);
844a5fe2 1057
86e3e494
SC
1058 guest_efer &= ~ignore_bits;
1059 guest_efer |= host_efer & ignore_bits;
84ad33ef 1060
86e3e494
SC
1061 vmx->guest_uret_msrs[i].data = guest_efer;
1062 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1063
1064 return true;
51c6cf66
AK
1065}
1066
e28baead
AL
1067#ifdef CONFIG_X86_32
1068/*
1069 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1070 * VMCS rather than the segment table. KVM uses this helper to figure
1071 * out the current bases to poke them into the VMCS before entry.
1072 */
2d49ec72
GN
1073static unsigned long segment_base(u16 selector)
1074{
8c2e41f7 1075 struct desc_struct *table;
2d49ec72
GN
1076 unsigned long v;
1077
8c2e41f7 1078 if (!(selector & ~SEGMENT_RPL_MASK))
2d49ec72
GN
1079 return 0;
1080
45fc8757 1081 table = get_current_gdt_ro();
2d49ec72 1082
8c2e41f7 1083 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2d49ec72
GN
1084 u16 ldt_selector = kvm_read_ldt();
1085
8c2e41f7 1086 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2d49ec72
GN
1087 return 0;
1088
8c2e41f7 1089 table = (struct desc_struct *)segment_base(ldt_selector);
2d49ec72 1090 }
8c2e41f7 1091 v = get_desc_base(&table[selector >> 3]);
2d49ec72
GN
1092 return v;
1093}
e28baead 1094#endif
2d49ec72 1095
e348ac7c
SC
1096static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1097{
2ef7619d 1098 return vmx_pt_mode_is_host_guest() &&
e348ac7c
SC
1099 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1100}
1101
1cc6cbc3
SC
1102static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1103{
1104 /* The base must be 128-byte aligned and a legal physical address. */
7096cbfb 1105 return !kvm_vcpu_is_illegal_gpa(vcpu, base) && !(base & 0x7f);
1cc6cbc3
SC
1106}
1107
2ef444f1
CP
1108static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1109{
1110 u32 i;
1111
1112 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1113 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1114 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1115 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1116 for (i = 0; i < addr_range; i++) {
1117 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1118 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1119 }
1120}
1121
1122static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1123{
1124 u32 i;
1125
1126 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1127 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1128 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1129 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1130 for (i = 0; i < addr_range; i++) {
1131 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1132 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1133 }
1134}
1135
1136static void pt_guest_enter(struct vcpu_vmx *vmx)
1137{
2ef7619d 1138 if (vmx_pt_mode_is_system())
2ef444f1
CP
1139 return;
1140
2ef444f1 1141 /*
b08c2896
CP
1142 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1143 * Save host state before VM entry.
2ef444f1 1144 */
b08c2896 1145 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
2ef444f1
CP
1146 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1147 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1148 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1149 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1150 }
1151}
1152
1153static void pt_guest_exit(struct vcpu_vmx *vmx)
1154{
2ef7619d 1155 if (vmx_pt_mode_is_system())
2ef444f1
CP
1156 return;
1157
1158 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1159 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1160 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1161 }
1162
1163 /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1164 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1165}
1166
13b964a2
SC
1167void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1168 unsigned long fs_base, unsigned long gs_base)
1169{
1170 if (unlikely(fs_sel != host->fs_sel)) {
1171 if (!(fs_sel & 7))
1172 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1173 else
1174 vmcs_write16(HOST_FS_SELECTOR, 0);
1175 host->fs_sel = fs_sel;
1176 }
1177 if (unlikely(gs_sel != host->gs_sel)) {
1178 if (!(gs_sel & 7))
1179 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1180 else
1181 vmcs_write16(HOST_GS_SELECTOR, 0);
1182 host->gs_sel = gs_sel;
1183 }
1184 if (unlikely(fs_base != host->fs_base)) {
1185 vmcs_writel(HOST_FS_BASE, fs_base);
1186 host->fs_base = fs_base;
1187 }
1188 if (unlikely(gs_base != host->gs_base)) {
1189 vmcs_writel(HOST_GS_BASE, gs_base);
1190 host->gs_base = gs_base;
1191 }
1192}
1193
97b7ead3 1194void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
33ed6329 1195{
04d2cc77 1196 struct vcpu_vmx *vmx = to_vmx(vcpu);
d7ee039e 1197 struct vmcs_host_state *host_state;
51e8a8cc 1198#ifdef CONFIG_X86_64
35060ed6 1199 int cpu = raw_smp_processor_id();
51e8a8cc 1200#endif
e368b875
SC
1201 unsigned long fs_base, gs_base;
1202 u16 fs_sel, gs_sel;
26bb0981 1203 int i;
04d2cc77 1204
d264ee0c
SC
1205 vmx->req_immediate_exit = false;
1206
f48b4711
LA
1207 /*
1208 * Note that guest MSRs to be saved/restored can also be changed
1209 * when guest state is loaded. This happens when guest transitions
1210 * to/from long-mode by setting MSR_EFER.LMA.
1211 */
658ece84
SC
1212 if (!vmx->guest_uret_msrs_loaded) {
1213 vmx->guest_uret_msrs_loaded = true;
e9bb1ae9 1214 for (i = 0; i < vmx->nr_active_uret_msrs; ++i)
802145c5 1215 kvm_set_user_return_msr(vmx->guest_uret_msrs[i].slot,
eb3db1b1
SC
1216 vmx->guest_uret_msrs[i].data,
1217 vmx->guest_uret_msrs[i].mask);
f48b4711
LA
1218
1219 }
c9dfd3fb 1220
1221 if (vmx->nested.need_vmcs12_to_shadow_sync)
1222 nested_sync_vmcs12_to_shadow(vcpu);
1223
b464f57e 1224 if (vmx->guest_state_loaded)
33ed6329
AK
1225 return;
1226
b464f57e 1227 host_state = &vmx->loaded_vmcs->host_state;
bd9966de 1228
33ed6329
AK
1229 /*
1230 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1231 * allow segment selectors with cpl > 0 or ti == 1.
1232 */
d7ee039e 1233 host_state->ldt_sel = kvm_read_ldt();
42b933b5
VK
1234
1235#ifdef CONFIG_X86_64
d7ee039e
SC
1236 savesegment(ds, host_state->ds_sel);
1237 savesegment(es, host_state->es_sel);
e368b875
SC
1238
1239 gs_base = cpu_kernelmode_gs_base(cpu);
b062b794 1240 if (likely(is_64bit_mm(current->mm))) {
6758034e 1241 current_save_fsgs();
e368b875
SC
1242 fs_sel = current->thread.fsindex;
1243 gs_sel = current->thread.gsindex;
b062b794 1244 fs_base = current->thread.fsbase;
e368b875 1245 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
b062b794 1246 } else {
e368b875
SC
1247 savesegment(fs, fs_sel);
1248 savesegment(gs, gs_sel);
b062b794 1249 fs_base = read_msr(MSR_FS_BASE);
e368b875 1250 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
33ed6329 1251 }
b2da15ac 1252
4679b61f 1253 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
4fde8d57 1254#else
e368b875
SC
1255 savesegment(fs, fs_sel);
1256 savesegment(gs, gs_sel);
1257 fs_base = segment_base(fs_sel);
1258 gs_base = segment_base(gs_sel);
707c0874 1259#endif
e368b875 1260
13b964a2 1261 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
b464f57e 1262 vmx->guest_state_loaded = true;
33ed6329
AK
1263}
1264
6d6095bd 1265static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
33ed6329 1266{
d7ee039e
SC
1267 struct vmcs_host_state *host_state;
1268
b464f57e 1269 if (!vmx->guest_state_loaded)
33ed6329
AK
1270 return;
1271
b464f57e 1272 host_state = &vmx->loaded_vmcs->host_state;
bd9966de 1273
e1beb1d3 1274 ++vmx->vcpu.stat.host_state_reload;
bd9966de 1275
c8770e7b 1276#ifdef CONFIG_X86_64
4679b61f 1277 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
c8770e7b 1278#endif
d7ee039e
SC
1279 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1280 kvm_load_ldt(host_state->ldt_sel);
33ed6329 1281#ifdef CONFIG_X86_64
d7ee039e 1282 load_gs_index(host_state->gs_sel);
9581d442 1283#else
d7ee039e 1284 loadsegment(gs, host_state->gs_sel);
33ed6329 1285#endif
33ed6329 1286 }
d7ee039e
SC
1287 if (host_state->fs_sel & 7)
1288 loadsegment(fs, host_state->fs_sel);
b2da15ac 1289#ifdef CONFIG_X86_64
d7ee039e
SC
1290 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1291 loadsegment(ds, host_state->ds_sel);
1292 loadsegment(es, host_state->es_sel);
b2da15ac 1293 }
b2da15ac 1294#endif
b7ffc44d 1295 invalidate_tss_limit();
44ea2b17 1296#ifdef CONFIG_X86_64
c8770e7b 1297 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
44ea2b17 1298#endif
45fc8757 1299 load_fixmap_gdt(raw_smp_processor_id());
b464f57e 1300 vmx->guest_state_loaded = false;
658ece84 1301 vmx->guest_uret_msrs_loaded = false;
33ed6329
AK
1302}
1303
678e315e
SC
1304#ifdef CONFIG_X86_64
1305static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
a9b21b62 1306{
4679b61f 1307 preempt_disable();
b464f57e 1308 if (vmx->guest_state_loaded)
4679b61f
PB
1309 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1310 preempt_enable();
678e315e 1311 return vmx->msr_guest_kernel_gs_base;
a9b21b62
AK
1312}
1313
678e315e
SC
1314static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1315{
4679b61f 1316 preempt_disable();
b464f57e 1317 if (vmx->guest_state_loaded)
4679b61f
PB
1318 wrmsrl(MSR_KERNEL_GS_BASE, data);
1319 preempt_enable();
678e315e
SC
1320 vmx->msr_guest_kernel_gs_base = data;
1321}
1322#endif
1323
5c911bef
SC
1324void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1325 struct loaded_vmcs *buddy)
6aa8b732 1326{
a2fa3e9f 1327 struct vcpu_vmx *vmx = to_vmx(vcpu);
b80c76ec 1328 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
5c911bef 1329 struct vmcs *prev;
6aa8b732 1330
b80c76ec 1331 if (!already_loaded) {
fe0e80be 1332 loaded_vmcs_clear(vmx->loaded_vmcs);
92fe13be 1333 local_irq_disable();
5a560f8b
XG
1334
1335 /*
31603d4f
SC
1336 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1337 * this cpu's percpu list, otherwise it may not yet be deleted
1338 * from its previous cpu's percpu list. Pairs with the
1339 * smb_wmb() in __loaded_vmcs_clear().
5a560f8b
XG
1340 */
1341 smp_rmb();
1342
d462b819
NHE
1343 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1344 &per_cpu(loaded_vmcss_on_cpu, cpu));
92fe13be 1345 local_irq_enable();
b80c76ec
JM
1346 }
1347
5c911bef
SC
1348 prev = per_cpu(current_vmcs, cpu);
1349 if (prev != vmx->loaded_vmcs->vmcs) {
b80c76ec
JM
1350 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1351 vmcs_load(vmx->loaded_vmcs->vmcs);
5c911bef
SC
1352
1353 /*
1354 * No indirect branch prediction barrier needed when switching
1355 * the active VMCS within a guest, e.g. on nested VM-Enter.
1356 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1357 */
1358 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1359 indirect_branch_prediction_barrier();
b80c76ec
JM
1360 }
1361
1362 if (!already_loaded) {
59c58ceb 1363 void *gdt = get_current_gdt_ro();
b80c76ec
JM
1364 unsigned long sysenter_esp;
1365
eeeb4f67
SC
1366 /*
1367 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1368 * TLB entries from its previous association with the vCPU.
1369 */
b80c76ec 1370 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
92fe13be 1371
6aa8b732
AK
1372 /*
1373 * Linux uses per-cpu TSS and GDT, so set these when switching
e0c23063 1374 * processors. See 22.2.4.
6aa8b732 1375 */
e0c23063 1376 vmcs_writel(HOST_TR_BASE,
72f5e08d 1377 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
59c58ceb 1378 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
6aa8b732
AK
1379
1380 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1381 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
ff2c3a18 1382
d462b819 1383 vmx->loaded_vmcs->cpu = cpu;
6aa8b732 1384 }
28b835d6 1385
2680d6da
OH
1386 /* Setup TSC multiplier */
1387 if (kvm_has_tsc_control &&
c95ba92a
PF
1388 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1389 decache_tsc_multiplier(vmx);
8ef863e6
SC
1390}
1391
1392/*
1393 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1394 * vcpu mutex is already taken.
1395 */
1af1bb05 1396static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
8ef863e6
SC
1397{
1398 struct vcpu_vmx *vmx = to_vmx(vcpu);
1399
5c911bef 1400 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
2680d6da 1401
28b835d6 1402 vmx_vcpu_pi_load(vcpu, cpu);
8ef863e6 1403
74c55931 1404 vmx->host_debugctlmsr = get_debugctlmsr();
28b835d6
FW
1405}
1406
13b964a2 1407static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
6aa8b732 1408{
28b835d6
FW
1409 vmx_vcpu_pi_put(vcpu);
1410
6d6095bd 1411 vmx_prepare_switch_to_host(to_vmx(vcpu));
6aa8b732
AK
1412}
1413
f244deed
WL
1414static bool emulation_required(struct kvm_vcpu *vcpu)
1415{
2ba4493a 1416 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
f244deed
WL
1417}
1418
97b7ead3 1419unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
6aa8b732 1420{
e7bddc52 1421 struct vcpu_vmx *vmx = to_vmx(vcpu);
78ac8b47 1422 unsigned long rflags, save_rflags;
345dcaa8 1423
cb3c1e2f
SC
1424 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1425 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
6de12732 1426 rflags = vmcs_readl(GUEST_RFLAGS);
e7bddc52 1427 if (vmx->rmode.vm86_active) {
6de12732 1428 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
e7bddc52 1429 save_rflags = vmx->rmode.save_rflags;
6de12732
AK
1430 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1431 }
e7bddc52 1432 vmx->rflags = rflags;
78ac8b47 1433 }
e7bddc52 1434 return vmx->rflags;
6aa8b732
AK
1435}
1436
97b7ead3 1437void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
6aa8b732 1438{
e7bddc52 1439 struct vcpu_vmx *vmx = to_vmx(vcpu);
491c1ad1 1440 unsigned long old_rflags;
f244deed 1441
bddd82d1 1442 if (is_unrestricted_guest(vcpu)) {
cb3c1e2f 1443 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
491c1ad1
SC
1444 vmx->rflags = rflags;
1445 vmcs_writel(GUEST_RFLAGS, rflags);
1446 return;
1447 }
1448
1449 old_rflags = vmx_get_rflags(vcpu);
e7bddc52
SC
1450 vmx->rflags = rflags;
1451 if (vmx->rmode.vm86_active) {
1452 vmx->rmode.save_rflags = rflags;
053de044 1453 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
78ac8b47 1454 }
6aa8b732 1455 vmcs_writel(GUEST_RFLAGS, rflags);
f244deed 1456
e7bddc52
SC
1457 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1458 vmx->emulation_required = emulation_required(vcpu);
6aa8b732
AK
1459}
1460
97b7ead3 1461u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2809f5d2
GC
1462{
1463 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1464 int ret = 0;
1465
1466 if (interruptibility & GUEST_INTR_STATE_STI)
48005f64 1467 ret |= KVM_X86_SHADOW_INT_STI;
2809f5d2 1468 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
48005f64 1469 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2809f5d2 1470
37ccdcbe 1471 return ret;
2809f5d2
GC
1472}
1473
97b7ead3 1474void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2809f5d2
GC
1475{
1476 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1477 u32 interruptibility = interruptibility_old;
1478
1479 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1480
48005f64 1481 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2809f5d2 1482 interruptibility |= GUEST_INTR_STATE_MOV_SS;
48005f64 1483 else if (mask & KVM_X86_SHADOW_INT_STI)
2809f5d2
GC
1484 interruptibility |= GUEST_INTR_STATE_STI;
1485
1486 if ((interruptibility != interruptibility_old))
1487 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1488}
1489
bf8c55d8
CP
1490static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1491{
1492 struct vcpu_vmx *vmx = to_vmx(vcpu);
1493 unsigned long value;
1494
1495 /*
1496 * Any MSR write that attempts to change bits marked reserved will
1497 * case a #GP fault.
1498 */
1499 if (data & vmx->pt_desc.ctl_bitmask)
1500 return 1;
1501
1502 /*
1503 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1504 * result in a #GP unless the same write also clears TraceEn.
1505 */
1506 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1507 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1508 return 1;
1509
1510 /*
1511 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1512 * and FabricEn would cause #GP, if
1513 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1514 */
1515 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1516 !(data & RTIT_CTL_FABRIC_EN) &&
1517 !intel_pt_validate_cap(vmx->pt_desc.caps,
1518 PT_CAP_single_range_output))
1519 return 1;
1520
1521 /*
1522 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1523 * utilize encodings marked reserved will casue a #GP fault.
1524 */
1525 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1526 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1527 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1528 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1529 return 1;
1530 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1531 PT_CAP_cycle_thresholds);
1532 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1533 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1534 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1535 return 1;
1536 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1537 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1538 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1539 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1540 return 1;
1541
1542 /*
1543 * If ADDRx_CFG is reserved or the encodings is >2 will
1544 * cause a #GP fault.
1545 */
1546 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1547 if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1548 return 1;
1549 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1550 if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1551 return 1;
1552 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1553 if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1554 return 1;
1555 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1556 if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1557 return 1;
1558
1559 return 0;
1560}
1561
09e3e2a1
SC
1562static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
1563{
1564 return true;
1565}
1566
1957aa63 1567static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
6aa8b732 1568{
fede8076 1569 unsigned long rip, orig_rip;
6aa8b732 1570
1957aa63
SC
1571 /*
1572 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1573 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1574 * set when EPT misconfig occurs. In practice, real hardware updates
1575 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1576 * (namely Hyper-V) don't set it due to it being undefined behavior,
1577 * i.e. we end up advancing IP with some random value.
1578 */
1579 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
a6bdda1f 1580 to_vmx(vcpu)->exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
fede8076
PB
1581 orig_rip = kvm_rip_read(vcpu);
1582 rip = orig_rip + vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1583#ifdef CONFIG_X86_64
1584 /*
1585 * We need to mask out the high 32 bits of RIP if not in 64-bit
1586 * mode, but just finding out that we are in 64-bit mode is
1587 * quite expensive. Only do it if there was a carry.
1588 */
1589 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1590 rip = (u32)rip;
1591#endif
1957aa63
SC
1592 kvm_rip_write(vcpu, rip);
1593 } else {
1594 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1595 return 0;
1596 }
6aa8b732 1597
2809f5d2
GC
1598 /* skipping an emulated instruction also counts */
1599 vmx_set_interrupt_shadow(vcpu, 0);
f8ea7c60 1600
60fc3d02 1601 return 1;
f8ea7c60
VK
1602}
1603
5ef8acbd
OU
1604/*
1605 * Recognizes a pending MTF VM-exit and records the nested state for later
1606 * delivery.
1607 */
1608static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1609{
1610 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1611 struct vcpu_vmx *vmx = to_vmx(vcpu);
1612
1613 if (!is_guest_mode(vcpu))
1614 return;
1615
1616 /*
1617 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1618 * T-bit traps. As instruction emulation is completed (i.e. at the
1619 * instruction boundary), any #DB exception pending delivery must be a
1620 * debug-trap. Record the pending MTF state to be delivered in
1621 * vmx_check_nested_events().
1622 */
1623 if (nested_cpu_has_mtf(vmcs12) &&
1624 (!vcpu->arch.exception.pending ||
1625 vcpu->arch.exception.nr == DB_VECTOR))
1626 vmx->nested.mtf_pending = true;
1627 else
1628 vmx->nested.mtf_pending = false;
1629}
1630
1631static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1632{
1633 vmx_update_emulated_instruction(vcpu);
1634 return skip_emulated_instruction(vcpu);
1635}
1636
caa057a2
WL
1637static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1638{
1639 /*
1640 * Ensure that we clear the HLT state in the VMCS. We don't need to
1641 * explicitly skip the instruction because if the HLT state is set,
1642 * then the instruction is already executing and RIP has already been
1643 * advanced.
1644 */
1645 if (kvm_hlt_in_guest(vcpu->kvm) &&
1646 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1647 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1648}
1649
cfcd20e5 1650static void vmx_queue_exception(struct kvm_vcpu *vcpu)
298101da 1651{
77ab6db0 1652 struct vcpu_vmx *vmx = to_vmx(vcpu);
cfcd20e5
WL
1653 unsigned nr = vcpu->arch.exception.nr;
1654 bool has_error_code = vcpu->arch.exception.has_error_code;
cfcd20e5 1655 u32 error_code = vcpu->arch.exception.error_code;
8ab2d2e2 1656 u32 intr_info = nr | INTR_INFO_VALID_MASK;
77ab6db0 1657
da998b46
JM
1658 kvm_deliver_exception_payload(vcpu);
1659
8ab2d2e2 1660 if (has_error_code) {
77ab6db0 1661 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
8ab2d2e2
JK
1662 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1663 }
77ab6db0 1664
7ffd92c5 1665 if (vmx->rmode.vm86_active) {
71f9833b
SH
1666 int inc_eip = 0;
1667 if (kvm_exception_is_soft(nr))
1668 inc_eip = vcpu->arch.event_exit_inst_len;
9497e1f2 1669 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
77ab6db0
JK
1670 return;
1671 }
1672
add5ff7a
SC
1673 WARN_ON_ONCE(vmx->emulation_required);
1674
66fd3f7f
GN
1675 if (kvm_exception_is_soft(nr)) {
1676 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1677 vmx->vcpu.arch.event_exit_inst_len);
8ab2d2e2
JK
1678 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1679 } else
1680 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1681
1682 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
caa057a2
WL
1683
1684 vmx_clear_hlt(vcpu);
298101da
AK
1685}
1686
bd65ba82 1687static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr)
a75beee6 1688{
eb3db1b1 1689 struct vmx_uret_msr tmp;
bd65ba82 1690 int from, to;
a2fa3e9f 1691
bd65ba82
SC
1692 from = __vmx_find_uret_msr(vmx, msr);
1693 if (from < 0)
1694 return;
1695 to = vmx->nr_active_uret_msrs++;
a2fa3e9f 1696
eb3db1b1
SC
1697 tmp = vmx->guest_uret_msrs[to];
1698 vmx->guest_uret_msrs[to] = vmx->guest_uret_msrs[from];
1699 vmx->guest_uret_msrs[from] = tmp;
a75beee6
ED
1700}
1701
e38aea3e
AK
1702/*
1703 * Set up the vmcs to automatically save and restore system
1704 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
1705 * mode, as fiddling with msrs is very expensive.
1706 */
8b9cf98c 1707static void setup_msrs(struct vcpu_vmx *vmx)
e38aea3e 1708{
bd65ba82
SC
1709 vmx->guest_uret_msrs_loaded = false;
1710 vmx->nr_active_uret_msrs = 0;
a75beee6 1711#ifdef CONFIG_X86_64
84c8c5b8
JM
1712 /*
1713 * The SYSCALL MSRs are only needed on long mode guests, and only
1714 * when EFER.SCE is set.
1715 */
1716 if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
bd65ba82
SC
1717 vmx_setup_uret_msr(vmx, MSR_STAR);
1718 vmx_setup_uret_msr(vmx, MSR_LSTAR);
1719 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK);
a75beee6
ED
1720 }
1721#endif
bd65ba82
SC
1722 if (update_transition_efer(vmx))
1723 vmx_setup_uret_msr(vmx, MSR_EFER);
e38aea3e 1724
bd65ba82
SC
1725 if (guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1726 vmx_setup_uret_msr(vmx, MSR_TSC_AUX);
1727
1728 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL);
5897297b 1729
8d14695f 1730 if (cpu_has_vmx_msr_bitmap())
904e14fb 1731 vmx_update_msr_bitmap(&vmx->vcpu);
e38aea3e
AK
1732}
1733
326e7425 1734static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
6aa8b732 1735{
45c3af97
PB
1736 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1737 u64 g_tsc_offset = 0;
1738
1739 /*
1740 * We're here if L1 chose not to trap WRMSR to TSC. According
1741 * to the spec, this should set L1's TSC; The offset that L1
1742 * set for L2 remains unchanged, and still needs to be added
1743 * to the newly set TSC to get L2's TSC.
1744 */
1745 if (is_guest_mode(vcpu) &&
5e3d394f 1746 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
45c3af97 1747 g_tsc_offset = vmcs12->tsc_offset;
326e7425 1748
45c3af97
PB
1749 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1750 vcpu->arch.tsc_offset - g_tsc_offset,
1751 offset);
1752 vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1753 return offset + g_tsc_offset;
6aa8b732
AK
1754}
1755
801d3424
NHE
1756/*
1757 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1758 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1759 * all guests if the "nested" module option is off, and can also be disabled
1760 * for a single guest by disabling its VMX cpuid bit.
1761 */
7c97fcb3 1762bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
801d3424 1763{
d6321d49 1764 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
801d3424
NHE
1765}
1766
55d2375e
SC
1767static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1768 uint64_t val)
62cc6b9d 1769{
55d2375e 1770 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
62cc6b9d 1771
55d2375e 1772 return !(val & ~valid_bits);
62cc6b9d
DM
1773}
1774
55d2375e 1775static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
62cc6b9d 1776{
55d2375e
SC
1777 switch (msr->index) {
1778 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1779 if (!nested)
1780 return 1;
1781 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
27461da3
LX
1782 case MSR_IA32_PERF_CAPABILITIES:
1783 msr->data = vmx_get_perf_capabilities();
1784 return 0;
55d2375e 1785 default:
12bc2132 1786 return KVM_MSR_RET_INVALID;
55d2375e 1787 }
62cc6b9d
DM
1788}
1789
55d2375e
SC
1790/*
1791 * Reads an msr value (of 'msr_index') into 'pdata'.
1792 * Returns 0 on success, non-0 otherwise.
1793 * Assumes vcpu_load() was already called.
1794 */
1795static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
62cc6b9d 1796{
55d2375e 1797 struct vcpu_vmx *vmx = to_vmx(vcpu);
eb3db1b1 1798 struct vmx_uret_msr *msr;
bf8c55d8 1799 u32 index;
62cc6b9d 1800
55d2375e
SC
1801 switch (msr_info->index) {
1802#ifdef CONFIG_X86_64
1803 case MSR_FS_BASE:
1804 msr_info->data = vmcs_readl(GUEST_FS_BASE);
62cc6b9d 1805 break;
55d2375e
SC
1806 case MSR_GS_BASE:
1807 msr_info->data = vmcs_readl(GUEST_GS_BASE);
62cc6b9d 1808 break;
55d2375e
SC
1809 case MSR_KERNEL_GS_BASE:
1810 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
62cc6b9d 1811 break;
55d2375e
SC
1812#endif
1813 case MSR_EFER:
1814 return kvm_get_msr_common(vcpu, msr_info);
c11f83e0
PB
1815 case MSR_IA32_TSX_CTRL:
1816 if (!msr_info->host_initiated &&
1817 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1818 return 1;
eb3db1b1 1819 goto find_uret_msr;
6e3ba4ab
TX
1820 case MSR_IA32_UMWAIT_CONTROL:
1821 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1822 return 1;
1823
1824 msr_info->data = vmx->msr_ia32_umwait_control;
1825 break;
55d2375e
SC
1826 case MSR_IA32_SPEC_CTRL:
1827 if (!msr_info->host_initiated &&
39485ed9 1828 !guest_has_spec_ctrl_msr(vcpu))
55d2375e
SC
1829 return 1;
1830
1831 msr_info->data = to_vmx(vcpu)->spec_ctrl;
62cc6b9d 1832 break;
6aa8b732 1833 case MSR_IA32_SYSENTER_CS:
609e36d3 1834 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
6aa8b732
AK
1835 break;
1836 case MSR_IA32_SYSENTER_EIP:
609e36d3 1837 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
6aa8b732
AK
1838 break;
1839 case MSR_IA32_SYSENTER_ESP:
609e36d3 1840 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
6aa8b732 1841 break;
0dd376e7 1842 case MSR_IA32_BNDCFGS:
691bd434 1843 if (!kvm_mpx_supported() ||
d6321d49
RK
1844 (!msr_info->host_initiated &&
1845 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
93c4adc7 1846 return 1;
609e36d3 1847 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
0dd376e7 1848 break;
c45dcc71
AR
1849 case MSR_IA32_MCG_EXT_CTL:
1850 if (!msr_info->host_initiated &&
a6cb099a 1851 !(vmx->msr_ia32_feature_control &
32ad73db 1852 FEAT_CTL_LMCE_ENABLED))
cae50139 1853 return 1;
c45dcc71
AR
1854 msr_info->data = vcpu->arch.mcg_ext_ctl;
1855 break;
32ad73db 1856 case MSR_IA32_FEAT_CTL:
a6cb099a 1857 msr_info->data = vmx->msr_ia32_feature_control;
cae50139
JK
1858 break;
1859 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1860 if (!nested_vmx_allowed(vcpu))
1861 return 1;
31de3d25
VK
1862 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1863 &msr_info->data))
1864 return 1;
1865 /*
1866 * Enlightened VMCS v1 doesn't have certain fields, but buggy
1867 * Hyper-V versions are still trying to use corresponding
1868 * features when they are exposed. Filter out the essential
1869 * minimum.
1870 */
1871 if (!msr_info->host_initiated &&
1872 vmx->nested.enlightened_vmcs_enabled)
1873 nested_evmcs_filter_control_msr(msr_info->index,
1874 &msr_info->data);
1875 break;
bf8c55d8 1876 case MSR_IA32_RTIT_CTL:
2ef7619d 1877 if (!vmx_pt_mode_is_host_guest())
bf8c55d8
CP
1878 return 1;
1879 msr_info->data = vmx->pt_desc.guest.ctl;
1880 break;
1881 case MSR_IA32_RTIT_STATUS:
2ef7619d 1882 if (!vmx_pt_mode_is_host_guest())
bf8c55d8
CP
1883 return 1;
1884 msr_info->data = vmx->pt_desc.guest.status;
1885 break;
1886 case MSR_IA32_RTIT_CR3_MATCH:
2ef7619d 1887 if (!vmx_pt_mode_is_host_guest() ||
bf8c55d8
CP
1888 !intel_pt_validate_cap(vmx->pt_desc.caps,
1889 PT_CAP_cr3_filtering))
1890 return 1;
1891 msr_info->data = vmx->pt_desc.guest.cr3_match;
1892 break;
1893 case MSR_IA32_RTIT_OUTPUT_BASE:
2ef7619d 1894 if (!vmx_pt_mode_is_host_guest() ||
bf8c55d8
CP
1895 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1896 PT_CAP_topa_output) &&
1897 !intel_pt_validate_cap(vmx->pt_desc.caps,
1898 PT_CAP_single_range_output)))
1899 return 1;
1900 msr_info->data = vmx->pt_desc.guest.output_base;
1901 break;
1902 case MSR_IA32_RTIT_OUTPUT_MASK:
2ef7619d 1903 if (!vmx_pt_mode_is_host_guest() ||
bf8c55d8
CP
1904 (!intel_pt_validate_cap(vmx->pt_desc.caps,
1905 PT_CAP_topa_output) &&
1906 !intel_pt_validate_cap(vmx->pt_desc.caps,
1907 PT_CAP_single_range_output)))
1908 return 1;
1909 msr_info->data = vmx->pt_desc.guest.output_mask;
1910 break;
1911 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1912 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2ef7619d 1913 if (!vmx_pt_mode_is_host_guest() ||
bf8c55d8
CP
1914 (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1915 PT_CAP_num_address_ranges)))
1916 return 1;
1917 if (index % 2)
1918 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1919 else
1920 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1921 break;
4e47c7a6 1922 case MSR_TSC_AUX:
d6321d49
RK
1923 if (!msr_info->host_initiated &&
1924 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4e47c7a6 1925 return 1;
eb3db1b1 1926 goto find_uret_msr;
6aa8b732 1927 default:
eb3db1b1 1928 find_uret_msr:
d85a8034 1929 msr = vmx_find_uret_msr(vmx, msr_info->index);
3bab1f5d 1930 if (msr) {
609e36d3 1931 msr_info->data = msr->data;
3bab1f5d 1932 break;
6aa8b732 1933 }
609e36d3 1934 return kvm_get_msr_common(vcpu, msr_info);
6aa8b732
AK
1935 }
1936
6aa8b732
AK
1937 return 0;
1938}
1939
2408500d
SC
1940static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
1941 u64 data)
1942{
1943#ifdef CONFIG_X86_64
1944 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
1945 return (u32)data;
1946#endif
1947 return (unsigned long)data;
1948}
1949
6aa8b732 1950/*
311497e0 1951 * Writes msr value into the appropriate "register".
6aa8b732
AK
1952 * Returns 0 on success, non-0 otherwise.
1953 * Assumes vcpu_load() was already called.
1954 */
8fe8ab46 1955static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
6aa8b732 1956{
a2fa3e9f 1957 struct vcpu_vmx *vmx = to_vmx(vcpu);
eb3db1b1 1958 struct vmx_uret_msr *msr;
2cc51560 1959 int ret = 0;
8fe8ab46
WA
1960 u32 msr_index = msr_info->index;
1961 u64 data = msr_info->data;
bf8c55d8 1962 u32 index;
2cc51560 1963
6aa8b732 1964 switch (msr_index) {
3bab1f5d 1965 case MSR_EFER:
8fe8ab46 1966 ret = kvm_set_msr_common(vcpu, msr_info);
2cc51560 1967 break;
16175a79 1968#ifdef CONFIG_X86_64
6aa8b732 1969 case MSR_FS_BASE:
2fb92db1 1970 vmx_segment_cache_clear(vmx);
6aa8b732
AK
1971 vmcs_writel(GUEST_FS_BASE, data);
1972 break;
1973 case MSR_GS_BASE:
2fb92db1 1974 vmx_segment_cache_clear(vmx);
6aa8b732
AK
1975 vmcs_writel(GUEST_GS_BASE, data);
1976 break;
44ea2b17 1977 case MSR_KERNEL_GS_BASE:
678e315e 1978 vmx_write_guest_kernel_gs_base(vmx, data);
44ea2b17 1979 break;
6aa8b732
AK
1980#endif
1981 case MSR_IA32_SYSENTER_CS:
de70d279
SC
1982 if (is_guest_mode(vcpu))
1983 get_vmcs12(vcpu)->guest_sysenter_cs = data;
6aa8b732
AK
1984 vmcs_write32(GUEST_SYSENTER_CS, data);
1985 break;
1986 case MSR_IA32_SYSENTER_EIP:
2408500d
SC
1987 if (is_guest_mode(vcpu)) {
1988 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
de70d279 1989 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2408500d 1990 }
f5b42c33 1991 vmcs_writel(GUEST_SYSENTER_EIP, data);
6aa8b732
AK
1992 break;
1993 case MSR_IA32_SYSENTER_ESP:
2408500d
SC
1994 if (is_guest_mode(vcpu)) {
1995 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
de70d279 1996 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2408500d 1997 }
f5b42c33 1998 vmcs_writel(GUEST_SYSENTER_ESP, data);
6aa8b732 1999 break;
699a1ac2
SC
2000 case MSR_IA32_DEBUGCTLMSR:
2001 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2002 VM_EXIT_SAVE_DEBUG_CONTROLS)
2003 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2004
2005 ret = kvm_set_msr_common(vcpu, msr_info);
2006 break;
2007
0dd376e7 2008 case MSR_IA32_BNDCFGS:
691bd434 2009 if (!kvm_mpx_supported() ||
d6321d49
RK
2010 (!msr_info->host_initiated &&
2011 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
93c4adc7 2012 return 1;
fd8cb433 2013 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
4531662d 2014 (data & MSR_IA32_BNDCFGS_RSVD))
93c4adc7 2015 return 1;
0dd376e7
LJ
2016 vmcs_write64(GUEST_BNDCFGS, data);
2017 break;
6e3ba4ab
TX
2018 case MSR_IA32_UMWAIT_CONTROL:
2019 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2020 return 1;
2021
2022 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2023 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2024 return 1;
2025
2026 vmx->msr_ia32_umwait_control = data;
2027 break;
d28b387f
KA
2028 case MSR_IA32_SPEC_CTRL:
2029 if (!msr_info->host_initiated &&
39485ed9 2030 !guest_has_spec_ctrl_msr(vcpu))
d28b387f
KA
2031 return 1;
2032
841c2be0 2033 if (kvm_spec_ctrl_test_value(data))
d28b387f
KA
2034 return 1;
2035
2036 vmx->spec_ctrl = data;
d28b387f
KA
2037 if (!data)
2038 break;
2039
2040 /*
2041 * For non-nested:
2042 * When it's written (to non-zero) for the first time, pass
2043 * it through.
2044 *
2045 * For nested:
2046 * The handling of the MSR bitmap for L2 guests is done in
4d516fe7 2047 * nested_vmx_prepare_msr_bitmap. We should not touch the
d28b387f
KA
2048 * vmcs02.msr_bitmap here since it gets completely overwritten
2049 * in the merging. We update the vmcs01 here for L1 as well
2050 * since it will end up touching the MSR anyway now.
2051 */
476c9bd8 2052 vmx_disable_intercept_for_msr(vcpu,
d28b387f
KA
2053 MSR_IA32_SPEC_CTRL,
2054 MSR_TYPE_RW);
2055 break;
c11f83e0
PB
2056 case MSR_IA32_TSX_CTRL:
2057 if (!msr_info->host_initiated &&
2058 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2059 return 1;
2060 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2061 return 1;
eb3db1b1 2062 goto find_uret_msr;
15d45071
AR
2063 case MSR_IA32_PRED_CMD:
2064 if (!msr_info->host_initiated &&
39485ed9 2065 !guest_has_pred_cmd_msr(vcpu))
15d45071
AR
2066 return 1;
2067
2068 if (data & ~PRED_CMD_IBPB)
2069 return 1;
39485ed9 2070 if (!boot_cpu_has(X86_FEATURE_IBPB))
6441fa61 2071 return 1;
15d45071
AR
2072 if (!data)
2073 break;
2074
2075 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2076
2077 /*
2078 * For non-nested:
2079 * When it's written (to non-zero) for the first time, pass
2080 * it through.
2081 *
2082 * For nested:
2083 * The handling of the MSR bitmap for L2 guests is done in
4d516fe7 2084 * nested_vmx_prepare_msr_bitmap. We should not touch the
15d45071
AR
2085 * vmcs02.msr_bitmap here since it gets completely overwritten
2086 * in the merging.
2087 */
476c9bd8 2088 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
15d45071 2089 break;
468d472f 2090 case MSR_IA32_CR_PAT:
d28f4290
SC
2091 if (!kvm_pat_valid(data))
2092 return 1;
2093
142e4be7
SC
2094 if (is_guest_mode(vcpu) &&
2095 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2096 get_vmcs12(vcpu)->guest_ia32_pat = data;
2097
468d472f
SY
2098 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2099 vmcs_write64(GUEST_IA32_PAT, data);
2100 vcpu->arch.pat = data;
2101 break;
2102 }
8fe8ab46 2103 ret = kvm_set_msr_common(vcpu, msr_info);
4e47c7a6 2104 break;
ba904635
WA
2105 case MSR_IA32_TSC_ADJUST:
2106 ret = kvm_set_msr_common(vcpu, msr_info);
4e47c7a6 2107 break;
c45dcc71
AR
2108 case MSR_IA32_MCG_EXT_CTL:
2109 if ((!msr_info->host_initiated &&
2110 !(to_vmx(vcpu)->msr_ia32_feature_control &
32ad73db 2111 FEAT_CTL_LMCE_ENABLED)) ||
c45dcc71
AR
2112 (data & ~MCG_EXT_CTL_LMCE_EN))
2113 return 1;
2114 vcpu->arch.mcg_ext_ctl = data;
2115 break;
32ad73db 2116 case MSR_IA32_FEAT_CTL:
37e4c997 2117 if (!vmx_feature_control_msr_valid(vcpu, data) ||
3b84080b 2118 (to_vmx(vcpu)->msr_ia32_feature_control &
32ad73db 2119 FEAT_CTL_LOCKED && !msr_info->host_initiated))
cae50139 2120 return 1;
3b84080b 2121 vmx->msr_ia32_feature_control = data;
cae50139
JK
2122 if (msr_info->host_initiated && data == 0)
2123 vmx_leave_nested(vcpu);
2124 break;
2125 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
62cc6b9d
DM
2126 if (!msr_info->host_initiated)
2127 return 1; /* they are read-only */
2128 if (!nested_vmx_allowed(vcpu))
2129 return 1;
2130 return vmx_set_vmx_msr(vcpu, msr_index, data);
bf8c55d8 2131 case MSR_IA32_RTIT_CTL:
2ef7619d 2132 if (!vmx_pt_mode_is_host_guest() ||
ee85dec2
LK
2133 vmx_rtit_ctl_check(vcpu, data) ||
2134 vmx->nested.vmxon)
bf8c55d8
CP
2135 return 1;
2136 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2137 vmx->pt_desc.guest.ctl = data;
476c9bd8 2138 pt_update_intercept_for_msr(vcpu);
bf8c55d8
CP
2139 break;
2140 case MSR_IA32_RTIT_STATUS:
e348ac7c
SC
2141 if (!pt_can_write_msr(vmx))
2142 return 1;
2143 if (data & MSR_IA32_RTIT_STATUS_MASK)
bf8c55d8
CP
2144 return 1;
2145 vmx->pt_desc.guest.status = data;
2146 break;
2147 case MSR_IA32_RTIT_CR3_MATCH:
e348ac7c
SC
2148 if (!pt_can_write_msr(vmx))
2149 return 1;
2150 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2151 PT_CAP_cr3_filtering))
bf8c55d8
CP
2152 return 1;
2153 vmx->pt_desc.guest.cr3_match = data;
2154 break;
2155 case MSR_IA32_RTIT_OUTPUT_BASE:
e348ac7c
SC
2156 if (!pt_can_write_msr(vmx))
2157 return 1;
2158 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2159 PT_CAP_topa_output) &&
2160 !intel_pt_validate_cap(vmx->pt_desc.caps,
2161 PT_CAP_single_range_output))
2162 return 1;
1cc6cbc3 2163 if (!pt_output_base_valid(vcpu, data))
bf8c55d8
CP
2164 return 1;
2165 vmx->pt_desc.guest.output_base = data;
2166 break;
2167 case MSR_IA32_RTIT_OUTPUT_MASK:
e348ac7c
SC
2168 if (!pt_can_write_msr(vmx))
2169 return 1;
2170 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2171 PT_CAP_topa_output) &&
2172 !intel_pt_validate_cap(vmx->pt_desc.caps,
2173 PT_CAP_single_range_output))
bf8c55d8
CP
2174 return 1;
2175 vmx->pt_desc.guest.output_mask = data;
2176 break;
2177 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
e348ac7c
SC
2178 if (!pt_can_write_msr(vmx))
2179 return 1;
bf8c55d8 2180 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
e348ac7c
SC
2181 if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2182 PT_CAP_num_address_ranges))
bf8c55d8 2183 return 1;
fe6ed369 2184 if (is_noncanonical_address(data, vcpu))
bf8c55d8
CP
2185 return 1;
2186 if (index % 2)
2187 vmx->pt_desc.guest.addr_b[index / 2] = data;
2188 else
2189 vmx->pt_desc.guest.addr_a[index / 2] = data;
2190 break;
4e47c7a6 2191 case MSR_TSC_AUX:
d6321d49
RK
2192 if (!msr_info->host_initiated &&
2193 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4e47c7a6
SY
2194 return 1;
2195 /* Check reserved bit, higher 32 bits should be zero */
2196 if ((data >> 32) != 0)
2197 return 1;
eb3db1b1 2198 goto find_uret_msr;
c11f83e0 2199
6aa8b732 2200 default:
eb3db1b1 2201 find_uret_msr:
d85a8034 2202 msr = vmx_find_uret_msr(vmx, msr_index);
b07a5c53 2203 if (msr)
7bf662bb 2204 ret = vmx_set_guest_uret_msr(vmx, msr, data);
b07a5c53
PB
2205 else
2206 ret = kvm_set_msr_common(vcpu, msr_info);
6aa8b732
AK
2207 }
2208
2cc51560 2209 return ret;
6aa8b732
AK
2210}
2211
5fdbf976 2212static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
6aa8b732 2213{
f98c1e77
SC
2214 unsigned long guest_owned_bits;
2215
cb3c1e2f
SC
2216 kvm_register_mark_available(vcpu, reg);
2217
5fdbf976
MT
2218 switch (reg) {
2219 case VCPU_REGS_RSP:
2220 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2221 break;
2222 case VCPU_REGS_RIP:
2223 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2224 break;
6de4f3ad
AK
2225 case VCPU_EXREG_PDPTR:
2226 if (enable_ept)
2227 ept_save_pdptrs(vcpu);
2228 break;
bd31fe49
SC
2229 case VCPU_EXREG_CR0:
2230 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2231
2232 vcpu->arch.cr0 &= ~guest_owned_bits;
2233 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2234 break;
34059c25 2235 case VCPU_EXREG_CR3:
bddd82d1
KS
2236 if (is_unrestricted_guest(vcpu) ||
2237 (enable_ept && is_paging(vcpu)))
34059c25
SC
2238 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2239 break;
f98c1e77
SC
2240 case VCPU_EXREG_CR4:
2241 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2242
2243 vcpu->arch.cr4 &= ~guest_owned_bits;
2244 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2245 break;
5fdbf976 2246 default:
34059c25 2247 WARN_ON_ONCE(1);
5fdbf976
MT
2248 break;
2249 }
6aa8b732
AK
2250}
2251
6aa8b732
AK
2252static __init int cpu_has_kvm_support(void)
2253{
6210e37b 2254 return cpu_has_vmx();
6aa8b732
AK
2255}
2256
2257static __init int vmx_disabled_by_bios(void)
2258{
a4d0b2fd
SC
2259 return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2260 !boot_cpu_has(X86_FEATURE_VMX);
6aa8b732
AK
2261}
2262
4f6ea0a8 2263static int kvm_cpu_vmxon(u64 vmxon_pointer)
7725b894 2264{
4f6ea0a8
SC
2265 u64 msr;
2266
fe0e80be 2267 cr4_set_bits(X86_CR4_VMXE);
1c5ac21a
AS
2268 intel_pt_handle_vmx(1);
2269
4f6ea0a8
SC
2270 asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2271 _ASM_EXTABLE(1b, %l[fault])
2272 : : [vmxon_pointer] "m"(vmxon_pointer)
2273 : : fault);
2274 return 0;
2275
2276fault:
2277 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2278 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2279 intel_pt_handle_vmx(0);
2280 cr4_clear_bits(X86_CR4_VMXE);
2281
2282 return -EFAULT;
7725b894
DX
2283}
2284
13a34e06 2285static int hardware_enable(void)
6aa8b732
AK
2286{
2287 int cpu = raw_smp_processor_id();
2288 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
4f6ea0a8 2289 int r;
6aa8b732 2290
1e02ce4c 2291 if (cr4_read_shadow() & X86_CR4_VMXE)
10474ae8
AG
2292 return -EBUSY;
2293
773e8a04
VK
2294 /*
2295 * This can happen if we hot-added a CPU but failed to allocate
2296 * VP assist page for it.
2297 */
2298 if (static_branch_unlikely(&enable_evmcs) &&
2299 !hv_get_vp_assist_page(cpu))
2300 return -EFAULT;
2301
4f6ea0a8
SC
2302 r = kvm_cpu_vmxon(phys_addr);
2303 if (r)
2304 return r;
8f536b76 2305
fdf288bf
DH
2306 if (enable_ept)
2307 ept_sync_global();
10474ae8
AG
2308
2309 return 0;
6aa8b732
AK
2310}
2311
d462b819 2312static void vmclear_local_loaded_vmcss(void)
543e4243
AK
2313{
2314 int cpu = raw_smp_processor_id();
d462b819 2315 struct loaded_vmcs *v, *n;
543e4243 2316
d462b819
NHE
2317 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2318 loaded_vmcss_on_cpu_link)
2319 __loaded_vmcs_clear(v);
543e4243
AK
2320}
2321
710ff4a8
EH
2322
2323/* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2324 * tricks.
2325 */
2326static void kvm_cpu_vmxoff(void)
6aa8b732 2327{
4b1e5478 2328 asm volatile (__ex("vmxoff"));
1c5ac21a
AS
2329
2330 intel_pt_handle_vmx(0);
fe0e80be 2331 cr4_clear_bits(X86_CR4_VMXE);
6aa8b732
AK
2332}
2333
13a34e06 2334static void hardware_disable(void)
710ff4a8 2335{
fe0e80be
DH
2336 vmclear_local_loaded_vmcss();
2337 kvm_cpu_vmxoff();
710ff4a8
EH
2338}
2339
7a57c09b
SC
2340/*
2341 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2342 * directly instead of going through cpu_has(), to ensure KVM is trapping
2343 * ENCLS whenever it's supported in hardware. It does not matter whether
2344 * the host OS supports or has enabled SGX.
2345 */
2346static bool cpu_has_sgx(void)
2347{
2348 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2349}
2350
1c3d14fe 2351static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
d77c26fc 2352 u32 msr, u32 *result)
1c3d14fe
YS
2353{
2354 u32 vmx_msr_low, vmx_msr_high;
2355 u32 ctl = ctl_min | ctl_opt;
2356
2357 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2358
2359 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2360 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2361
2362 /* Ensure minimum (required) set of control bits are supported. */
2363 if (ctl_min & ~ctl)
002c7f7c 2364 return -EIO;
1c3d14fe
YS
2365
2366 *result = ctl;
2367 return 0;
2368}
2369
7caaa711
SC
2370static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2371 struct vmx_capability *vmx_cap)
6aa8b732
AK
2372{
2373 u32 vmx_msr_low, vmx_msr_high;
d56f546d 2374 u32 min, opt, min2, opt2;
1c3d14fe
YS
2375 u32 _pin_based_exec_control = 0;
2376 u32 _cpu_based_exec_control = 0;
f78e0e2e 2377 u32 _cpu_based_2nd_exec_control = 0;
1c3d14fe
YS
2378 u32 _vmexit_control = 0;
2379 u32 _vmentry_control = 0;
2380
1389309c 2381 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
10166744 2382 min = CPU_BASED_HLT_EXITING |
1c3d14fe
YS
2383#ifdef CONFIG_X86_64
2384 CPU_BASED_CR8_LOAD_EXITING |
2385 CPU_BASED_CR8_STORE_EXITING |
2386#endif
d56f546d
SY
2387 CPU_BASED_CR3_LOAD_EXITING |
2388 CPU_BASED_CR3_STORE_EXITING |
8eb73e2d 2389 CPU_BASED_UNCOND_IO_EXITING |
1c3d14fe 2390 CPU_BASED_MOV_DR_EXITING |
5e3d394f 2391 CPU_BASED_USE_TSC_OFFSETTING |
4d5422ce
WL
2392 CPU_BASED_MWAIT_EXITING |
2393 CPU_BASED_MONITOR_EXITING |
fee84b07
AK
2394 CPU_BASED_INVLPG_EXITING |
2395 CPU_BASED_RDPMC_EXITING;
443381a8 2396
f78e0e2e 2397 opt = CPU_BASED_TPR_SHADOW |
25c5f225 2398 CPU_BASED_USE_MSR_BITMAPS |
f78e0e2e 2399 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1c3d14fe
YS
2400 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2401 &_cpu_based_exec_control) < 0)
002c7f7c 2402 return -EIO;
6e5d865c
YS
2403#ifdef CONFIG_X86_64
2404 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2405 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2406 ~CPU_BASED_CR8_STORE_EXITING;
2407#endif
f78e0e2e 2408 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
d56f546d
SY
2409 min2 = 0;
2410 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
8d14695f 2411 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2384d2b3 2412 SECONDARY_EXEC_WBINVD_EXITING |
d56f546d 2413 SECONDARY_EXEC_ENABLE_VPID |
3a624e29 2414 SECONDARY_EXEC_ENABLE_EPT |
4b8d54f9 2415 SECONDARY_EXEC_UNRESTRICTED_GUEST |
4e47c7a6 2416 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
0367f205 2417 SECONDARY_EXEC_DESC |
7f3603b6 2418 SECONDARY_EXEC_ENABLE_RDTSCP |
83d4c286 2419 SECONDARY_EXEC_ENABLE_INVPCID |
c7c9c56c 2420 SECONDARY_EXEC_APIC_REGISTER_VIRT |
abc4fc58 2421 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
20300099 2422 SECONDARY_EXEC_SHADOW_VMCS |
843e4330 2423 SECONDARY_EXEC_XSAVES |
736fdf72
DH
2424 SECONDARY_EXEC_RDSEED_EXITING |
2425 SECONDARY_EXEC_RDRAND_EXITING |
8b3e34e4 2426 SECONDARY_EXEC_ENABLE_PML |
2a499e49 2427 SECONDARY_EXEC_TSC_SCALING |
e69e72fa 2428 SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
f99e3daf
CP
2429 SECONDARY_EXEC_PT_USE_GPA |
2430 SECONDARY_EXEC_PT_CONCEAL_VMX |
7a57c09b
SC
2431 SECONDARY_EXEC_ENABLE_VMFUNC;
2432 if (cpu_has_sgx())
2433 opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
d56f546d
SY
2434 if (adjust_vmx_controls(min2, opt2,
2435 MSR_IA32_VMX_PROCBASED_CTLS2,
f78e0e2e
SY
2436 &_cpu_based_2nd_exec_control) < 0)
2437 return -EIO;
2438 }
2439#ifndef CONFIG_X86_64
2440 if (!(_cpu_based_2nd_exec_control &
2441 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2442 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2443#endif
83d4c286
YZ
2444
2445 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2446 _cpu_based_2nd_exec_control &= ~(
8d14695f 2447 SECONDARY_EXEC_APIC_REGISTER_VIRT |
c7c9c56c
YZ
2448 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2449 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
83d4c286 2450
61f1dd90 2451 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
7caaa711 2452 &vmx_cap->ept, &vmx_cap->vpid);
61f1dd90 2453
d56f546d 2454 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
a7052897
MT
2455 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2456 enabled */
5fff7d27
GN
2457 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2458 CPU_BASED_CR3_STORE_EXITING |
2459 CPU_BASED_INVLPG_EXITING);
7caaa711
SC
2460 } else if (vmx_cap->ept) {
2461 vmx_cap->ept = 0;
61f1dd90
WL
2462 pr_warn_once("EPT CAP should not exist if not support "
2463 "1-setting enable EPT VM-execution control\n");
2464 }
2465 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
7caaa711
SC
2466 vmx_cap->vpid) {
2467 vmx_cap->vpid = 0;
61f1dd90
WL
2468 pr_warn_once("VPID CAP should not exist if not support "
2469 "1-setting enable VPID VM-execution control\n");
d56f546d 2470 }
1c3d14fe 2471
91fa0f8e 2472 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
1c3d14fe
YS
2473#ifdef CONFIG_X86_64
2474 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2475#endif
c73da3fc 2476 opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
c73da3fc
SC
2477 VM_EXIT_LOAD_IA32_PAT |
2478 VM_EXIT_LOAD_IA32_EFER |
f99e3daf
CP
2479 VM_EXIT_CLEAR_BNDCFGS |
2480 VM_EXIT_PT_CONCEAL_PIP |
2481 VM_EXIT_CLEAR_IA32_RTIT_CTL;
1c3d14fe
YS
2482 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2483 &_vmexit_control) < 0)
002c7f7c 2484 return -EIO;
1c3d14fe 2485
8a1b4392
PB
2486 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2487 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2488 PIN_BASED_VMX_PREEMPTION_TIMER;
01e439be
YZ
2489 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2490 &_pin_based_exec_control) < 0)
2491 return -EIO;
2492
1c17c3e6
PB
2493 if (cpu_has_broken_vmx_preemption_timer())
2494 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
01e439be 2495 if (!(_cpu_based_2nd_exec_control &
91fa0f8e 2496 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
01e439be
YZ
2497 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2498
c845f9c6 2499 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
c73da3fc
SC
2500 opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2501 VM_ENTRY_LOAD_IA32_PAT |
2502 VM_ENTRY_LOAD_IA32_EFER |
f99e3daf
CP
2503 VM_ENTRY_LOAD_BNDCFGS |
2504 VM_ENTRY_PT_CONCEAL_PIP |
2505 VM_ENTRY_LOAD_IA32_RTIT_CTL;
1c3d14fe
YS
2506 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2507 &_vmentry_control) < 0)
002c7f7c 2508 return -EIO;
6aa8b732 2509
c73da3fc
SC
2510 /*
2511 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2512 * can't be used due to an errata where VM Exit may incorrectly clear
2513 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the
2514 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2515 */
2516 if (boot_cpu_data.x86 == 0x6) {
2517 switch (boot_cpu_data.x86_model) {
2518 case 26: /* AAK155 */
2519 case 30: /* AAP115 */
2520 case 37: /* AAT100 */
2521 case 44: /* BC86,AAY89,BD102 */
2522 case 46: /* BA97 */
85ba2b16 2523 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
c73da3fc
SC
2524 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2525 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2526 "does not work properly. Using workaround\n");
2527 break;
2528 default:
2529 break;
2530 }
2531 }
2532
2533
c68876fd 2534 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
1c3d14fe
YS
2535
2536 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2537 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
002c7f7c 2538 return -EIO;
1c3d14fe
YS
2539
2540#ifdef CONFIG_X86_64
2541 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2542 if (vmx_msr_high & (1u<<16))
002c7f7c 2543 return -EIO;
1c3d14fe
YS
2544#endif
2545
2546 /* Require Write-Back (WB) memory type for VMCS accesses. */
2547 if (((vmx_msr_high >> 18) & 15) != 6)
002c7f7c 2548 return -EIO;
1c3d14fe 2549
002c7f7c 2550 vmcs_conf->size = vmx_msr_high & 0x1fff;
16cb0255 2551 vmcs_conf->order = get_order(vmcs_conf->size);
9ac7e3e8 2552 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
773e8a04 2553
2307af1c 2554 vmcs_conf->revision_id = vmx_msr_low;
1c3d14fe 2555
002c7f7c
YS
2556 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2557 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
f78e0e2e 2558 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
002c7f7c
YS
2559 vmcs_conf->vmexit_ctrl = _vmexit_control;
2560 vmcs_conf->vmentry_ctrl = _vmentry_control;
1c3d14fe 2561
064eedf2
VK
2562#if IS_ENABLED(CONFIG_HYPERV)
2563 if (enlightened_vmcs)
773e8a04 2564 evmcs_sanitize_exec_ctrls(vmcs_conf);
064eedf2 2565#endif
773e8a04 2566
1c3d14fe 2567 return 0;
c68876fd 2568}
6aa8b732 2569
41836839 2570struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
6aa8b732
AK
2571{
2572 int node = cpu_to_node(cpu);
2573 struct page *pages;
2574 struct vmcs *vmcs;
2575
41836839 2576 pages = __alloc_pages_node(node, flags, vmcs_config.order);
6aa8b732
AK
2577 if (!pages)
2578 return NULL;
2579 vmcs = page_address(pages);
1c3d14fe 2580 memset(vmcs, 0, vmcs_config.size);
2307af1c
LA
2581
2582 /* KVM supports Enlightened VMCS v1 only */
2583 if (static_branch_unlikely(&enable_evmcs))
392b2f25 2584 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2307af1c 2585 else
392b2f25 2586 vmcs->hdr.revision_id = vmcs_config.revision_id;
2307af1c 2587
491a6038
LA
2588 if (shadow)
2589 vmcs->hdr.shadow_vmcs = 1;
6aa8b732
AK
2590 return vmcs;
2591}
2592
89b0c9f5 2593void free_vmcs(struct vmcs *vmcs)
6aa8b732 2594{
1c3d14fe 2595 free_pages((unsigned long)vmcs, vmcs_config.order);
6aa8b732
AK
2596}
2597
d462b819
NHE
2598/*
2599 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2600 */
89b0c9f5 2601void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
d462b819
NHE
2602{
2603 if (!loaded_vmcs->vmcs)
2604 return;
2605 loaded_vmcs_clear(loaded_vmcs);
2606 free_vmcs(loaded_vmcs->vmcs);
2607 loaded_vmcs->vmcs = NULL;
904e14fb
PB
2608 if (loaded_vmcs->msr_bitmap)
2609 free_page((unsigned long)loaded_vmcs->msr_bitmap);
355f4fb1 2610 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
d462b819
NHE
2611}
2612
89b0c9f5 2613int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
f21f165e 2614{
491a6038 2615 loaded_vmcs->vmcs = alloc_vmcs(false);
f21f165e
PB
2616 if (!loaded_vmcs->vmcs)
2617 return -ENOMEM;
2618
d260f9ef
SC
2619 vmcs_clear(loaded_vmcs->vmcs);
2620
f21f165e 2621 loaded_vmcs->shadow_vmcs = NULL;
804939ea 2622 loaded_vmcs->hv_timer_soft_disabled = false;
d260f9ef
SC
2623 loaded_vmcs->cpu = -1;
2624 loaded_vmcs->launched = 0;
904e14fb
PB
2625
2626 if (cpu_has_vmx_msr_bitmap()) {
41836839
BG
2627 loaded_vmcs->msr_bitmap = (unsigned long *)
2628 __get_free_page(GFP_KERNEL_ACCOUNT);
904e14fb
PB
2629 if (!loaded_vmcs->msr_bitmap)
2630 goto out_vmcs;
2631 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
ceef7d10 2632
1f008e11
AB
2633 if (IS_ENABLED(CONFIG_HYPERV) &&
2634 static_branch_unlikely(&enable_evmcs) &&
ceef7d10
VK
2635 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2636 struct hv_enlightened_vmcs *evmcs =
2637 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2638
2639 evmcs->hv_enlightenments_control.msr_bitmap = 1;
2640 }
904e14fb 2641 }
d7ee039e
SC
2642
2643 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
3af80fec
SC
2644 memset(&loaded_vmcs->controls_shadow, 0,
2645 sizeof(struct vmcs_controls_shadow));
d7ee039e 2646
f21f165e 2647 return 0;
904e14fb
PB
2648
2649out_vmcs:
2650 free_loaded_vmcs(loaded_vmcs);
2651 return -ENOMEM;
f21f165e
PB
2652}
2653
39959588 2654static void free_kvm_area(void)
6aa8b732
AK
2655{
2656 int cpu;
2657
3230bb47 2658 for_each_possible_cpu(cpu) {
6aa8b732 2659 free_vmcs(per_cpu(vmxarea, cpu));
3230bb47
ZA
2660 per_cpu(vmxarea, cpu) = NULL;
2661 }
6aa8b732
AK
2662}
2663
6aa8b732
AK
2664static __init int alloc_kvm_area(void)
2665{
2666 int cpu;
2667
3230bb47 2668 for_each_possible_cpu(cpu) {
6aa8b732
AK
2669 struct vmcs *vmcs;
2670
41836839 2671 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
6aa8b732
AK
2672 if (!vmcs) {
2673 free_kvm_area();
2674 return -ENOMEM;
2675 }
2676
2307af1c
LA
2677 /*
2678 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2679 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2680 * revision_id reported by MSR_IA32_VMX_BASIC.
2681 *
312a4661 2682 * However, even though not explicitly documented by
2307af1c
LA
2683 * TLFS, VMXArea passed as VMXON argument should
2684 * still be marked with revision_id reported by
2685 * physical CPU.
2686 */
2687 if (static_branch_unlikely(&enable_evmcs))
392b2f25 2688 vmcs->hdr.revision_id = vmcs_config.revision_id;
2307af1c 2689
6aa8b732
AK
2690 per_cpu(vmxarea, cpu) = vmcs;
2691 }
2692 return 0;
2693}
2694
91b0aa2c 2695static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
d99e4152 2696 struct kvm_segment *save)
6aa8b732 2697{
d99e4152
GN
2698 if (!emulate_invalid_guest_state) {
2699 /*
2700 * CS and SS RPL should be equal during guest entry according
2701 * to VMX spec, but in reality it is not always so. Since vcpu
2702 * is in the middle of the transition from real mode to
2703 * protected mode it is safe to assume that RPL 0 is a good
2704 * default value.
2705 */
2706 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
b32a9918
NA
2707 save->selector &= ~SEGMENT_RPL_MASK;
2708 save->dpl = save->selector & SEGMENT_RPL_MASK;
d99e4152 2709 save->s = 1;
6aa8b732 2710 }
d99e4152 2711 vmx_set_segment(vcpu, save, seg);
6aa8b732
AK
2712}
2713
2714static void enter_pmode(struct kvm_vcpu *vcpu)
2715{
2716 unsigned long flags;
a89a8fb9 2717 struct vcpu_vmx *vmx = to_vmx(vcpu);
6aa8b732 2718
d99e4152
GN
2719 /*
2720 * Update real mode segment cache. It may be not up-to-date if sement
2721 * register was written while vcpu was in a guest mode.
2722 */
2723 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2724 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2725 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2726 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2727 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2728 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2729
7ffd92c5 2730 vmx->rmode.vm86_active = 0;
6aa8b732 2731
f5f7b2fe 2732 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
6aa8b732
AK
2733
2734 flags = vmcs_readl(GUEST_RFLAGS);
78ac8b47
AK
2735 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2736 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
6aa8b732
AK
2737 vmcs_writel(GUEST_RFLAGS, flags);
2738
66aee91a
RR
2739 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2740 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
6aa8b732
AK
2741
2742 update_exception_bitmap(vcpu);
2743
91b0aa2c
GN
2744 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2745 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2746 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2747 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2748 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2749 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
6aa8b732
AK
2750}
2751
f5f7b2fe 2752static void fix_rmode_seg(int seg, struct kvm_segment *save)
6aa8b732 2753{
772e0318 2754 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
d99e4152
GN
2755 struct kvm_segment var = *save;
2756
2757 var.dpl = 0x3;
2758 if (seg == VCPU_SREG_CS)
2759 var.type = 0x3;
2760
2761 if (!emulate_invalid_guest_state) {
2762 var.selector = var.base >> 4;
2763 var.base = var.base & 0xffff0;
2764 var.limit = 0xffff;
2765 var.g = 0;
2766 var.db = 0;
2767 var.present = 1;
2768 var.s = 1;
2769 var.l = 0;
2770 var.unusable = 0;
2771 var.type = 0x3;
2772 var.avl = 0;
2773 if (save->base & 0xf)
2774 printk_once(KERN_WARNING "kvm: segment base is not "
2775 "paragraph aligned when entering "
2776 "protected mode (seg=%d)", seg);
2777 }
6aa8b732 2778
d99e4152 2779 vmcs_write16(sf->selector, var.selector);
96794e4e 2780 vmcs_writel(sf->base, var.base);
d99e4152
GN
2781 vmcs_write32(sf->limit, var.limit);
2782 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
6aa8b732
AK
2783}
2784
2785static void enter_rmode(struct kvm_vcpu *vcpu)
2786{
2787 unsigned long flags;
a89a8fb9 2788 struct vcpu_vmx *vmx = to_vmx(vcpu);
40bbb9d0 2789 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
6aa8b732 2790
f5f7b2fe
AK
2791 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2792 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2793 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2794 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2795 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
c6ad1153
GN
2796 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2797 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
f5f7b2fe 2798
7ffd92c5 2799 vmx->rmode.vm86_active = 1;
6aa8b732 2800
776e58ea
GN
2801 /*
2802 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4918c6ca 2803 * vcpu. Warn the user that an update is overdue.
776e58ea 2804 */
40bbb9d0 2805 if (!kvm_vmx->tss_addr)
776e58ea
GN
2806 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2807 "called before entering vcpu\n");
776e58ea 2808
2fb92db1
AK
2809 vmx_segment_cache_clear(vmx);
2810
40bbb9d0 2811 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
6aa8b732 2812 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
6aa8b732
AK
2813 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2814
2815 flags = vmcs_readl(GUEST_RFLAGS);
78ac8b47 2816 vmx->rmode.save_rflags = flags;
6aa8b732 2817
053de044 2818 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
6aa8b732
AK
2819
2820 vmcs_writel(GUEST_RFLAGS, flags);
66aee91a 2821 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
6aa8b732
AK
2822 update_exception_bitmap(vcpu);
2823
d99e4152
GN
2824 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2825 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2826 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2827 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2828 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2829 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
b246dd5d 2830
8668a3c4 2831 kvm_mmu_reset_context(vcpu);
6aa8b732
AK
2832}
2833
72f211ec 2834int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
401d10de
AS
2835{
2836 struct vcpu_vmx *vmx = to_vmx(vcpu);
d85a8034 2837 struct vmx_uret_msr *msr = vmx_find_uret_msr(vmx, MSR_EFER);
26bb0981 2838
72f211ec 2839 /* Nothing to do if hardware doesn't support EFER. */
26bb0981 2840 if (!msr)
72f211ec 2841 return 0;
401d10de 2842
f6801dff 2843 vcpu->arch.efer = efer;
401d10de 2844 if (efer & EFER_LMA) {
2961e876 2845 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
401d10de
AS
2846 msr->data = efer;
2847 } else {
2961e876 2848 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
401d10de
AS
2849
2850 msr->data = efer & ~EFER_LME;
2851 }
2852 setup_msrs(vmx);
72f211ec 2853 return 0;
401d10de
AS
2854}
2855
05b3e0c2 2856#ifdef CONFIG_X86_64
6aa8b732
AK
2857
2858static void enter_lmode(struct kvm_vcpu *vcpu)
2859{
2860 u32 guest_tr_ar;
2861
2fb92db1
AK
2862 vmx_segment_cache_clear(to_vmx(vcpu));
2863
6aa8b732 2864 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4d283ec9 2865 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
bd80158a
JK
2866 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2867 __func__);
6aa8b732 2868 vmcs_write32(GUEST_TR_AR_BYTES,
4d283ec9
AL
2869 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2870 | VMX_AR_TYPE_BUSY_64_TSS);
6aa8b732 2871 }
da38f438 2872 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
6aa8b732
AK
2873}
2874
2875static void exit_lmode(struct kvm_vcpu *vcpu)
2876{
2961e876 2877 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
da38f438 2878 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
6aa8b732
AK
2879}
2880
2881#endif
2882
7780938c 2883static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
5058b692
SC
2884{
2885 struct vcpu_vmx *vmx = to_vmx(vcpu);
2886
2887 /*
7780938c
SC
2888 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
2889 * the CPU is not required to invalidate guest-physical mappings on
2890 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
2891 * associated with the root EPT structure and not any particular VPID
2892 * (INVVPID also isn't required to invalidate guest-physical mappings).
5058b692
SC
2893 */
2894 if (enable_ept) {
2895 ept_sync_global();
2896 } else if (enable_vpid) {
2897 if (cpu_has_vmx_invvpid_global()) {
2898 vpid_sync_vcpu_global();
2899 } else {
2900 vpid_sync_vcpu_single(vmx->vpid);
2901 vpid_sync_vcpu_single(vmx->nested.vpid02);
2902 }
2903 }
2904}
2905
33d19ec9
SC
2906static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
2907{
2a40b900
SC
2908 struct kvm_mmu *mmu = vcpu->arch.mmu;
2909 u64 root_hpa = mmu->root_hpa;
33d19ec9
SC
2910
2911 /* No flush required if the current context is invalid. */
2912 if (!VALID_PAGE(root_hpa))
2913 return;
2914
2915 if (enable_ept)
2a40b900
SC
2916 ept_sync_context(construct_eptp(vcpu, root_hpa,
2917 mmu->shadow_root_level));
33d19ec9
SC
2918 else if (!is_guest_mode(vcpu))
2919 vpid_sync_context(to_vmx(vcpu)->vpid);
2920 else
2921 vpid_sync_context(nested_get_vpid02(vcpu));
2922}
2923
faff8758
JS
2924static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2925{
faff8758 2926 /*
ad104b5e
SC
2927 * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
2928 * vmx_flush_tlb_guest() for an explanation of why this is ok.
faff8758 2929 */
ad104b5e 2930 vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
faff8758
JS
2931}
2932
e64419d9
SC
2933static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
2934{
2935 /*
2936 * vpid_sync_context() is a nop if vmx->vpid==0, e.g. if enable_vpid==0
2937 * or a vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit
2938 * are required to flush GVA->{G,H}PA mappings from the TLB if vpid is
2939 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
2940 * i.e. no explicit INVVPID is necessary.
2941 */
2942 vpid_sync_context(to_vmx(vcpu)->vpid);
2943}
2944
43fea4e4 2945void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
1439442c 2946{
d0d538b9
GN
2947 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2948
cb3c1e2f 2949 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
6de4f3ad
AK
2950 return;
2951
bf03d4f9 2952 if (is_pae_paging(vcpu)) {
d0d538b9
GN
2953 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2954 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2955 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2956 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
1439442c
SY
2957 }
2958}
2959
97b7ead3 2960void ept_save_pdptrs(struct kvm_vcpu *vcpu)
8f5d549f 2961{
d0d538b9
GN
2962 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2963
9932b49e
SC
2964 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
2965 return;
2966
2967 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2968 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2969 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2970 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
6de4f3ad 2971
cb3c1e2f 2972 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
8f5d549f
AK
2973}
2974
1439442c
SY
2975static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2976 unsigned long cr0,
2977 struct kvm_vcpu *vcpu)
2978{
2183f564
SC
2979 struct vcpu_vmx *vmx = to_vmx(vcpu);
2980
cb3c1e2f 2981 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
34059c25 2982 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
1439442c
SY
2983 if (!(cr0 & X86_CR0_PG)) {
2984 /* From paging/starting to nonpaging */
2183f564
SC
2985 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
2986 CPU_BASED_CR3_STORE_EXITING);
1439442c 2987 vcpu->arch.cr0 = cr0;
fc78f519 2988 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
1439442c
SY
2989 } else if (!is_paging(vcpu)) {
2990 /* From nonpaging to paging */
2183f564
SC
2991 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
2992 CPU_BASED_CR3_STORE_EXITING);
1439442c 2993 vcpu->arch.cr0 = cr0;
fc78f519 2994 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
1439442c 2995 }
95eb84a7
SY
2996
2997 if (!(cr0 & X86_CR0_WP))
2998 *hw_cr0 &= ~X86_CR0_WP;
1439442c
SY
2999}
3000
97b7ead3 3001void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
6aa8b732 3002{
7ffd92c5 3003 struct vcpu_vmx *vmx = to_vmx(vcpu);
3a624e29
NK
3004 unsigned long hw_cr0;
3005
3de6347b 3006 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
bddd82d1 3007 if (is_unrestricted_guest(vcpu))
5037878e 3008 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
218e763f 3009 else {
5037878e 3010 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
1439442c 3011
218e763f
GN
3012 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3013 enter_pmode(vcpu);
6aa8b732 3014
218e763f
GN
3015 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3016 enter_rmode(vcpu);
3017 }
6aa8b732 3018
05b3e0c2 3019#ifdef CONFIG_X86_64
f6801dff 3020 if (vcpu->arch.efer & EFER_LME) {
707d92fa 3021 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
6aa8b732 3022 enter_lmode(vcpu);
707d92fa 3023 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
6aa8b732
AK
3024 exit_lmode(vcpu);
3025 }
3026#endif
3027
bddd82d1 3028 if (enable_ept && !is_unrestricted_guest(vcpu))
1439442c
SY
3029 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3030
6aa8b732 3031 vmcs_writel(CR0_READ_SHADOW, cr0);
1439442c 3032 vmcs_writel(GUEST_CR0, hw_cr0);
ad312c7c 3033 vcpu->arch.cr0 = cr0;
bd31fe49 3034 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
14168786
GN
3035
3036 /* depends on vcpu->arch.cr0 to be set to a new value */
3037 vmx->emulation_required = emulation_required(vcpu);
6aa8b732
AK
3038}
3039
d468d94b 3040static int vmx_get_max_tdp_level(void)
855feb67 3041{
d468d94b 3042 if (cpu_has_vmx_ept_5levels())
855feb67
YZ
3043 return 5;
3044 return 4;
3045}
3046
2a40b900
SC
3047u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa,
3048 int root_level)
1439442c 3049{
855feb67
YZ
3050 u64 eptp = VMX_EPTP_MT_WB;
3051
2a40b900 3052 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
1439442c 3053
995f00a6
PF
3054 if (enable_ept_ad_bits &&
3055 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
bb97a016 3056 eptp |= VMX_EPTP_AD_ENABLE_BIT;
1439442c
SY
3057 eptp |= (root_hpa & PAGE_MASK);
3058
3059 return eptp;
3060}
3061
2a40b900
SC
3062static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, unsigned long pgd,
3063 int pgd_level)
6aa8b732 3064{
877ad952 3065 struct kvm *kvm = vcpu->kvm;
04f11ef4 3066 bool update_guest_cr3 = true;
1439442c
SY
3067 unsigned long guest_cr3;
3068 u64 eptp;
3069
089d034e 3070 if (enable_ept) {
2a40b900 3071 eptp = construct_eptp(vcpu, pgd, pgd_level);
1439442c 3072 vmcs_write64(EPT_POINTER, eptp);
877ad952 3073
afaf0b2f 3074 if (kvm_x86_ops.tlb_remote_flush) {
877ad952
TL
3075 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3076 to_vmx(vcpu)->ept_pointer = eptp;
3077 to_kvm_vmx(kvm)->ept_pointers_match
3078 = EPT_POINTERS_CHECK;
3079 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
3080 }
3081
df7e0681 3082 if (!enable_unrestricted_guest && !is_paging(vcpu))
877ad952 3083 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
b17b7436
SC
3084 else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3085 guest_cr3 = vcpu->arch.cr3;
3086 else /* vmcs01.GUEST_CR3 is already up-to-date. */
3087 update_guest_cr3 = false;
43fea4e4 3088 vmx_ept_load_pdptrs(vcpu);
be100ef1
SC
3089 } else {
3090 guest_cr3 = pgd;
1439442c
SY
3091 }
3092
04f11ef4
SC
3093 if (update_guest_cr3)
3094 vmcs_writel(GUEST_CR3, guest_cr3);
6aa8b732
AK
3095}
3096
c2fe3cd4
SC
3097static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3098{
3099 /*
3100 * We operate under the default treatment of SMM, so VMX cannot be
3101 * enabled under SMM. Note, whether or not VMXE is allowed at all is
ee69c92b 3102 * handled by kvm_is_valid_cr4().
c2fe3cd4
SC
3103 */
3104 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3105 return false;
3106
3107 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3108 return false;
3109
3110 return true;
3111}
3112
3113void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
6aa8b732 3114{
2259c17f 3115 unsigned long old_cr4 = vcpu->arch.cr4;
fe7f895d 3116 struct vcpu_vmx *vmx = to_vmx(vcpu);
085e68ee
BS
3117 /*
3118 * Pass through host's Machine Check Enable value to hw_cr4, which
3119 * is in force while we are in guest mode. Do not let guests control
3120 * this bit, even if host CR4.MCE == 0.
3121 */
5dc1f044
SC
3122 unsigned long hw_cr4;
3123
3124 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
bddd82d1 3125 if (is_unrestricted_guest(vcpu))
5dc1f044 3126 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
fe7f895d 3127 else if (vmx->rmode.vm86_active)
5dc1f044
SC
3128 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3129 else
3130 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
1439442c 3131
64f7a115
SC
3132 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3133 if (cr4 & X86_CR4_UMIP) {
fe7f895d 3134 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
64f7a115
SC
3135 hw_cr4 &= ~X86_CR4_UMIP;
3136 } else if (!is_guest_mode(vcpu) ||
fe7f895d
SC
3137 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3138 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3139 }
64f7a115 3140 }
0367f205 3141
ad312c7c 3142 vcpu->arch.cr4 = cr4;
f98c1e77 3143 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
5dc1f044 3144
bddd82d1 3145 if (!is_unrestricted_guest(vcpu)) {
5dc1f044
SC
3146 if (enable_ept) {
3147 if (!is_paging(vcpu)) {
3148 hw_cr4 &= ~X86_CR4_PAE;
3149 hw_cr4 |= X86_CR4_PSE;
3150 } else if (!(cr4 & X86_CR4_PAE)) {
3151 hw_cr4 &= ~X86_CR4_PAE;
3152 }
bc23008b 3153 }
1439442c 3154
656ec4a4 3155 /*
ddba2628
HH
3156 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3157 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3158 * to be manually disabled when guest switches to non-paging
3159 * mode.
3160 *
3161 * If !enable_unrestricted_guest, the CPU is always running
3162 * with CR0.PG=1 and CR4 needs to be modified.
3163 * If enable_unrestricted_guest, the CPU automatically
3164 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
656ec4a4 3165 */
5dc1f044
SC
3166 if (!is_paging(vcpu))
3167 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3168 }
656ec4a4 3169
1439442c
SY
3170 vmcs_writel(CR4_READ_SHADOW, cr4);
3171 vmcs_writel(GUEST_CR4, hw_cr4);
2259c17f
JM
3172
3173 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3174 kvm_update_cpuid_runtime(vcpu);
6aa8b732
AK
3175}
3176
97b7ead3 3177void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
6aa8b732 3178{
a9179499 3179 struct vcpu_vmx *vmx = to_vmx(vcpu);
6aa8b732
AK
3180 u32 ar;
3181
c6ad1153 3182 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
f5f7b2fe 3183 *var = vmx->rmode.segs[seg];
a9179499 3184 if (seg == VCPU_SREG_TR
2fb92db1 3185 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
f5f7b2fe 3186 return;
1390a28b
AK
3187 var->base = vmx_read_guest_seg_base(vmx, seg);
3188 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3189 return;
a9179499 3190 }
2fb92db1
AK
3191 var->base = vmx_read_guest_seg_base(vmx, seg);
3192 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3193 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3194 ar = vmx_read_guest_seg_ar(vmx, seg);
03617c18 3195 var->unusable = (ar >> 16) & 1;
6aa8b732
AK
3196 var->type = ar & 15;
3197 var->s = (ar >> 4) & 1;
3198 var->dpl = (ar >> 5) & 3;
03617c18
GN
3199 /*
3200 * Some userspaces do not preserve unusable property. Since usable
3201 * segment has to be present according to VMX spec we can use present
3202 * property to amend userspace bug by making unusable segment always
3203 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3204 * segment as unusable.
3205 */
3206 var->present = !var->unusable;
6aa8b732
AK
3207 var->avl = (ar >> 12) & 1;
3208 var->l = (ar >> 13) & 1;
3209 var->db = (ar >> 14) & 1;
3210 var->g = (ar >> 15) & 1;
6aa8b732
AK
3211}
3212
a9179499
AK
3213static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3214{
a9179499
AK
3215 struct kvm_segment s;
3216
3217 if (to_vmx(vcpu)->rmode.vm86_active) {
3218 vmx_get_segment(vcpu, &s, seg);
3219 return s.base;
3220 }
2fb92db1 3221 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
a9179499
AK
3222}
3223
97b7ead3 3224int vmx_get_cpl(struct kvm_vcpu *vcpu)
2e4d2653 3225{
b09408d0
MT
3226 struct vcpu_vmx *vmx = to_vmx(vcpu);
3227
ae9fedc7 3228 if (unlikely(vmx->rmode.vm86_active))
2e4d2653 3229 return 0;
ae9fedc7
PB
3230 else {
3231 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
4d283ec9 3232 return VMX_AR_DPL(ar);
69c73028 3233 }
69c73028
AK
3234}
3235
653e3108 3236static u32 vmx_segment_access_rights(struct kvm_segment *var)
6aa8b732 3237{
6aa8b732
AK
3238 u32 ar;
3239
f0495f9b 3240 if (var->unusable || !var->present)
6aa8b732
AK
3241 ar = 1 << 16;
3242 else {
3243 ar = var->type & 15;
3244 ar |= (var->s & 1) << 4;
3245 ar |= (var->dpl & 3) << 5;
3246 ar |= (var->present & 1) << 7;
3247 ar |= (var->avl & 1) << 12;
3248 ar |= (var->l & 1) << 13;
3249 ar |= (var->db & 1) << 14;
3250 ar |= (var->g & 1) << 15;
3251 }
653e3108
AK
3252
3253 return ar;
3254}
3255
97b7ead3 3256void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
653e3108 3257{
7ffd92c5 3258 struct vcpu_vmx *vmx = to_vmx(vcpu);
772e0318 3259 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
653e3108 3260
2fb92db1
AK
3261 vmx_segment_cache_clear(vmx);
3262
1ecd50a9
GN
3263 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3264 vmx->rmode.segs[seg] = *var;
3265 if (seg == VCPU_SREG_TR)
3266 vmcs_write16(sf->selector, var->selector);
3267 else if (var->s)
3268 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
d99e4152 3269 goto out;
653e3108 3270 }
1ecd50a9 3271
653e3108
AK
3272 vmcs_writel(sf->base, var->base);
3273 vmcs_write32(sf->limit, var->limit);
3274 vmcs_write16(sf->selector, var->selector);
3a624e29
NK
3275
3276 /*
3277 * Fix the "Accessed" bit in AR field of segment registers for older
3278 * qemu binaries.
3279 * IA32 arch specifies that at the time of processor reset the
3280 * "Accessed" bit in the AR field of segment registers is 1. And qemu
0fa06071 3281 * is setting it to 0 in the userland code. This causes invalid guest
3a624e29
NK
3282 * state vmexit when "unrestricted guest" mode is turned on.
3283 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3284 * tree. Newer qemu binaries with that qemu fix would not need this
3285 * kvm hack.
3286 */
bddd82d1 3287 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
f924d66d 3288 var->type |= 0x1; /* Accessed */
3a624e29 3289
f924d66d 3290 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
d99e4152
GN
3291
3292out:
98eb2f8b 3293 vmx->emulation_required = emulation_required(vcpu);
6aa8b732
AK
3294}
3295
6aa8b732
AK
3296static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3297{
2fb92db1 3298 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
6aa8b732
AK
3299
3300 *db = (ar >> 14) & 1;
3301 *l = (ar >> 13) & 1;
3302}
3303
89a27f4d 3304static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
6aa8b732 3305{
89a27f4d
GN
3306 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3307 dt->address = vmcs_readl(GUEST_IDTR_BASE);
6aa8b732
AK
3308}
3309
89a27f4d 3310static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
6aa8b732 3311{
89a27f4d
GN
3312 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3313 vmcs_writel(GUEST_IDTR_BASE, dt->address);
6aa8b732
AK
3314}
3315
89a27f4d 3316static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
6aa8b732 3317{
89a27f4d
GN
3318 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3319 dt->address = vmcs_readl(GUEST_GDTR_BASE);
6aa8b732
AK
3320}
3321
89a27f4d 3322static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
6aa8b732 3323{
89a27f4d
GN
3324 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3325 vmcs_writel(GUEST_GDTR_BASE, dt->address);
6aa8b732
AK
3326}
3327
648dfaa7
MG
3328static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3329{
3330 struct kvm_segment var;
3331 u32 ar;
3332
3333 vmx_get_segment(vcpu, &var, seg);
07f42f5f 3334 var.dpl = 0x3;
0647f4aa
GN
3335 if (seg == VCPU_SREG_CS)
3336 var.type = 0x3;
648dfaa7
MG
3337 ar = vmx_segment_access_rights(&var);
3338
3339 if (var.base != (var.selector << 4))
3340 return false;
89efbed0 3341 if (var.limit != 0xffff)
648dfaa7 3342 return false;
07f42f5f 3343 if (ar != 0xf3)
648dfaa7
MG
3344 return false;
3345
3346 return true;
3347}
3348
3349static bool code_segment_valid(struct kvm_vcpu *vcpu)
3350{
3351 struct kvm_segment cs;
3352 unsigned int cs_rpl;
3353
3354 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
b32a9918 3355 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
648dfaa7 3356
1872a3f4
AK
3357 if (cs.unusable)
3358 return false;
4d283ec9 3359 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
648dfaa7
MG
3360 return false;
3361 if (!cs.s)
3362 return false;
4d283ec9 3363 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
648dfaa7
MG
3364 if (cs.dpl > cs_rpl)
3365 return false;
1872a3f4 3366 } else {
648dfaa7
MG
3367 if (cs.dpl != cs_rpl)
3368 return false;
3369 }
3370 if (!cs.present)
3371 return false;
3372
3373 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3374 return true;
3375}
3376
3377static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3378{
3379 struct kvm_segment ss;
3380 unsigned int ss_rpl;
3381
3382 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
b32a9918 3383 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
648dfaa7 3384
1872a3f4
AK
3385 if (ss.unusable)
3386 return true;
3387 if (ss.type != 3 && ss.type != 7)
648dfaa7
MG
3388 return false;
3389 if (!ss.s)
3390 return false;
3391 if (ss.dpl != ss_rpl) /* DPL != RPL */
3392 return false;
3393 if (!ss.present)
3394 return false;
3395
3396 return true;
3397}
3398
3399static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3400{
3401 struct kvm_segment var;
3402 unsigned int rpl;
3403
3404 vmx_get_segment(vcpu, &var, seg);
b32a9918 3405 rpl = var.selector & SEGMENT_RPL_MASK;
648dfaa7 3406
1872a3f4
AK
3407 if (var.unusable)
3408 return true;
648dfaa7
MG
3409 if (!var.s)
3410 return false;
3411 if (!var.present)
3412 return false;
4d283ec9 3413 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
648dfaa7
MG
3414 if (var.dpl < rpl) /* DPL < RPL */
3415 return false;
3416 }
3417
3418 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3419 * rights flags
3420 */
3421 return true;
3422}
3423
3424static bool tr_valid(struct kvm_vcpu *vcpu)
3425{
3426 struct kvm_segment tr;
3427
3428 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3429
1872a3f4
AK
3430 if (tr.unusable)
3431 return false;
b32a9918 3432 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
648dfaa7 3433 return false;
1872a3f4 3434 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
648dfaa7
MG
3435 return false;
3436 if (!tr.present)
3437 return false;
3438
3439 return true;
3440}
3441
3442static bool ldtr_valid(struct kvm_vcpu *vcpu)
3443{
3444 struct kvm_segment ldtr;
3445
3446 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3447
1872a3f4
AK
3448 if (ldtr.unusable)
3449 return true;
b32a9918 3450 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
648dfaa7
MG
3451 return false;
3452 if (ldtr.type != 2)
3453 return false;
3454 if (!ldtr.present)
3455 return false;
3456
3457 return true;
3458}
3459
3460static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3461{
3462 struct kvm_segment cs, ss;
3463
3464 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3465 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3466
b32a9918
NA
3467 return ((cs.selector & SEGMENT_RPL_MASK) ==
3468 (ss.selector & SEGMENT_RPL_MASK));
648dfaa7
MG
3469}
3470
3471/*
3472 * Check if guest state is valid. Returns true if valid, false if
3473 * not.
3474 * We assume that registers are always usable
3475 */
2ba4493a 3476bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
648dfaa7
MG
3477{
3478 /* real mode guest state checks */
f13882d8 3479 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
648dfaa7
MG
3480 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3481 return false;
3482 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3483 return false;
3484 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3485 return false;
3486 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3487 return false;
3488 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3489 return false;
3490 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3491 return false;
3492 } else {
3493 /* protected mode guest state checks */
3494 if (!cs_ss_rpl_check(vcpu))
3495 return false;
3496 if (!code_segment_valid(vcpu))
3497 return false;
3498 if (!stack_segment_valid(vcpu))
3499 return false;
3500 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3501 return false;
3502 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3503 return false;
3504 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3505 return false;
3506 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3507 return false;
3508 if (!tr_valid(vcpu))
3509 return false;
3510 if (!ldtr_valid(vcpu))
3511 return false;
3512 }
3513 /* TODO:
3514 * - Add checks on RIP
3515 * - Add checks on RFLAGS
3516 */
3517
3518 return true;
3519}
3520
ff5a983c 3521static int init_rmode_tss(struct kvm *kvm, void __user *ua)
6aa8b732 3522{
ff5a983c
PX
3523 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3524 u16 data;
3525 int i;
3526
3527 for (i = 0; i < 3; i++) {
3528 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3529 return -EFAULT;
3530 }
6aa8b732 3531
195aefde 3532 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
ff5a983c
PX
3533 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3534 return -EFAULT;
3535
195aefde 3536 data = ~0;
ff5a983c
PX
3537 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3538 return -EFAULT;
3539
3540 return 0;
6aa8b732
AK
3541}
3542
b7ebfb05
SY
3543static int init_rmode_identity_map(struct kvm *kvm)
3544{
40bbb9d0 3545 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
2a5755bb 3546 int i, r = 0;
ff5a983c 3547 void __user *uaddr;
b7ebfb05
SY
3548 u32 tmp;
3549
40bbb9d0 3550 /* Protect kvm_vmx->ept_identity_pagetable_done. */
a255d479
TC
3551 mutex_lock(&kvm->slots_lock);
3552
40bbb9d0 3553 if (likely(kvm_vmx->ept_identity_pagetable_done))
2a5755bb 3554 goto out;
a255d479 3555
40bbb9d0
SC
3556 if (!kvm_vmx->ept_identity_map_addr)
3557 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
a255d479 3558
ff5a983c
PX
3559 uaddr = __x86_set_memory_region(kvm,
3560 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3561 kvm_vmx->ept_identity_map_addr,
3562 PAGE_SIZE);
3563 if (IS_ERR(uaddr)) {
3564 r = PTR_ERR(uaddr);
2a5755bb 3565 goto out;
ff5a983c 3566 }
a255d479 3567
b7ebfb05
SY
3568 /* Set up identity-mapping pagetable for EPT in real mode */
3569 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3570 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3571 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
ff5a983c
PX
3572 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3573 r = -EFAULT;
b7ebfb05 3574 goto out;
ff5a983c 3575 }
b7ebfb05 3576 }
40bbb9d0 3577 kvm_vmx->ept_identity_pagetable_done = true;
f51770ed 3578
b7ebfb05 3579out:
a255d479 3580 mutex_unlock(&kvm->slots_lock);
f51770ed 3581 return r;
b7ebfb05
SY
3582}
3583
6aa8b732
AK
3584static void seg_setup(int seg)
3585{
772e0318 3586 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3a624e29 3587 unsigned int ar;
6aa8b732
AK
3588
3589 vmcs_write16(sf->selector, 0);
3590 vmcs_writel(sf->base, 0);
3591 vmcs_write32(sf->limit, 0xffff);
d54d07b2
GN
3592 ar = 0x93;
3593 if (seg == VCPU_SREG_CS)
3594 ar |= 0x08; /* code segment */
3a624e29
NK
3595
3596 vmcs_write32(sf->ar_bytes, ar);
6aa8b732
AK
3597}
3598
f78e0e2e
SY
3599static int alloc_apic_access_page(struct kvm *kvm)
3600{
4484141a 3601 struct page *page;
ff5a983c
PX
3602 void __user *hva;
3603 int ret = 0;
f78e0e2e 3604
79fac95e 3605 mutex_lock(&kvm->slots_lock);
c24ae0dc 3606 if (kvm->arch.apic_access_page_done)
f78e0e2e 3607 goto out;
ff5a983c
PX
3608 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3609 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3610 if (IS_ERR(hva)) {
3611 ret = PTR_ERR(hva);
f78e0e2e 3612 goto out;
ff5a983c 3613 }
72dc67a6 3614
73a6d941 3615 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
4484141a 3616 if (is_error_page(page)) {
ff5a983c 3617 ret = -EFAULT;
4484141a
XG
3618 goto out;
3619 }
3620
c24ae0dc
TC
3621 /*
3622 * Do not pin the page in memory, so that memory hot-unplug
3623 * is able to migrate it.
3624 */
3625 put_page(page);
3626 kvm->arch.apic_access_page_done = true;
f78e0e2e 3627out:
79fac95e 3628 mutex_unlock(&kvm->slots_lock);
ff5a983c 3629 return ret;
f78e0e2e
SY
3630}
3631
97b7ead3 3632int allocate_vpid(void)
2384d2b3
SY
3633{
3634 int vpid;
3635
919818ab 3636 if (!enable_vpid)
991e7a0e 3637 return 0;
2384d2b3
SY
3638 spin_lock(&vmx_vpid_lock);
3639 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
991e7a0e 3640 if (vpid < VMX_NR_VPIDS)
2384d2b3 3641 __set_bit(vpid, vmx_vpid_bitmap);
991e7a0e
WL
3642 else
3643 vpid = 0;
2384d2b3 3644 spin_unlock(&vmx_vpid_lock);
991e7a0e 3645 return vpid;
2384d2b3
SY
3646}
3647
97b7ead3 3648void free_vpid(int vpid)
cdbecfc3 3649{
991e7a0e 3650 if (!enable_vpid || vpid == 0)
cdbecfc3
LJ
3651 return;
3652 spin_lock(&vmx_vpid_lock);
991e7a0e 3653 __clear_bit(vpid, vmx_vpid_bitmap);
cdbecfc3
LJ
3654 spin_unlock(&vmx_vpid_lock);
3655}
3656
3eb90017
AG
3657static void vmx_clear_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3658{
3659 int f = sizeof(unsigned long);
3660
3661 if (msr <= 0x1fff)
3662 __clear_bit(msr, msr_bitmap + 0x000 / f);
3663 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3664 __clear_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3665}
3666
3667static void vmx_clear_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3668{
3669 int f = sizeof(unsigned long);
3670
3671 if (msr <= 0x1fff)
3672 __clear_bit(msr, msr_bitmap + 0x800 / f);
3673 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3674 __clear_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3675}
3676
3677static void vmx_set_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
25c5f225 3678{
3e7c73e9 3679 int f = sizeof(unsigned long);
25c5f225 3680
3eb90017
AG
3681 if (msr <= 0x1fff)
3682 __set_bit(msr, msr_bitmap + 0x000 / f);
3683 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3684 __set_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3685}
3686
3687static void vmx_set_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3688{
3689 int f = sizeof(unsigned long);
3690
3691 if (msr <= 0x1fff)
3692 __set_bit(msr, msr_bitmap + 0x800 / f);
3693 else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3694 __set_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3695}
3696
476c9bd8 3697static __always_inline void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu,
904e14fb 3698 u32 msr, int type)
25c5f225 3699{
476c9bd8
AL
3700 struct vcpu_vmx *vmx = to_vmx(vcpu);
3701 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
25c5f225
SY
3702
3703 if (!cpu_has_vmx_msr_bitmap())
3704 return;
3705
ceef7d10
VK
3706 if (static_branch_unlikely(&enable_evmcs))
3707 evmcs_touch_msr_bitmap();
3708
25c5f225 3709 /*
3eb90017
AG
3710 * Mark the desired intercept state in shadow bitmap, this is needed
3711 * for resync when the MSR filters change.
3712 */
3713 if (is_valid_passthrough_msr(msr)) {
3714 int idx = possible_passthrough_msr_slot(msr);
3715
3716 if (idx != -ENOENT) {
3717 if (type & MSR_TYPE_R)
3718 clear_bit(idx, vmx->shadow_msr_intercept.read);
3719 if (type & MSR_TYPE_W)
3720 clear_bit(idx, vmx->shadow_msr_intercept.write);
3721 }
3722 }
8d14695f 3723
3eb90017
AG
3724 if ((type & MSR_TYPE_R) &&
3725 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3726 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3727 type &= ~MSR_TYPE_R;
3728 }
8d14695f 3729
3eb90017
AG
3730 if ((type & MSR_TYPE_W) &&
3731 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3732 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3733 type &= ~MSR_TYPE_W;
3734 }
8d14695f 3735
3eb90017
AG
3736 if (type & MSR_TYPE_R)
3737 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
8d14695f 3738
3eb90017
AG
3739 if (type & MSR_TYPE_W)
3740 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
8d14695f
YZ
3741}
3742
476c9bd8 3743static __always_inline void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu,
904e14fb
PB
3744 u32 msr, int type)
3745{
476c9bd8
AL
3746 struct vcpu_vmx *vmx = to_vmx(vcpu);
3747 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
904e14fb
PB
3748
3749 if (!cpu_has_vmx_msr_bitmap())
3750 return;
3751
ceef7d10
VK
3752 if (static_branch_unlikely(&enable_evmcs))
3753 evmcs_touch_msr_bitmap();
3754
904e14fb 3755 /*
3eb90017
AG
3756 * Mark the desired intercept state in shadow bitmap, this is needed
3757 * for resync when the MSR filter changes.
3758 */
3759 if (is_valid_passthrough_msr(msr)) {
3760 int idx = possible_passthrough_msr_slot(msr);
3761
3762 if (idx != -ENOENT) {
3763 if (type & MSR_TYPE_R)
3764 set_bit(idx, vmx->shadow_msr_intercept.read);
3765 if (type & MSR_TYPE_W)
3766 set_bit(idx, vmx->shadow_msr_intercept.write);
3767 }
3768 }
904e14fb 3769
3eb90017
AG
3770 if (type & MSR_TYPE_R)
3771 vmx_set_msr_bitmap_read(msr_bitmap, msr);
904e14fb 3772
3eb90017
AG
3773 if (type & MSR_TYPE_W)
3774 vmx_set_msr_bitmap_write(msr_bitmap, msr);
904e14fb
PB
3775}
3776
476c9bd8
AL
3777static __always_inline void vmx_set_intercept_for_msr(struct kvm_vcpu *vcpu,
3778 u32 msr, int type, bool value)
904e14fb
PB
3779{
3780 if (value)
476c9bd8 3781 vmx_enable_intercept_for_msr(vcpu, msr, type);
904e14fb 3782 else
476c9bd8 3783 vmx_disable_intercept_for_msr(vcpu, msr, type);
904e14fb
PB
3784}
3785
904e14fb 3786static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
5897297b 3787{
904e14fb
PB
3788 u8 mode = 0;
3789
3790 if (cpu_has_secondary_exec_ctrls() &&
fe7f895d 3791 (secondary_exec_controls_get(to_vmx(vcpu)) &
904e14fb
PB
3792 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3793 mode |= MSR_BITMAP_MODE_X2APIC;
3794 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3795 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3796 }
3797
904e14fb 3798 return mode;
8d14695f
YZ
3799}
3800
9389b9d5 3801static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
8d14695f 3802{
9389b9d5
SC
3803 unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3804 unsigned long read_intercept;
904e14fb
PB
3805 int msr;
3806
9389b9d5
SC
3807 read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3808
904e14fb 3809 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
9389b9d5
SC
3810 unsigned int read_idx = msr / BITS_PER_LONG;
3811 unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3eb90017 3812
9389b9d5
SC
3813 msr_bitmap[read_idx] = read_intercept;
3814 msr_bitmap[write_idx] = ~0ul;
904e14fb 3815 }
9389b9d5 3816}
904e14fb 3817
9389b9d5
SC
3818static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu, u8 mode)
3819{
3820 if (!cpu_has_vmx_msr_bitmap())
3821 return;
3822
3823 vmx_reset_x2apic_msrs(vcpu, mode);
3824
3825 /*
3826 * TPR reads and writes can be virtualized even if virtual interrupt
3827 * delivery is not in use.
3828 */
3829 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
3830 !(mode & MSR_BITMAP_MODE_X2APIC));
3831
3832 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3833 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
3834 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3835 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
f6e90f9e 3836 }
5897297b
AK
3837}
3838
97b7ead3 3839void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
904e14fb
PB
3840{
3841 struct vcpu_vmx *vmx = to_vmx(vcpu);
904e14fb
PB
3842 u8 mode = vmx_msr_bitmap_mode(vcpu);
3843 u8 changed = mode ^ vmx->msr_bitmap_mode;
3844
3845 if (!changed)
3846 return;
3847
904e14fb 3848 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3eb90017 3849 vmx_update_msr_bitmap_x2apic(vcpu, mode);
904e14fb
PB
3850
3851 vmx->msr_bitmap_mode = mode;
3852}
3853
476c9bd8 3854void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
b08c2896 3855{
476c9bd8 3856 struct vcpu_vmx *vmx = to_vmx(vcpu);
b08c2896
CP
3857 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3858 u32 i;
3859
476c9bd8
AL
3860 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
3861 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
3862 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
3863 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
b08c2896 3864 for (i = 0; i < vmx->pt_desc.addr_range; i++) {
476c9bd8
AL
3865 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3866 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
b08c2896
CP
3867 }
3868}
3869
e6c67d8c
LA
3870static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3871{
3872 struct vcpu_vmx *vmx = to_vmx(vcpu);
3873 void *vapic_page;
3874 u32 vppr;
3875 int rvi;
3876
3877 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3878 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
96c66e87 3879 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
e6c67d8c
LA
3880 return false;
3881
7e712684 3882 rvi = vmx_get_rvi();
e6c67d8c 3883
96c66e87 3884 vapic_page = vmx->nested.virtual_apic_map.hva;
e6c67d8c 3885 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
e6c67d8c
LA
3886
3887 return ((rvi & 0xf0) > (vppr & 0xf0));
3888}
3889
3eb90017
AG
3890static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
3891{
3892 struct vcpu_vmx *vmx = to_vmx(vcpu);
3893 u32 i;
3894
3895 /*
3896 * Set intercept permissions for all potentially passed through MSRs
3897 * again. They will automatically get filtered through the MSR filter,
3898 * so we are back in sync after this.
3899 */
3900 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
3901 u32 msr = vmx_possible_passthrough_msrs[i];
3902 bool read = test_bit(i, vmx->shadow_msr_intercept.read);
3903 bool write = test_bit(i, vmx->shadow_msr_intercept.write);
3904
3905 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_R, read);
3906 vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_W, write);
3907 }
3908
3909 pt_update_intercept_for_msr(vcpu);
3910 vmx_update_msr_bitmap_x2apic(vcpu, vmx_msr_bitmap_mode(vcpu));
3911}
3912
06a5524f
WV
3913static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3914 bool nested)
21bc8dc5
RK
3915{
3916#ifdef CONFIG_SMP
06a5524f
WV
3917 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3918
21bc8dc5 3919 if (vcpu->mode == IN_GUEST_MODE) {
28b835d6 3920 /*
5753743f
HZ
3921 * The vector of interrupt to be delivered to vcpu had
3922 * been set in PIR before this function.
3923 *
3924 * Following cases will be reached in this block, and
3925 * we always send a notification event in all cases as
3926 * explained below.
3927 *
3928 * Case 1: vcpu keeps in non-root mode. Sending a
3929 * notification event posts the interrupt to vcpu.
3930 *
3931 * Case 2: vcpu exits to root mode and is still
3932 * runnable. PIR will be synced to vIRR before the
3933 * next vcpu entry. Sending a notification event in
3934 * this case has no effect, as vcpu is not in root
3935 * mode.
28b835d6 3936 *
5753743f
HZ
3937 * Case 3: vcpu exits to root mode and is blocked.
3938 * vcpu_block() has already synced PIR to vIRR and
3939 * never blocks vcpu if vIRR is not cleared. Therefore,
3940 * a blocked vcpu here does not wait for any requested
3941 * interrupts in PIR, and sending a notification event
3942 * which has no effect is safe here.
28b835d6 3943 */
28b835d6 3944
06a5524f 3945 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
21bc8dc5
RK
3946 return true;
3947 }
3948#endif
3949 return false;
3950}
3951
705699a1
WV
3952static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3953 int vector)
3954{
3955 struct vcpu_vmx *vmx = to_vmx(vcpu);
3956
3957 if (is_guest_mode(vcpu) &&
3958 vector == vmx->nested.posted_intr_nv) {
705699a1
WV
3959 /*
3960 * If a posted intr is not recognized by hardware,
3961 * we will accomplish it in the next vmentry.
3962 */
3963 vmx->nested.pi_pending = true;
3964 kvm_make_request(KVM_REQ_EVENT, vcpu);
6b697711
LA
3965 /* the PIR and ON have been set by L1. */
3966 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3967 kvm_vcpu_kick(vcpu);
705699a1
WV
3968 return 0;
3969 }
3970 return -1;
3971}
a20ed54d
YZ
3972/*
3973 * Send interrupt to vcpu via posted interrupt way.
3974 * 1. If target vcpu is running(non-root mode), send posted interrupt
3975 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3976 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3977 * interrupt from PIR in next vmentry.
3978 */
91a5f413 3979static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
a20ed54d
YZ
3980{
3981 struct vcpu_vmx *vmx = to_vmx(vcpu);
3982 int r;
3983
705699a1
WV
3984 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3985 if (!r)
91a5f413
VK
3986 return 0;
3987
3988 if (!vcpu->arch.apicv_active)
3989 return -1;
705699a1 3990
a20ed54d 3991 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
91a5f413 3992 return 0;
a20ed54d 3993
b95234c8
PB
3994 /* If a previous notification has sent the IPI, nothing to do. */
3995 if (pi_test_and_set_on(&vmx->pi_desc))
91a5f413 3996 return 0;
b95234c8 3997
379a3c8e
WL
3998 if (vcpu != kvm_get_running_vcpu() &&
3999 !kvm_vcpu_trigger_posted_interrupt(vcpu, false))
a20ed54d 4000 kvm_vcpu_kick(vcpu);
91a5f413
VK
4001
4002 return 0;
a20ed54d
YZ
4003}
4004
a3a8ff8e
NHE
4005/*
4006 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4007 * will not change in the lifetime of the guest.
4008 * Note that host-state that does change is set elsewhere. E.g., host-state
4009 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4010 */
97b7ead3 4011void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
a3a8ff8e
NHE
4012{
4013 u32 low32, high32;
4014 unsigned long tmpl;
d6e41f11 4015 unsigned long cr0, cr3, cr4;
a3a8ff8e 4016
04ac88ab
AL
4017 cr0 = read_cr0();
4018 WARN_ON(cr0 & X86_CR0_TS);
4019 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
d6e41f11
AL
4020
4021 /*
4022 * Save the most likely value for this task's CR3 in the VMCS.
4023 * We can't use __get_current_cr3_fast() because we're not atomic.
4024 */
6c690ee1 4025 cr3 = __read_cr3();
d6e41f11 4026 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
d7ee039e 4027 vmx->loaded_vmcs->host_state.cr3 = cr3;
a3a8ff8e 4028
d974baa3 4029 /* Save the most likely value for this task's CR4 in the VMCS. */
1e02ce4c 4030 cr4 = cr4_read_shadow();
d974baa3 4031 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
d7ee039e 4032 vmx->loaded_vmcs->host_state.cr4 = cr4;
d974baa3 4033
a3a8ff8e 4034 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
b2da15ac
AK
4035#ifdef CONFIG_X86_64
4036 /*
4037 * Load null selectors, so we can avoid reloading them in
6d6095bd
SC
4038 * vmx_prepare_switch_to_host(), in case userspace uses
4039 * the null selectors too (the expected case).
b2da15ac
AK
4040 */
4041 vmcs_write16(HOST_DS_SELECTOR, 0);
4042 vmcs_write16(HOST_ES_SELECTOR, 0);
4043#else
a3a8ff8e
NHE
4044 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4045 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
b2da15ac 4046#endif
a3a8ff8e
NHE
4047 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4048 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4049
2342080c 4050 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
a3a8ff8e 4051
453eafbe 4052 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
a3a8ff8e
NHE
4053
4054 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4055 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4056 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4057 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4058
4059 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4060 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4061 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4062 }
5a5e8a15 4063
c73da3fc 4064 if (cpu_has_load_ia32_efer())
5a5e8a15 4065 vmcs_write64(HOST_IA32_EFER, host_efer);
a3a8ff8e
NHE
4066}
4067
97b7ead3 4068void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
bf8179a0 4069{
2ed41aa6
SC
4070 struct kvm_vcpu *vcpu = &vmx->vcpu;
4071
4072 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4073 ~vcpu->arch.cr4_guest_rsvd_bits;
fa71e952 4074 if (!enable_ept)
2ed41aa6 4075 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PGE;
fe3ef05c 4076 if (is_guest_mode(&vmx->vcpu))
2ed41aa6
SC
4077 vcpu->arch.cr4_guest_owned_bits &=
4078 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4079 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
bf8179a0
NHE
4080}
4081
c075c3e4 4082u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
01e439be
YZ
4083{
4084 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4085
d62caabb 4086 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
01e439be 4087 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
d02fcf50
PB
4088
4089 if (!enable_vnmi)
4090 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4091
804939ea
SC
4092 if (!enable_preemption_timer)
4093 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4094
01e439be
YZ
4095 return pin_based_exec_ctrl;
4096}
4097
d62caabb
AS
4098static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4099{
4100 struct vcpu_vmx *vmx = to_vmx(vcpu);
4101
c5f2c766 4102 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
3ce424e4
RK
4103 if (cpu_has_secondary_exec_ctrls()) {
4104 if (kvm_vcpu_apicv_active(vcpu))
fe7f895d 4105 secondary_exec_controls_setbit(vmx,
3ce424e4
RK
4106 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4107 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4108 else
fe7f895d 4109 secondary_exec_controls_clearbit(vmx,
3ce424e4
RK
4110 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4111 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4112 }
4113
4114 if (cpu_has_vmx_msr_bitmap())
904e14fb 4115 vmx_update_msr_bitmap(vcpu);
d62caabb
AS
4116}
4117
89b0c9f5
SC
4118u32 vmx_exec_control(struct vcpu_vmx *vmx)
4119{
4120 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4121
4122 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4123 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4124
4125 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4126 exec_control &= ~CPU_BASED_TPR_SHADOW;
4127#ifdef CONFIG_X86_64
4128 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4129 CPU_BASED_CR8_LOAD_EXITING;
4130#endif
4131 }
4132 if (!enable_ept)
4133 exec_control |= CPU_BASED_CR3_STORE_EXITING |
4134 CPU_BASED_CR3_LOAD_EXITING |
4135 CPU_BASED_INVLPG_EXITING;
4136 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4137 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4138 CPU_BASED_MONITOR_EXITING);
4139 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4140 exec_control &= ~CPU_BASED_HLT_EXITING;
4141 return exec_control;
4142}
4143
8b50b92f
SC
4144/*
4145 * Adjust a single secondary execution control bit to intercept/allow an
4146 * instruction in the guest. This is usually done based on whether or not a
4147 * feature has been exposed to the guest in order to correctly emulate faults.
4148 */
4149static inline void
4150vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4151 u32 control, bool enabled, bool exiting)
4152{
4153 /*
4154 * If the control is for an opt-in feature, clear the control if the
4155 * feature is not exposed to the guest, i.e. not enabled. If the
4156 * control is opt-out, i.e. an exiting control, clear the control if
4157 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4158 * disabled for the associated instruction. Note, the caller is
4159 * responsible presetting exec_control to set all supported bits.
4160 */
4161 if (enabled == exiting)
4162 *exec_control &= ~control;
4163
4164 /*
4165 * Update the nested MSR settings so that a nested VMM can/can't set
4166 * controls for features that are/aren't exposed to the guest.
4167 */
4168 if (nested) {
4169 if (enabled)
4170 vmx->nested.msrs.secondary_ctls_high |= control;
4171 else
4172 vmx->nested.msrs.secondary_ctls_high &= ~control;
4173 }
4174}
4175
4176/*
4177 * Wrapper macro for the common case of adjusting a secondary execution control
4178 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4179 * verifies that the control is actually supported by KVM and hardware.
4180 */
4181#define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4182({ \
4183 bool __enabled; \
4184 \
4185 if (cpu_has_vmx_##name()) { \
4186 __enabled = guest_cpuid_has(&(vmx)->vcpu, \
4187 X86_FEATURE_##feat_name); \
4188 vmx_adjust_secondary_exec_control(vmx, exec_control, \
4189 SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4190 } \
4191})
4192
4193/* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4194#define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4195 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4196
4197#define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4198 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
89b0c9f5 4199
80154d77 4200static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
bf8179a0 4201{
80154d77
PB
4202 struct kvm_vcpu *vcpu = &vmx->vcpu;
4203
bf8179a0 4204 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
0367f205 4205
2ef7619d 4206 if (vmx_pt_mode_is_system())
f99e3daf 4207 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
80154d77 4208 if (!cpu_need_virtualize_apic_accesses(vcpu))
bf8179a0
NHE
4209 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4210 if (vmx->vpid == 0)
4211 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4212 if (!enable_ept) {
4213 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4214 enable_unrestricted_guest = 0;
4215 }
4216 if (!enable_unrestricted_guest)
4217 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
b31c114b 4218 if (kvm_pause_in_guest(vmx->vcpu.kvm))
bf8179a0 4219 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
80154d77 4220 if (!kvm_vcpu_apicv_active(vcpu))
c7c9c56c
YZ
4221 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4222 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
8d14695f 4223 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
0367f205
PB
4224
4225 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4226 * in vmx_set_cr4. */
4227 exec_control &= ~SECONDARY_EXEC_DESC;
4228
abc4fc58
AG
4229 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4230 (handle_vmptrld).
4231 We can NOT enable shadow_vmcs here because we don't have yet
4232 a current VMCS12
4233 */
4234 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
a3eaa864
KH
4235
4236 if (!enable_pml)
4237 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
843e4330 4238
becdad85 4239 if (cpu_has_vmx_xsaves()) {
3db13480
PB
4240 /* Exposing XSAVES only when XSAVE is exposed */
4241 bool xsaves_enabled =
96be4e06 4242 boot_cpu_has(X86_FEATURE_XSAVE) &&
3db13480
PB
4243 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4244 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4245
7204160e
AL
4246 vcpu->arch.xsaves_enabled = xsaves_enabled;
4247
8b50b92f
SC
4248 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4249 SECONDARY_EXEC_XSAVES,
4250 xsaves_enabled, false);
45ec368c
JM
4251 }
4252
8b50b92f 4253 vmx_adjust_sec_exec_feature(vmx, &exec_control, rdtscp, RDTSCP);
75f4fc8d 4254
b936d3eb
SC
4255 /*
4256 * Expose INVPCID if and only if PCID is also exposed to the guest.
4257 * INVPCID takes a #UD when it's disabled in the VMCS, but a #GP or #PF
4258 * if CR4.PCIDE=0. Enumerating CPUID.INVPCID=1 would lead to incorrect
4259 * behavior from the guest perspective (it would expect #GP or #PF).
4260 */
4261 if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
4262 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
8b50b92f 4263 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
75f4fc8d 4264
e69e72fa 4265
8b50b92f
SC
4266 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4267 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
e69e72fa 4268
8b50b92f
SC
4269 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4270 ENABLE_USR_WAIT_PAUSE, false);
e69e72fa 4271
80154d77 4272 vmx->secondary_exec_control = exec_control;
bf8179a0
NHE
4273}
4274
ce88decf
XG
4275static void ept_set_mmio_spte_mask(void)
4276{
4277 /*
4278 * EPT Misconfigurations can be generated if the value of bits 2:0
4279 * of an EPT paging-structure entry is 110b (write/execute).
ce88decf 4280 */
e7581cac 4281 kvm_mmu_set_mmio_spte_mask(VMX_EPT_MISCONFIG_WX_VALUE, 0);
ce88decf
XG
4282}
4283
f53cd63c 4284#define VMX_XSS_EXIT_BITMAP 0
6aa8b732 4285
944c3464 4286/*
1b84292b
XL
4287 * Noting that the initialization of Guest-state Area of VMCS is in
4288 * vmx_vcpu_reset().
944c3464 4289 */
1b84292b 4290static void init_vmcs(struct vcpu_vmx *vmx)
944c3464 4291{
944c3464 4292 if (nested)
1b84292b 4293 nested_vmx_set_vmcs_shadowing_bitmap();
944c3464 4294
25c5f225 4295 if (cpu_has_vmx_msr_bitmap())
904e14fb 4296 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
25c5f225 4297
6aa8b732
AK
4298 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4299
6aa8b732 4300 /* Control */
3af80fec 4301 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
6e5d865c 4302
3af80fec 4303 exec_controls_set(vmx, vmx_exec_control(vmx));
6aa8b732 4304
dfa169bb 4305 if (cpu_has_secondary_exec_ctrls()) {
80154d77 4306 vmx_compute_secondary_exec_control(vmx);
3af80fec 4307 secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
dfa169bb 4308 }
f78e0e2e 4309
d62caabb 4310 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
c7c9c56c
YZ
4311 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4312 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4313 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4314 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4315
4316 vmcs_write16(GUEST_INTR_STATUS, 0);
01e439be 4317
0bcf261c 4318 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
01e439be 4319 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
c7c9c56c
YZ
4320 }
4321
b31c114b 4322 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4b8d54f9 4323 vmcs_write32(PLE_GAP, ple_gap);
a7653ecd
RK
4324 vmx->ple_window = ple_window;
4325 vmx->ple_window_dirty = true;
4b8d54f9
ZE
4326 }
4327
c3707958
XG
4328 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4329 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
6aa8b732
AK
4330 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4331
9581d442
AK
4332 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4333 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
a547c6db 4334 vmx_set_constant_host_state(vmx);
6aa8b732
AK
4335 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4336 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
6aa8b732 4337
2a499e49
BD
4338 if (cpu_has_vmx_vmfunc())
4339 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4340
2cc51560
ED
4341 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4342 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
33966dd6 4343 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
2cc51560 4344 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
33966dd6 4345 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
6aa8b732 4346
74545705
RK
4347 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4348 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
468d472f 4349
3af80fec 4350 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
6aa8b732
AK
4351
4352 /* 22.2.1, 20.8.1 */
3af80fec 4353 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
1c3d14fe 4354
fa71e952
SC
4355 vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4356 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
bd7e5b08 4357
bf8179a0 4358 set_cr4_guest_host_mask(vmx);
e00c8cf2 4359
35fbe0d4
XL
4360 if (vmx->vpid != 0)
4361 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4362
becdad85 4363 if (cpu_has_vmx_xsaves())
f53cd63c
WL
4364 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4365
4e59516a 4366 if (enable_pml) {
4e59516a
PF
4367 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4368 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4369 }
0b665d30
SC
4370
4371 if (cpu_has_vmx_encls_vmexit())
4372 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
2ef444f1 4373
2ef7619d 4374 if (vmx_pt_mode_is_host_guest()) {
2ef444f1
CP
4375 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4376 /* Bit[6~0] are forced to 1, writes are ignored. */
4377 vmx->pt_desc.guest.output_mask = 0x7F;
4378 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4379 }
e00c8cf2
AK
4380}
4381
d28bc9dd 4382static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
e00c8cf2
AK
4383{
4384 struct vcpu_vmx *vmx = to_vmx(vcpu);
58cb628d 4385 struct msr_data apic_base_msr;
d28bc9dd 4386 u64 cr0;
e00c8cf2 4387
7ffd92c5 4388 vmx->rmode.vm86_active = 0;
d28b387f 4389 vmx->spec_ctrl = 0;
e00c8cf2 4390
6e3ba4ab
TX
4391 vmx->msr_ia32_umwait_control = 0;
4392
ad312c7c 4393 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
95c06540 4394 vmx->hv_deadline_tsc = -1;
d28bc9dd
NA
4395 kvm_set_cr8(vcpu, 0);
4396
4397 if (!init_event) {
4398 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4399 MSR_IA32_APICBASE_ENABLE;
4400 if (kvm_vcpu_is_reset_bsp(vcpu))
4401 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4402 apic_base_msr.host_initiated = true;
4403 kvm_set_apic_base(vcpu, &apic_base_msr);
4404 }
e00c8cf2 4405
2fb92db1
AK
4406 vmx_segment_cache_clear(vmx);
4407
5706be0d 4408 seg_setup(VCPU_SREG_CS);
66450a21 4409 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
f3531054 4410 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
e00c8cf2
AK
4411
4412 seg_setup(VCPU_SREG_DS);
4413 seg_setup(VCPU_SREG_ES);
4414 seg_setup(VCPU_SREG_FS);
4415 seg_setup(VCPU_SREG_GS);
4416 seg_setup(VCPU_SREG_SS);
4417
4418 vmcs_write16(GUEST_TR_SELECTOR, 0);
4419 vmcs_writel(GUEST_TR_BASE, 0);
4420 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4421 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4422
4423 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4424 vmcs_writel(GUEST_LDTR_BASE, 0);
4425 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4426 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4427
d28bc9dd
NA
4428 if (!init_event) {
4429 vmcs_write32(GUEST_SYSENTER_CS, 0);
4430 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4431 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4432 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4433 }
e00c8cf2 4434
c37c2873 4435 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
66450a21 4436 kvm_rip_write(vcpu, 0xfff0);
e00c8cf2 4437
e00c8cf2
AK
4438 vmcs_writel(GUEST_GDTR_BASE, 0);
4439 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4440
4441 vmcs_writel(GUEST_IDTR_BASE, 0);
4442 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4443
443381a8 4444 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
e00c8cf2 4445 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
f3531054 4446 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
a554d207
WL
4447 if (kvm_mpx_supported())
4448 vmcs_write64(GUEST_BNDCFGS, 0);
e00c8cf2 4449
e00c8cf2
AK
4450 setup_msrs(vmx);
4451
6aa8b732
AK
4452 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4453
d28bc9dd 4454 if (cpu_has_vmx_tpr_shadow() && !init_event) {
f78e0e2e 4455 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
35754c98 4456 if (cpu_need_tpr_shadow(vcpu))
f78e0e2e 4457 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
d28bc9dd 4458 __pa(vcpu->arch.apic->regs));
f78e0e2e
SY
4459 vmcs_write32(TPR_THRESHOLD, 0);
4460 }
4461
a73896cb 4462 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6aa8b732 4463
d28bc9dd 4464 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
d28bc9dd 4465 vmx->vcpu.arch.cr0 = cr0;
f2463247 4466 vmx_set_cr0(vcpu, cr0); /* enter rmode */
d28bc9dd 4467 vmx_set_cr4(vcpu, 0);
5690891b 4468 vmx_set_efer(vcpu, 0);
bd7e5b08 4469
d28bc9dd 4470 update_exception_bitmap(vcpu);
6aa8b732 4471
dd5f5341 4472 vpid_sync_context(vmx->vpid);
caa057a2
WL
4473 if (init_event)
4474 vmx_clear_hlt(vcpu);
6aa8b732
AK
4475}
4476
55d2375e 4477static void enable_irq_window(struct kvm_vcpu *vcpu)
3b86cd99 4478{
9dadc2f9 4479 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
3b86cd99
JK
4480}
4481
c9a7953f 4482static void enable_nmi_window(struct kvm_vcpu *vcpu)
3b86cd99 4483{
d02fcf50 4484 if (!enable_vnmi ||
8a1b4392 4485 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
c9a7953f
JK
4486 enable_irq_window(vcpu);
4487 return;
4488 }
3b86cd99 4489
4e2a0bc5 4490 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
3b86cd99
JK
4491}
4492
66fd3f7f 4493static void vmx_inject_irq(struct kvm_vcpu *vcpu)
85f455f7 4494{
9c8cba37 4495 struct vcpu_vmx *vmx = to_vmx(vcpu);
66fd3f7f
GN
4496 uint32_t intr;
4497 int irq = vcpu->arch.interrupt.nr;
9c8cba37 4498
229456fc 4499 trace_kvm_inj_virq(irq);
2714d1d3 4500
fa89a817 4501 ++vcpu->stat.irq_injections;
7ffd92c5 4502 if (vmx->rmode.vm86_active) {
71f9833b
SH
4503 int inc_eip = 0;
4504 if (vcpu->arch.interrupt.soft)
4505 inc_eip = vcpu->arch.event_exit_inst_len;
9497e1f2 4506 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
85f455f7
ED
4507 return;
4508 }
66fd3f7f
GN
4509 intr = irq | INTR_INFO_VALID_MASK;
4510 if (vcpu->arch.interrupt.soft) {
4511 intr |= INTR_TYPE_SOFT_INTR;
4512 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4513 vmx->vcpu.arch.event_exit_inst_len);
4514 } else
4515 intr |= INTR_TYPE_EXT_INTR;
4516 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
caa057a2
WL
4517
4518 vmx_clear_hlt(vcpu);
85f455f7
ED
4519}
4520
f08864b4
SY
4521static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4522{
66a5a347
JK
4523 struct vcpu_vmx *vmx = to_vmx(vcpu);
4524
d02fcf50 4525 if (!enable_vnmi) {
8a1b4392
PB
4526 /*
4527 * Tracking the NMI-blocked state in software is built upon
4528 * finding the next open IRQ window. This, in turn, depends on
4529 * well-behaving guests: They have to keep IRQs disabled at
4530 * least as long as the NMI handler runs. Otherwise we may
4531 * cause NMI nesting, maybe breaking the guest. But as this is
4532 * highly unlikely, we can live with the residual risk.
4533 */
4534 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4535 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4536 }
4537
4c4a6f79
PB
4538 ++vcpu->stat.nmi_injections;
4539 vmx->loaded_vmcs->nmi_known_unmasked = false;
3b86cd99 4540
7ffd92c5 4541 if (vmx->rmode.vm86_active) {
9497e1f2 4542 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
66a5a347
JK
4543 return;
4544 }
c5a6d5f7 4545
f08864b4
SY
4546 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4547 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
caa057a2
WL
4548
4549 vmx_clear_hlt(vcpu);
f08864b4
SY
4550}
4551
97b7ead3 4552bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
3cfc3092 4553{
4c4a6f79
PB
4554 struct vcpu_vmx *vmx = to_vmx(vcpu);
4555 bool masked;
4556
d02fcf50 4557 if (!enable_vnmi)
8a1b4392 4558 return vmx->loaded_vmcs->soft_vnmi_blocked;
4c4a6f79 4559 if (vmx->loaded_vmcs->nmi_known_unmasked)
9d58b931 4560 return false;
4c4a6f79
PB
4561 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4562 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4563 return masked;
3cfc3092
JK
4564}
4565
97b7ead3 4566void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
3cfc3092
JK
4567{
4568 struct vcpu_vmx *vmx = to_vmx(vcpu);
4569
d02fcf50 4570 if (!enable_vnmi) {
8a1b4392
PB
4571 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4572 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4573 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4574 }
4575 } else {
4576 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4577 if (masked)
4578 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4579 GUEST_INTR_STATE_NMI);
4580 else
4581 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4582 GUEST_INTR_STATE_NMI);
4583 }
3cfc3092
JK
4584}
4585
1b660b6b
SC
4586bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4587{
4588 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4589 return false;
4590
4591 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4592 return true;
4593
4594 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4595 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4596 GUEST_INTR_STATE_NMI));
4597}
4598
c9d40913 4599static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
2505dc9f 4600{
b6b8a145 4601 if (to_vmx(vcpu)->nested.nested_run_pending)
c9d40913 4602 return -EBUSY;
ea8ceb83 4603
c300ab9f
PB
4604 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
4605 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
c9d40913 4606 return -EBUSY;
c300ab9f 4607
1b660b6b
SC
4608 return !vmx_nmi_blocked(vcpu);
4609}
429ab576 4610
1b660b6b
SC
4611bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4612{
4613 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
88c604b6 4614 return false;
8a1b4392 4615
7ab0abdb 4616 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
1b660b6b
SC
4617 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4618 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
2505dc9f
JK
4619}
4620
c9d40913 4621static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
78646121 4622{
a1c77abb 4623 if (to_vmx(vcpu)->nested.nested_run_pending)
c9d40913 4624 return -EBUSY;
a1c77abb 4625
c300ab9f
PB
4626 /*
4627 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4628 * e.g. if the IRQ arrived asynchronously after checking nested events.
4629 */
4630 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
c9d40913 4631 return -EBUSY;
c300ab9f 4632
1b660b6b 4633 return !vmx_interrupt_blocked(vcpu);
78646121
GN
4634}
4635
cbc94022
IE
4636static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4637{
ff5a983c 4638 void __user *ret;
cbc94022 4639
f7eaeb0a
SC
4640 if (enable_unrestricted_guest)
4641 return 0;
4642
6a3c623b
PX
4643 mutex_lock(&kvm->slots_lock);
4644 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4645 PAGE_SIZE * 3);
4646 mutex_unlock(&kvm->slots_lock);
4647
ff5a983c
PX
4648 if (IS_ERR(ret))
4649 return PTR_ERR(ret);
4650
40bbb9d0 4651 to_kvm_vmx(kvm)->tss_addr = addr;
ff5a983c
PX
4652
4653 return init_rmode_tss(kvm, ret);
cbc94022
IE
4654}
4655
2ac52ab8
SC
4656static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4657{
40bbb9d0 4658 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
2ac52ab8
SC
4659 return 0;
4660}
4661
0ca1b4f4 4662static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6aa8b732 4663{
77ab6db0 4664 switch (vec) {
77ab6db0 4665 case BP_VECTOR:
c573cd22
JK
4666 /*
4667 * Update instruction length as we may reinject the exception
4668 * from user space while in guest debugging mode.
4669 */
4670 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4671 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
d0bfb940 4672 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
0ca1b4f4 4673 return false;
df561f66 4674 fallthrough;
0ca1b4f4 4675 case DB_VECTOR:
a8cfbae5
ML
4676 return !(vcpu->guest_debug &
4677 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
d0bfb940 4678 case DE_VECTOR:
77ab6db0
JK
4679 case OF_VECTOR:
4680 case BR_VECTOR:
4681 case UD_VECTOR:
4682 case DF_VECTOR:
4683 case SS_VECTOR:
4684 case GP_VECTOR:
4685 case MF_VECTOR:
0ca1b4f4 4686 return true;
77ab6db0 4687 }
0ca1b4f4
GN
4688 return false;
4689}
4690
4691static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4692 int vec, u32 err_code)
4693{
4694 /*
4695 * Instruction with address size override prefix opcode 0x67
4696 * Cause the #SS fault with 0 error code in VM86 mode.
4697 */
4698 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
60fc3d02 4699 if (kvm_emulate_instruction(vcpu, 0)) {
0ca1b4f4
GN
4700 if (vcpu->arch.halt_request) {
4701 vcpu->arch.halt_request = 0;
5cb56059 4702 return kvm_vcpu_halt(vcpu);
0ca1b4f4
GN
4703 }
4704 return 1;
4705 }
4706 return 0;
4707 }
4708
4709 /*
4710 * Forward all other exceptions that are valid in real mode.
4711 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4712 * the required debugging infrastructure rework.
4713 */
4714 kvm_queue_exception(vcpu, vec);
4715 return 1;
6aa8b732
AK
4716}
4717
851ba692 4718static int handle_machine_check(struct kvm_vcpu *vcpu)
a0861c02 4719{
95b5a48c 4720 /* handled by vmx_vcpu_run() */
a0861c02
AK
4721 return 1;
4722}
4723
e6f8b6c1
XL
4724/*
4725 * If the host has split lock detection disabled, then #AC is
4726 * unconditionally injected into the guest, which is the pre split lock
4727 * detection behaviour.
4728 *
4729 * If the host has split lock detection enabled then #AC is
4730 * only injected into the guest when:
4731 * - Guest CPL == 3 (user mode)
4732 * - Guest has #AC detection enabled in CR0
4733 * - Guest EFLAGS has AC bit set
4734 */
4735static inline bool guest_inject_ac(struct kvm_vcpu *vcpu)
4736{
4737 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4738 return true;
4739
4740 return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4741 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4742}
4743
95b5a48c 4744static int handle_exception_nmi(struct kvm_vcpu *vcpu)
6aa8b732 4745{
1155f76a 4746 struct vcpu_vmx *vmx = to_vmx(vcpu);
851ba692 4747 struct kvm_run *kvm_run = vcpu->run;
d0bfb940 4748 u32 intr_info, ex_no, error_code;
42dbaa5a 4749 unsigned long cr2, rip, dr6;
6aa8b732 4750 u32 vect_info;
6aa8b732 4751
1155f76a 4752 vect_info = vmx->idt_vectoring_info;
f27ad73a 4753 intr_info = vmx_get_intr_info(vcpu);
6aa8b732 4754
2ea72039 4755 if (is_machine_check(intr_info) || is_nmi(intr_info))
95b5a48c 4756 return 1; /* handled by handle_exception_nmi_irqoff() */
2ab455cc 4757
082d06ed
WL
4758 if (is_invalid_opcode(intr_info))
4759 return handle_ud(vcpu);
7aa81cc0 4760
6aa8b732 4761 error_code = 0;
2e11384c 4762 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
6aa8b732 4763 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
bf4ca23e 4764
9e869480
LA
4765 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4766 WARN_ON_ONCE(!enable_vmware_backdoor);
a6c6ed1e
SC
4767
4768 /*
4769 * VMware backdoor emulation on #GP interception only handles
4770 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4771 * error code on #GP.
4772 */
4773 if (error_code) {
4774 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4775 return 1;
4776 }
60fc3d02 4777 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
9e869480
LA
4778 }
4779
bf4ca23e
XG
4780 /*
4781 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4782 * MMIO, it is better to report an internal error.
4783 * See the comments in vmx_handle_exit.
4784 */
4785 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4786 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4787 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4788 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
1aa561b1 4789 vcpu->run->internal.ndata = 4;
bf4ca23e
XG
4790 vcpu->run->internal.data[0] = vect_info;
4791 vcpu->run->internal.data[1] = intr_info;
80f0e95d 4792 vcpu->run->internal.data[2] = error_code;
8a14fe4f 4793 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
bf4ca23e
XG
4794 return 0;
4795 }
4796
6aa8b732 4797 if (is_page_fault(intr_info)) {
5addc235 4798 cr2 = vmx_get_exit_qual(vcpu);
1dbf5d68
MG
4799 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
4800 /*
4801 * EPT will cause page fault only if we need to
4802 * detect illegal GPAs.
4803 */
b96e6506 4804 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
1dbf5d68
MG
4805 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
4806 return 1;
4807 } else
4808 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
6aa8b732
AK
4809 }
4810
d0bfb940 4811 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
0ca1b4f4
GN
4812
4813 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4814 return handle_rmode_exception(vcpu, ex_no, error_code);
4815
42dbaa5a
JK
4816 switch (ex_no) {
4817 case DB_VECTOR:
5addc235 4818 dr6 = vmx_get_exit_qual(vcpu);
42dbaa5a
JK
4819 if (!(vcpu->guest_debug &
4820 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
32d43cd3 4821 if (is_icebp(intr_info))
1957aa63 4822 WARN_ON(!skip_emulated_instruction(vcpu));
fd2a445a 4823
4d5523cf 4824 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
42dbaa5a
JK
4825 return 1;
4826 }
13196638 4827 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
42dbaa5a 4828 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
df561f66 4829 fallthrough;
42dbaa5a 4830 case BP_VECTOR:
c573cd22
JK
4831 /*
4832 * Update instruction length as we may reinject #BP from
4833 * user space while in guest debugging mode. Reading it for
4834 * #DB as well causes no harm, it is not used in that case.
4835 */
4836 vmx->vcpu.arch.event_exit_inst_len =
4837 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6aa8b732 4838 kvm_run->exit_reason = KVM_EXIT_DEBUG;
0a434bb2 4839 rip = kvm_rip_read(vcpu);
d0bfb940
JK
4840 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4841 kvm_run->debug.arch.exception = ex_no;
42dbaa5a 4842 break;
e6f8b6c1
XL
4843 case AC_VECTOR:
4844 if (guest_inject_ac(vcpu)) {
4845 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4846 return 1;
4847 }
4848
4849 /*
4850 * Handle split lock. Depending on detection mode this will
4851 * either warn and disable split lock detection for this
4852 * task or force SIGBUS on it.
4853 */
4854 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4855 return 1;
4856 fallthrough;
42dbaa5a 4857 default:
d0bfb940
JK
4858 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4859 kvm_run->ex.exception = ex_no;
4860 kvm_run->ex.error_code = error_code;
42dbaa5a 4861 break;
6aa8b732 4862 }
6aa8b732
AK
4863 return 0;
4864}
4865
f399e60c 4866static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
6aa8b732 4867{
1165f5fe 4868 ++vcpu->stat.irq_exits;
6aa8b732
AK
4869 return 1;
4870}
4871
851ba692 4872static int handle_triple_fault(struct kvm_vcpu *vcpu)
988ad74f 4873{
851ba692 4874 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
bbeac283 4875 vcpu->mmio_needed = 0;
988ad74f
AK
4876 return 0;
4877}
6aa8b732 4878
851ba692 4879static int handle_io(struct kvm_vcpu *vcpu)
6aa8b732 4880{
bfdaab09 4881 unsigned long exit_qualification;
dca7f128 4882 int size, in, string;
039576c0 4883 unsigned port;
6aa8b732 4884
5addc235 4885 exit_qualification = vmx_get_exit_qual(vcpu);
039576c0 4886 string = (exit_qualification & 16) != 0;
e70669ab 4887
cf8f70bf 4888 ++vcpu->stat.io_exits;
e70669ab 4889
432baf60 4890 if (string)
60fc3d02 4891 return kvm_emulate_instruction(vcpu, 0);
e70669ab 4892
cf8f70bf
GN
4893 port = exit_qualification >> 16;
4894 size = (exit_qualification & 7) + 1;
432baf60 4895 in = (exit_qualification & 8) != 0;
cf8f70bf 4896
dca7f128 4897 return kvm_fast_pio(vcpu, size, port, in);
6aa8b732
AK
4898}
4899
102d8325
IM
4900static void
4901vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4902{
4903 /*
4904 * Patch in the VMCALL instruction:
4905 */
4906 hypercall[0] = 0x0f;
4907 hypercall[1] = 0x01;
4908 hypercall[2] = 0xc1;
102d8325
IM
4909}
4910
0fa06071 4911/* called to set cr0 as appropriate for a mov-to-cr0 exit. */
eeadf9e7
NHE
4912static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4913{
eeadf9e7 4914 if (is_guest_mode(vcpu)) {
1a0d74e6
JK
4915 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4916 unsigned long orig_val = val;
4917
eeadf9e7
NHE
4918 /*
4919 * We get here when L2 changed cr0 in a way that did not change
4920 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
1a0d74e6
JK
4921 * but did change L0 shadowed bits. So we first calculate the
4922 * effective cr0 value that L1 would like to write into the
4923 * hardware. It consists of the L2-owned bits from the new
4924 * value combined with the L1-owned bits from L1's guest_cr0.
eeadf9e7 4925 */
1a0d74e6
JK
4926 val = (val & ~vmcs12->cr0_guest_host_mask) |
4927 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4928
3899152c 4929 if (!nested_guest_cr0_valid(vcpu, val))
eeadf9e7 4930 return 1;
1a0d74e6
JK
4931
4932 if (kvm_set_cr0(vcpu, val))
4933 return 1;
4934 vmcs_writel(CR0_READ_SHADOW, orig_val);
eeadf9e7 4935 return 0;
1a0d74e6
JK
4936 } else {
4937 if (to_vmx(vcpu)->nested.vmxon &&
3899152c 4938 !nested_host_cr0_valid(vcpu, val))
1a0d74e6 4939 return 1;
3899152c 4940
eeadf9e7 4941 return kvm_set_cr0(vcpu, val);
1a0d74e6 4942 }
eeadf9e7
NHE
4943}
4944
4945static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4946{
4947 if (is_guest_mode(vcpu)) {
1a0d74e6
JK
4948 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4949 unsigned long orig_val = val;
4950
4951 /* analogously to handle_set_cr0 */
4952 val = (val & ~vmcs12->cr4_guest_host_mask) |
4953 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4954 if (kvm_set_cr4(vcpu, val))
eeadf9e7 4955 return 1;
1a0d74e6 4956 vmcs_writel(CR4_READ_SHADOW, orig_val);
eeadf9e7
NHE
4957 return 0;
4958 } else
4959 return kvm_set_cr4(vcpu, val);
4960}
4961
0367f205
PB
4962static int handle_desc(struct kvm_vcpu *vcpu)
4963{
4964 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
60fc3d02 4965 return kvm_emulate_instruction(vcpu, 0);
0367f205
PB
4966}
4967
851ba692 4968static int handle_cr(struct kvm_vcpu *vcpu)
6aa8b732 4969{
229456fc 4970 unsigned long exit_qualification, val;
6aa8b732
AK
4971 int cr;
4972 int reg;
49a9b07e 4973 int err;
6affcbed 4974 int ret;
6aa8b732 4975
5addc235 4976 exit_qualification = vmx_get_exit_qual(vcpu);
6aa8b732
AK
4977 cr = exit_qualification & 15;
4978 reg = (exit_qualification >> 8) & 15;
4979 switch ((exit_qualification >> 4) & 3) {
4980 case 0: /* mov to cr */
1e32c079 4981 val = kvm_register_readl(vcpu, reg);
229456fc 4982 trace_kvm_cr_write(cr, val);
6aa8b732
AK
4983 switch (cr) {
4984 case 0:
eeadf9e7 4985 err = handle_set_cr0(vcpu, val);
6affcbed 4986 return kvm_complete_insn_gp(vcpu, err);
6aa8b732 4987 case 3:
e1de91cc 4988 WARN_ON_ONCE(enable_unrestricted_guest);
2390218b 4989 err = kvm_set_cr3(vcpu, val);
6affcbed 4990 return kvm_complete_insn_gp(vcpu, err);
6aa8b732 4991 case 4:
eeadf9e7 4992 err = handle_set_cr4(vcpu, val);
6affcbed 4993 return kvm_complete_insn_gp(vcpu, err);
0a5fff19
GN
4994 case 8: {
4995 u8 cr8_prev = kvm_get_cr8(vcpu);
1e32c079 4996 u8 cr8 = (u8)val;
eea1cff9 4997 err = kvm_set_cr8(vcpu, cr8);
6affcbed 4998 ret = kvm_complete_insn_gp(vcpu, err);
35754c98 4999 if (lapic_in_kernel(vcpu))
6affcbed 5000 return ret;
0a5fff19 5001 if (cr8_prev <= cr8)
6affcbed
KH
5002 return ret;
5003 /*
5004 * TODO: we might be squashing a
5005 * KVM_GUESTDBG_SINGLESTEP-triggered
5006 * KVM_EXIT_DEBUG here.
5007 */
851ba692 5008 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
0a5fff19
GN
5009 return 0;
5010 }
4b8073e4 5011 }
6aa8b732 5012 break;
25c4c276 5013 case 2: /* clts */
bd7e5b08
PB
5014 WARN_ONCE(1, "Guest should always own CR0.TS");
5015 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4d4ec087 5016 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
6affcbed 5017 return kvm_skip_emulated_instruction(vcpu);
6aa8b732
AK
5018 case 1: /*mov from cr*/
5019 switch (cr) {
5020 case 3:
e1de91cc 5021 WARN_ON_ONCE(enable_unrestricted_guest);
9f8fe504
AK
5022 val = kvm_read_cr3(vcpu);
5023 kvm_register_write(vcpu, reg, val);
5024 trace_kvm_cr_read(cr, val);
6affcbed 5025 return kvm_skip_emulated_instruction(vcpu);
6aa8b732 5026 case 8:
229456fc
MT
5027 val = kvm_get_cr8(vcpu);
5028 kvm_register_write(vcpu, reg, val);
5029 trace_kvm_cr_read(cr, val);
6affcbed 5030 return kvm_skip_emulated_instruction(vcpu);
6aa8b732
AK
5031 }
5032 break;
5033 case 3: /* lmsw */
a1f83a74 5034 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4d4ec087 5035 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
a1f83a74 5036 kvm_lmsw(vcpu, val);
6aa8b732 5037
6affcbed 5038 return kvm_skip_emulated_instruction(vcpu);
6aa8b732
AK
5039 default:
5040 break;
5041 }
851ba692 5042 vcpu->run->exit_reason = 0;
a737f256 5043 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
6aa8b732
AK
5044 (int)(exit_qualification >> 4) & 3, cr);
5045 return 0;
5046}
5047
851ba692 5048static int handle_dr(struct kvm_vcpu *vcpu)
6aa8b732 5049{
bfdaab09 5050 unsigned long exit_qualification;
16f8a6f9
NA
5051 int dr, dr7, reg;
5052
5addc235 5053 exit_qualification = vmx_get_exit_qual(vcpu);
16f8a6f9
NA
5054 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5055
5056 /* First, if DR does not exist, trigger UD */
5057 if (!kvm_require_dr(vcpu, dr))
5058 return 1;
6aa8b732 5059
f2483415 5060 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
0a79b009
AK
5061 if (!kvm_require_cpl(vcpu, 0))
5062 return 1;
16f8a6f9
NA
5063 dr7 = vmcs_readl(GUEST_DR7);
5064 if (dr7 & DR7_GD) {
42dbaa5a
JK
5065 /*
5066 * As the vm-exit takes precedence over the debug trap, we
5067 * need to emulate the latter, either for the host or the
5068 * guest debugging itself.
5069 */
5070 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
45981ded 5071 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_RTM | DR6_FIXED_1;
16f8a6f9 5072 vcpu->run->debug.arch.dr7 = dr7;
82b32774 5073 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
851ba692
AK
5074 vcpu->run->debug.arch.exception = DB_VECTOR;
5075 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
42dbaa5a
JK
5076 return 0;
5077 } else {
4d5523cf 5078 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
42dbaa5a
JK
5079 return 1;
5080 }
5081 }
5082
81908bf4 5083 if (vcpu->guest_debug == 0) {
2183f564 5084 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
81908bf4
PB
5085
5086 /*
5087 * No more DR vmexits; force a reload of the debug registers
5088 * and reenter on this instruction. The next vmexit will
5089 * retrieve the full state of the debug registers.
5090 */
5091 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5092 return 1;
5093 }
5094
42dbaa5a
JK
5095 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5096 if (exit_qualification & TYPE_MOV_FROM_DR) {
020df079 5097 unsigned long val;
4c4d563b
JK
5098
5099 if (kvm_get_dr(vcpu, dr, &val))
5100 return 1;
5101 kvm_register_write(vcpu, reg, val);
020df079 5102 } else
5777392e 5103 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
4c4d563b
JK
5104 return 1;
5105
6affcbed 5106 return kvm_skip_emulated_instruction(vcpu);
6aa8b732
AK
5107}
5108
81908bf4
PB
5109static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5110{
81908bf4
PB
5111 get_debugreg(vcpu->arch.db[0], 0);
5112 get_debugreg(vcpu->arch.db[1], 1);
5113 get_debugreg(vcpu->arch.db[2], 2);
5114 get_debugreg(vcpu->arch.db[3], 3);
5115 get_debugreg(vcpu->arch.dr6, 6);
5116 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5117
5118 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2183f564 5119 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
81908bf4
PB
5120}
5121
020df079
GN
5122static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5123{
5124 vmcs_writel(GUEST_DR7, val);
5125}
5126
851ba692 5127static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
6e5d865c 5128{
eb90f341 5129 kvm_apic_update_ppr(vcpu);
6e5d865c
YS
5130 return 1;
5131}
5132
851ba692 5133static int handle_interrupt_window(struct kvm_vcpu *vcpu)
6aa8b732 5134{
9dadc2f9 5135 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
2714d1d3 5136
3842d135
AK
5137 kvm_make_request(KVM_REQ_EVENT, vcpu);
5138
a26bf12a 5139 ++vcpu->stat.irq_window_exits;
6aa8b732
AK
5140 return 1;
5141}
5142
851ba692 5143static int handle_vmcall(struct kvm_vcpu *vcpu)
c21415e8 5144{
0d9c055e 5145 return kvm_emulate_hypercall(vcpu);
c21415e8
IM
5146}
5147
ec25d5e6
GN
5148static int handle_invd(struct kvm_vcpu *vcpu)
5149{
28e2b2f1
TL
5150 /* Treat an INVD instruction as a NOP and just skip it. */
5151 return kvm_skip_emulated_instruction(vcpu);
ec25d5e6
GN
5152}
5153
851ba692 5154static int handle_invlpg(struct kvm_vcpu *vcpu)
a7052897 5155{
5addc235 5156 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
a7052897
MT
5157
5158 kvm_mmu_invlpg(vcpu, exit_qualification);
6affcbed 5159 return kvm_skip_emulated_instruction(vcpu);
a7052897
MT
5160}
5161
fee84b07
AK
5162static int handle_rdpmc(struct kvm_vcpu *vcpu)
5163{
5164 int err;
5165
5166 err = kvm_rdpmc(vcpu);
6affcbed 5167 return kvm_complete_insn_gp(vcpu, err);
fee84b07
AK
5168}
5169
851ba692 5170static int handle_wbinvd(struct kvm_vcpu *vcpu)
e5edaa01 5171{
6affcbed 5172 return kvm_emulate_wbinvd(vcpu);
e5edaa01
ED
5173}
5174
2acf923e
DC
5175static int handle_xsetbv(struct kvm_vcpu *vcpu)
5176{
5177 u64 new_bv = kvm_read_edx_eax(vcpu);
de3cd117 5178 u32 index = kvm_rcx_read(vcpu);
2acf923e
DC
5179
5180 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
6affcbed 5181 return kvm_skip_emulated_instruction(vcpu);
2acf923e
DC
5182 return 1;
5183}
5184
851ba692 5185static int handle_apic_access(struct kvm_vcpu *vcpu)
f78e0e2e 5186{
58fbbf26 5187 if (likely(fasteoi)) {
5addc235 5188 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
58fbbf26
KT
5189 int access_type, offset;
5190
5191 access_type = exit_qualification & APIC_ACCESS_TYPE;
5192 offset = exit_qualification & APIC_ACCESS_OFFSET;
5193 /*
5194 * Sane guest uses MOV to write EOI, with written value
5195 * not cared. So make a short-circuit here by avoiding
5196 * heavy instruction emulation.
5197 */
5198 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5199 (offset == APIC_EOI)) {
5200 kvm_lapic_set_eoi(vcpu);
6affcbed 5201 return kvm_skip_emulated_instruction(vcpu);
58fbbf26
KT
5202 }
5203 }
60fc3d02 5204 return kvm_emulate_instruction(vcpu, 0);
f78e0e2e
SY
5205}
5206
c7c9c56c
YZ
5207static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5208{
5addc235 5209 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
c7c9c56c
YZ
5210 int vector = exit_qualification & 0xff;
5211
5212 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5213 kvm_apic_set_eoi_accelerated(vcpu, vector);
5214 return 1;
5215}
5216
83d4c286
YZ
5217static int handle_apic_write(struct kvm_vcpu *vcpu)
5218{
5addc235 5219 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
83d4c286
YZ
5220 u32 offset = exit_qualification & 0xfff;
5221
5222 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5223 kvm_apic_write_nodecode(vcpu, offset);
5224 return 1;
5225}
5226
851ba692 5227static int handle_task_switch(struct kvm_vcpu *vcpu)
37817f29 5228{
60637aac 5229 struct vcpu_vmx *vmx = to_vmx(vcpu);
37817f29 5230 unsigned long exit_qualification;
e269fb21
JK
5231 bool has_error_code = false;
5232 u32 error_code = 0;
37817f29 5233 u16 tss_selector;
7f3d35fd 5234 int reason, type, idt_v, idt_index;
64a7ec06
GN
5235
5236 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
7f3d35fd 5237 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
64a7ec06 5238 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
37817f29 5239
5addc235 5240 exit_qualification = vmx_get_exit_qual(vcpu);
37817f29
IE
5241
5242 reason = (u32)exit_qualification >> 30;
64a7ec06
GN
5243 if (reason == TASK_SWITCH_GATE && idt_v) {
5244 switch (type) {
5245 case INTR_TYPE_NMI_INTR:
5246 vcpu->arch.nmi_injected = false;
654f06fc 5247 vmx_set_nmi_mask(vcpu, true);
64a7ec06
GN
5248 break;
5249 case INTR_TYPE_EXT_INTR:
66fd3f7f 5250 case INTR_TYPE_SOFT_INTR:
64a7ec06
GN
5251 kvm_clear_interrupt_queue(vcpu);
5252 break;
5253 case INTR_TYPE_HARD_EXCEPTION:
e269fb21
JK
5254 if (vmx->idt_vectoring_info &
5255 VECTORING_INFO_DELIVER_CODE_MASK) {
5256 has_error_code = true;
5257 error_code =
5258 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5259 }
df561f66 5260 fallthrough;
64a7ec06
GN
5261 case INTR_TYPE_SOFT_EXCEPTION:
5262 kvm_clear_exception_queue(vcpu);
5263 break;
5264 default:
5265 break;
5266 }
60637aac 5267 }
37817f29
IE
5268 tss_selector = exit_qualification;
5269
64a7ec06
GN
5270 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5271 type != INTR_TYPE_EXT_INTR &&
5272 type != INTR_TYPE_NMI_INTR))
1957aa63 5273 WARN_ON(!skip_emulated_instruction(vcpu));
64a7ec06 5274
42dbaa5a
JK
5275 /*
5276 * TODO: What about debug traps on tss switch?
5277 * Are we supposed to inject them and update dr6?
5278 */
1051778f
SC
5279 return kvm_task_switch(vcpu, tss_selector,
5280 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
60fc3d02 5281 reason, has_error_code, error_code);
37817f29
IE
5282}
5283
851ba692 5284static int handle_ept_violation(struct kvm_vcpu *vcpu)
1439442c 5285{
f9c617f6 5286 unsigned long exit_qualification;
1439442c 5287 gpa_t gpa;
eebed243 5288 u64 error_code;
1439442c 5289
5addc235 5290 exit_qualification = vmx_get_exit_qual(vcpu);
1439442c 5291
0be9c7a8
GN
5292 /*
5293 * EPT violation happened while executing iret from NMI,
5294 * "blocked by NMI" bit has to be set before next VM entry.
5295 * There are errata that may cause this bit to not be set:
5296 * AAK134, BY25.
5297 */
bcd1c294 5298 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
d02fcf50 5299 enable_vnmi &&
bcd1c294 5300 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
0be9c7a8
GN
5301 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5302
1439442c 5303 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
229456fc 5304 trace_kvm_page_fault(gpa, exit_qualification);
4f5982a5 5305
27959a44 5306 /* Is it a read fault? */
ab22a473 5307 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
27959a44
JS
5308 ? PFERR_USER_MASK : 0;
5309 /* Is it a write fault? */
ab22a473 5310 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
27959a44
JS
5311 ? PFERR_WRITE_MASK : 0;
5312 /* Is it a fetch fault? */
ab22a473 5313 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
27959a44
JS
5314 ? PFERR_FETCH_MASK : 0;
5315 /* ept page table entry is present? */
5316 error_code |= (exit_qualification &
5317 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5318 EPT_VIOLATION_EXECUTABLE))
5319 ? PFERR_PRESENT_MASK : 0;
4f5982a5 5320
eebed243
PB
5321 error_code |= (exit_qualification & 0x100) != 0 ?
5322 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
25d92081 5323
25d92081 5324 vcpu->arch.exit_qualification = exit_qualification;
1dbf5d68
MG
5325
5326 /*
5327 * Check that the GPA doesn't exceed physical memory limits, as that is
5328 * a guest page fault. We have to emulate the instruction here, because
5329 * if the illegal address is that of a paging structure, then
5330 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5331 * would also use advanced VM-exit information for EPT violations to
5332 * reconstruct the page fault error code.
5333 */
c0623f5e 5334 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
1dbf5d68
MG
5335 return kvm_emulate_instruction(vcpu, 0);
5336
4f5982a5 5337 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
1439442c
SY
5338}
5339
851ba692 5340static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
68f89400 5341{
68f89400
MT
5342 gpa_t gpa;
5343
9034e6e8
PB
5344 /*
5345 * A nested guest cannot optimize MMIO vmexits, because we have an
5346 * nGPA here instead of the required GPA.
5347 */
68f89400 5348 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
9034e6e8
PB
5349 if (!is_guest_mode(vcpu) &&
5350 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
931c33b1 5351 trace_kvm_fast_mmio(gpa);
1957aa63 5352 return kvm_skip_emulated_instruction(vcpu);
68c3b4d1 5353 }
68f89400 5354
c75d0edc 5355 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
68f89400
MT
5356}
5357
851ba692 5358static int handle_nmi_window(struct kvm_vcpu *vcpu)
f08864b4 5359{
d02fcf50 5360 WARN_ON_ONCE(!enable_vnmi);
4e2a0bc5 5361 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
f08864b4 5362 ++vcpu->stat.nmi_window_exits;
3842d135 5363 kvm_make_request(KVM_REQ_EVENT, vcpu);
f08864b4
SY
5364
5365 return 1;
5366}
5367
80ced186 5368static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
ea953ef0 5369{
8b3079a5 5370 struct vcpu_vmx *vmx = to_vmx(vcpu);
49e9d557 5371 bool intr_window_requested;
b8405c18 5372 unsigned count = 130;
49e9d557 5373
2183f564 5374 intr_window_requested = exec_controls_get(vmx) &
9dadc2f9 5375 CPU_BASED_INTR_WINDOW_EXITING;
ea953ef0 5376
98eb2f8b 5377 while (vmx->emulation_required && count-- != 0) {
db438592 5378 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
49e9d557
AK
5379 return handle_interrupt_window(&vmx->vcpu);
5380
72875d8a 5381 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
de87dcdd
AK
5382 return 1;
5383
60fc3d02 5384 if (!kvm_emulate_instruction(vcpu, 0))
8fff2710 5385 return 0;
1d5a4d9b 5386
add5ff7a 5387 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
8fff2710
SC
5388 vcpu->arch.exception.pending) {
5389 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5390 vcpu->run->internal.suberror =
5391 KVM_INTERNAL_ERROR_EMULATION;
5392 vcpu->run->internal.ndata = 0;
5393 return 0;
5394 }
ea953ef0 5395
8d76c49e
GN
5396 if (vcpu->arch.halt_request) {
5397 vcpu->arch.halt_request = 0;
8fff2710 5398 return kvm_vcpu_halt(vcpu);
8d76c49e
GN
5399 }
5400
8fff2710 5401 /*
72c3c0fe
TG
5402 * Note, return 1 and not 0, vcpu_run() will invoke
5403 * xfer_to_guest_mode() which will create a proper return
5404 * code.
8fff2710 5405 */
72c3c0fe 5406 if (__xfer_to_guest_mode_work_pending())
8fff2710 5407 return 1;
ea953ef0
MG
5408 }
5409
8fff2710 5410 return 1;
b4a2d31d
RK
5411}
5412
5413static void grow_ple_window(struct kvm_vcpu *vcpu)
5414{
5415 struct vcpu_vmx *vmx = to_vmx(vcpu);
c5c5d6fa 5416 unsigned int old = vmx->ple_window;
b4a2d31d 5417
c8e88717
BM
5418 vmx->ple_window = __grow_ple_window(old, ple_window,
5419 ple_window_grow,
5420 ple_window_max);
b4a2d31d 5421
4f75bcc3 5422 if (vmx->ple_window != old) {
b4a2d31d 5423 vmx->ple_window_dirty = true;
4f75bcc3
PX
5424 trace_kvm_ple_window_update(vcpu->vcpu_id,
5425 vmx->ple_window, old);
5426 }
b4a2d31d
RK
5427}
5428
5429static void shrink_ple_window(struct kvm_vcpu *vcpu)
5430{
5431 struct vcpu_vmx *vmx = to_vmx(vcpu);
c5c5d6fa 5432 unsigned int old = vmx->ple_window;
b4a2d31d 5433
c8e88717
BM
5434 vmx->ple_window = __shrink_ple_window(old, ple_window,
5435 ple_window_shrink,
5436 ple_window);
b4a2d31d 5437
4f75bcc3 5438 if (vmx->ple_window != old) {
b4a2d31d 5439 vmx->ple_window_dirty = true;
4f75bcc3
PX
5440 trace_kvm_ple_window_update(vcpu->vcpu_id,
5441 vmx->ple_window, old);
5442 }
b4a2d31d
RK
5443}
5444
e01bca2f 5445static void vmx_enable_tdp(void)
f160c7b7
JS
5446{
5447 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5448 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5449 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5450 0ull, VMX_EPT_EXECUTABLE_MASK,
5451 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
d0ec49d4 5452 VMX_EPT_RWX_MASK, 0ull);
f160c7b7
JS
5453
5454 ept_set_mmio_spte_mask();
f160c7b7
JS
5455}
5456
4b8d54f9
ZE
5457/*
5458 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5459 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5460 */
9fb41ba8 5461static int handle_pause(struct kvm_vcpu *vcpu)
4b8d54f9 5462{
b31c114b 5463 if (!kvm_pause_in_guest(vcpu->kvm))
b4a2d31d
RK
5464 grow_ple_window(vcpu);
5465
de63ad4c
LM
5466 /*
5467 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5468 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5469 * never set PAUSE_EXITING and just set PLE if supported,
5470 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5471 */
5472 kvm_vcpu_on_spin(vcpu, true);
6affcbed 5473 return kvm_skip_emulated_instruction(vcpu);
4b8d54f9
ZE
5474}
5475
87c00572 5476static int handle_nop(struct kvm_vcpu *vcpu)
59708670 5477{
6affcbed 5478 return kvm_skip_emulated_instruction(vcpu);
59708670
SY
5479}
5480
87c00572
GS
5481static int handle_mwait(struct kvm_vcpu *vcpu)
5482{
5483 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5484 return handle_nop(vcpu);
5485}
5486
45ec368c
JM
5487static int handle_invalid_op(struct kvm_vcpu *vcpu)
5488{
5489 kvm_queue_exception(vcpu, UD_VECTOR);
5490 return 1;
5491}
5492
5f3d45e7
MD
5493static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5494{
5495 return 1;
5496}
5497
87c00572
GS
5498static int handle_monitor(struct kvm_vcpu *vcpu)
5499{
5500 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5501 return handle_nop(vcpu);
5502}
5503
55d2375e 5504static int handle_invpcid(struct kvm_vcpu *vcpu)
19677e32 5505{
55d2375e
SC
5506 u32 vmx_instruction_info;
5507 unsigned long type;
55d2375e 5508 gva_t gva;
55d2375e
SC
5509 struct {
5510 u64 pcid;
5511 u64 gla;
5512 } operand;
f9eb4af6 5513
55d2375e 5514 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
19677e32
BD
5515 kvm_queue_exception(vcpu, UD_VECTOR);
5516 return 1;
5517 }
5518
55d2375e
SC
5519 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5520 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5521
5522 if (type > 3) {
5523 kvm_inject_gp(vcpu, 0);
f9eb4af6
EK
5524 return 1;
5525 }
5526
55d2375e
SC
5527 /* According to the Intel instruction reference, the memory operand
5528 * is read even if it isn't needed (e.g., for type==all)
5529 */
5addc235 5530 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
fdb28619
EK
5531 vmx_instruction_info, false,
5532 sizeof(operand), &gva))
3573e22c
BD
5533 return 1;
5534
9715092f 5535 return kvm_handle_invpcid(vcpu, type, gva);
e29acc55
JM
5536}
5537
55d2375e 5538static int handle_pml_full(struct kvm_vcpu *vcpu)
ec378aee 5539{
55d2375e 5540 unsigned long exit_qualification;
b3897a49 5541
55d2375e 5542 trace_kvm_pml_full(vcpu->vcpu_id);
b3897a49 5543
5addc235 5544 exit_qualification = vmx_get_exit_qual(vcpu);
cbf71279
RK
5545
5546 /*
55d2375e
SC
5547 * PML buffer FULL happened while executing iret from NMI,
5548 * "blocked by NMI" bit has to be set before next VM entry.
cbf71279 5549 */
55d2375e
SC
5550 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5551 enable_vnmi &&
5552 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5553 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5554 GUEST_INTR_STATE_NMI);
e49fcb8b 5555
55d2375e
SC
5556 /*
5557 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5558 * here.., and there's no userspace involvement needed for PML.
5559 */
ec378aee
NHE
5560 return 1;
5561}
5562
26efe2fd 5563static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
8ca44e88 5564{
804939ea
SC
5565 struct vcpu_vmx *vmx = to_vmx(vcpu);
5566
5567 if (!vmx->req_immediate_exit &&
26efe2fd 5568 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
55d2375e 5569 kvm_lapic_expired_hv_timer(vcpu);
26efe2fd
WL
5570 return EXIT_FASTPATH_REENTER_GUEST;
5571 }
5572
5573 return EXIT_FASTPATH_NONE;
5574}
804939ea 5575
26efe2fd
WL
5576static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5577{
5578 handle_fastpath_preemption_timer(vcpu);
55d2375e 5579 return 1;
8ca44e88
DM
5580}
5581
55d2375e
SC
5582/*
5583 * When nested=0, all VMX instruction VM Exits filter here. The handlers
5584 * are overwritten by nested_vmx_setup() when nested=1.
5585 */
5586static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
b8bbab92 5587{
55d2375e
SC
5588 kvm_queue_exception(vcpu, UD_VECTOR);
5589 return 1;
b8bbab92
VK
5590}
5591
55d2375e 5592static int handle_encls(struct kvm_vcpu *vcpu)
e7953d7f 5593{
55d2375e
SC
5594 /*
5595 * SGX virtualization is not yet supported. There is no software
5596 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5597 * to prevent the guest from executing ENCLS.
5598 */
5599 kvm_queue_exception(vcpu, UD_VECTOR);
5600 return 1;
e7953d7f
AG
5601}
5602
ec378aee 5603/*
55d2375e
SC
5604 * The exit handlers return 1 if the exit was handled fully and guest execution
5605 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
5606 * to be done to userspace and return 0.
ec378aee 5607 */
55d2375e 5608static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
95b5a48c 5609 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
55d2375e
SC
5610 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
5611 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
5612 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
5613 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
5614 [EXIT_REASON_CR_ACCESS] = handle_cr,
5615 [EXIT_REASON_DR_ACCESS] = handle_dr,
f399e60c
AA
5616 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
5617 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
5618 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
9dadc2f9 5619 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
f399e60c 5620 [EXIT_REASON_HLT] = kvm_emulate_halt,
55d2375e
SC
5621 [EXIT_REASON_INVD] = handle_invd,
5622 [EXIT_REASON_INVLPG] = handle_invlpg,
5623 [EXIT_REASON_RDPMC] = handle_rdpmc,
5624 [EXIT_REASON_VMCALL] = handle_vmcall,
5625 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
5626 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
5627 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
5628 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
5629 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
5630 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
5631 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
5632 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
5633 [EXIT_REASON_VMON] = handle_vmx_instruction,
5634 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
5635 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
5636 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
5637 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
5638 [EXIT_REASON_WBINVD] = handle_wbinvd,
5639 [EXIT_REASON_XSETBV] = handle_xsetbv,
5640 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
5641 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
5642 [EXIT_REASON_GDTR_IDTR] = handle_desc,
5643 [EXIT_REASON_LDTR_TR] = handle_desc,
5644 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
5645 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
5646 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
5647 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
5648 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
5649 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
5650 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
5651 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
5652 [EXIT_REASON_RDRAND] = handle_invalid_op,
5653 [EXIT_REASON_RDSEED] = handle_invalid_op,
55d2375e
SC
5654 [EXIT_REASON_PML_FULL] = handle_pml_full,
5655 [EXIT_REASON_INVPCID] = handle_invpcid,
5656 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
5657 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
5658 [EXIT_REASON_ENCLS] = handle_encls,
5659};
b8bbab92 5660
55d2375e
SC
5661static const int kvm_vmx_max_exit_handlers =
5662 ARRAY_SIZE(kvm_vmx_exit_handlers);
ec378aee 5663
235ba74f
SC
5664static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2,
5665 u32 *intr_info, u32 *error_code)
ec378aee 5666{
235ba74f
SC
5667 struct vcpu_vmx *vmx = to_vmx(vcpu);
5668
5addc235 5669 *info1 = vmx_get_exit_qual(vcpu);
a6bdda1f 5670 if (!(vmx->exit_reason.failed_vmentry)) {
235ba74f
SC
5671 *info2 = vmx->idt_vectoring_info;
5672 *intr_info = vmx_get_intr_info(vcpu);
5673 if (is_exception_with_error_code(*intr_info))
5674 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5675 else
5676 *error_code = 0;
5677 } else {
5678 *info2 = 0;
5679 *intr_info = 0;
5680 *error_code = 0;
5681 }
ec378aee
NHE
5682}
5683
55d2375e 5684static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
27d6c865 5685{
55d2375e
SC
5686 if (vmx->pml_pg) {
5687 __free_page(vmx->pml_pg);
5688 vmx->pml_pg = NULL;
b8bbab92 5689 }
27d6c865
NHE
5690}
5691
55d2375e 5692static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
cd232ad0 5693{
55d2375e
SC
5694 struct vcpu_vmx *vmx = to_vmx(vcpu);
5695 u64 *pml_buf;
5696 u16 pml_idx;
cd232ad0 5697
55d2375e 5698 pml_idx = vmcs_read16(GUEST_PML_INDEX);
cd232ad0 5699
55d2375e
SC
5700 /* Do nothing if PML buffer is empty */
5701 if (pml_idx == (PML_ENTITY_NUM - 1))
5702 return;
cd232ad0 5703
55d2375e
SC
5704 /* PML index always points to next available PML buffer entity */
5705 if (pml_idx >= PML_ENTITY_NUM)
5706 pml_idx = 0;
5707 else
5708 pml_idx++;
945679e3 5709
55d2375e
SC
5710 pml_buf = page_address(vmx->pml_pg);
5711 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5712 u64 gpa;
945679e3 5713
55d2375e
SC
5714 gpa = pml_buf[pml_idx];
5715 WARN_ON(gpa & (PAGE_SIZE - 1));
5716 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
945679e3
VK
5717 }
5718
55d2375e
SC
5719 /* reset PML index */
5720 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
945679e3
VK
5721}
5722
f4160e45 5723/*
55d2375e
SC
5724 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5725 * Called before reporting dirty_bitmap to userspace.
f4160e45 5726 */
55d2375e 5727static void kvm_flush_pml_buffers(struct kvm *kvm)
49f705c5 5728{
55d2375e
SC
5729 int i;
5730 struct kvm_vcpu *vcpu;
49f705c5 5731 /*
55d2375e
SC
5732 * We only need to kick vcpu out of guest mode here, as PML buffer
5733 * is flushed at beginning of all VMEXITs, and it's obvious that only
5734 * vcpus running in guest are possible to have unflushed GPAs in PML
5735 * buffer.
49f705c5 5736 */
55d2375e
SC
5737 kvm_for_each_vcpu(i, vcpu, kvm)
5738 kvm_vcpu_kick(vcpu);
49f705c5
NHE
5739}
5740
55d2375e 5741static void vmx_dump_sel(char *name, uint32_t sel)
49f705c5 5742{
55d2375e
SC
5743 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5744 name, vmcs_read16(sel),
5745 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5746 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5747 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
49f705c5
NHE
5748}
5749
55d2375e 5750static void vmx_dump_dtsel(char *name, uint32_t limit)
a8bc284e 5751{
55d2375e
SC
5752 pr_err("%s limit=0x%08x, base=0x%016lx\n",
5753 name, vmcs_read32(limit),
5754 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
a8bc284e
JM
5755}
5756
69090810 5757void dump_vmcs(void)
63846663 5758{
6f2f8453
PB
5759 u32 vmentry_ctl, vmexit_ctl;
5760 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5761 unsigned long cr4;
63846663 5762
6f2f8453
PB
5763 if (!dump_invalid_vmcs) {
5764 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5765 return;
5766 }
5767
5768 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5769 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5770 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5771 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5772 cr4 = vmcs_readl(GUEST_CR4);
6f2f8453 5773 secondary_exec_control = 0;
55d2375e
SC
5774 if (cpu_has_secondary_exec_ctrls())
5775 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
14c07ad8 5776
55d2375e
SC
5777 pr_err("*** Guest State ***\n");
5778 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5779 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5780 vmcs_readl(CR0_GUEST_HOST_MASK));
5781 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5782 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5783 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
75bc72f0 5784 if (cpu_has_vmx_ept()) {
55d2375e
SC
5785 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
5786 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5787 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
5788 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
e9ac033e 5789 }
55d2375e
SC
5790 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
5791 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5792 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
5793 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5794 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5795 vmcs_readl(GUEST_SYSENTER_ESP),
5796 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5797 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
5798 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
5799 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
5800 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
5801 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
5802 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
5803 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5804 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5805 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5806 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
5807 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5808 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5809 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
75bc72f0
DE
5810 vmcs_read64(GUEST_IA32_EFER),
5811 vmcs_read64(GUEST_IA32_PAT));
55d2375e
SC
5812 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
5813 vmcs_read64(GUEST_IA32_DEBUGCTL),
5814 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5815 if (cpu_has_load_perf_global_ctrl() &&
5816 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5817 pr_err("PerfGlobCtl = 0x%016llx\n",
5818 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5819 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5820 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5821 pr_err("Interruptibility = %08x ActivityState = %08x\n",
5822 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5823 vmcs_read32(GUEST_ACTIVITY_STATE));
5824 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5825 pr_err("InterruptStatus = %04x\n",
5826 vmcs_read16(GUEST_INTR_STATUS));
ff651cb6 5827
55d2375e
SC
5828 pr_err("*** Host State ***\n");
5829 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
5830 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5831 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5832 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5833 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5834 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5835 vmcs_read16(HOST_TR_SELECTOR));
5836 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5837 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5838 vmcs_readl(HOST_TR_BASE));
5839 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5840 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5841 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5842 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5843 vmcs_readl(HOST_CR4));
5844 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5845 vmcs_readl(HOST_IA32_SYSENTER_ESP),
5846 vmcs_read32(HOST_IA32_SYSENTER_CS),
5847 vmcs_readl(HOST_IA32_SYSENTER_EIP));
5848 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5849 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
5850 vmcs_read64(HOST_IA32_EFER),
5851 vmcs_read64(HOST_IA32_PAT));
5852 if (cpu_has_load_perf_global_ctrl() &&
5853 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5854 pr_err("PerfGlobCtl = 0x%016llx\n",
5855 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
ff651cb6 5856
55d2375e
SC
5857 pr_err("*** Control State ***\n");
5858 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5859 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5860 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5861 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5862 vmcs_read32(EXCEPTION_BITMAP),
5863 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5864 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5865 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5866 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5867 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5868 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5869 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5870 vmcs_read32(VM_EXIT_INTR_INFO),
5871 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5872 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5873 pr_err(" reason=%08x qualification=%016lx\n",
5874 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5875 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5876 vmcs_read32(IDT_VECTORING_INFO_FIELD),
5877 vmcs_read32(IDT_VECTORING_ERROR_CODE));
5878 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5879 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5880 pr_err("TSC Multiplier = 0x%016llx\n",
5881 vmcs_read64(TSC_MULTIPLIER));
9d609649
PB
5882 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5883 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5884 u16 status = vmcs_read16(GUEST_INTR_STATUS);
5885 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5886 }
d6a85c32 5887 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
9d609649
PB
5888 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5889 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
d6a85c32 5890 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
9d609649 5891 }
55d2375e
SC
5892 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5893 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5894 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5895 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
55d2375e
SC
5896 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5897 pr_err("PLE Gap=%08x Window=%08x\n",
5898 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5899 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5900 pr_err("Virtual processor ID = 0x%04x\n",
5901 vmcs_read16(VIRTUAL_PROCESSOR_ID));
ff651cb6
WV
5902}
5903
55d2375e
SC
5904/*
5905 * The guest has exited. See if we can fix it or if we need userspace
5906 * assistance.
5907 */
404d5d7b 5908static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
ff651cb6 5909{
55d2375e 5910 struct vcpu_vmx *vmx = to_vmx(vcpu);
a6bdda1f 5911 union vmx_exit_reason exit_reason = vmx->exit_reason;
55d2375e 5912 u32 vectoring_info = vmx->idt_vectoring_info;
a6bdda1f 5913 u16 exit_handler_index;
ff651cb6 5914
55d2375e
SC
5915 /*
5916 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5917 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5918 * querying dirty_bitmap, we only need to kick all vcpus out of guest
5919 * mode as if vcpus is in root mode, the PML buffer must has been
5920 * flushed already.
5921 */
5922 if (enable_pml)
5923 vmx_flush_pml_buffer(vcpu);
1dc35dac 5924
db438592
SC
5925 /*
5926 * We should never reach this point with a pending nested VM-Enter, and
5927 * more specifically emulation of L2 due to invalid guest state (see
5928 * below) should never happen as that means we incorrectly allowed a
5929 * nested VM-Enter with an invalid vmcs12.
5930 */
5931 WARN_ON_ONCE(vmx->nested.nested_run_pending);
5932
55d2375e
SC
5933 /* If guest state is invalid, start emulating */
5934 if (vmx->emulation_required)
5935 return handle_invalid_guest_state(vcpu);
1dc35dac 5936
96b100cd
PB
5937 if (is_guest_mode(vcpu)) {
5938 /*
5939 * The host physical addresses of some pages of guest memory
5940 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
5941 * Page). The CPU may write to these pages via their host
5942 * physical address while L2 is running, bypassing any
5943 * address-translation-based dirty tracking (e.g. EPT write
5944 * protection).
5945 *
5946 * Mark them dirty on every exit from L2 to prevent them from
5947 * getting out of sync with dirty tracking.
5948 */
5949 nested_mark_vmcs12_pages_dirty(vcpu);
5950
f47baaed 5951 if (nested_vmx_reflect_vmexit(vcpu))
789afc5c 5952 return 1;
96b100cd 5953 }
9ed38ffa 5954
a6bdda1f 5955 if (exit_reason.failed_vmentry) {
55d2375e
SC
5956 dump_vmcs();
5957 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5958 vcpu->run->fail_entry.hardware_entry_failure_reason
a6bdda1f 5959 = exit_reason.full;
8a14fe4f 5960 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
55d2375e 5961 return 0;
9ed38ffa
LP
5962 }
5963
55d2375e 5964 if (unlikely(vmx->fail)) {
3b20e03a 5965 dump_vmcs();
55d2375e
SC
5966 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5967 vcpu->run->fail_entry.hardware_entry_failure_reason
5968 = vmcs_read32(VM_INSTRUCTION_ERROR);
8a14fe4f 5969 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
55d2375e
SC
5970 return 0;
5971 }
50c28f21 5972
55d2375e
SC
5973 /*
5974 * Note:
5975 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5976 * delivery event since it indicates guest is accessing MMIO.
5977 * The vm-exit can be triggered again after return to guest that
5978 * will cause infinite loop.
5979 */
5980 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
a6bdda1f
SC
5981 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
5982 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
5983 exit_reason.basic != EXIT_REASON_PML_FULL &&
5984 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
5985 exit_reason.basic != EXIT_REASON_TASK_SWITCH)) {
d2be95d4
RW
5986 int ndata = 3;
5987
55d2375e
SC
5988 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5989 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
55d2375e 5990 vcpu->run->internal.data[0] = vectoring_info;
a6bdda1f 5991 vcpu->run->internal.data[1] = exit_reason.full;
55d2375e 5992 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
a6bdda1f 5993 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
d2be95d4 5994 vcpu->run->internal.data[ndata++] =
55d2375e
SC
5995 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5996 }
d2be95d4
RW
5997 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
5998 vcpu->run->internal.ndata = ndata;
55d2375e
SC
5999 return 0;
6000 }
50c28f21 6001
55d2375e
SC
6002 if (unlikely(!enable_vnmi &&
6003 vmx->loaded_vmcs->soft_vnmi_blocked)) {
db438592 6004 if (!vmx_interrupt_blocked(vcpu)) {
55d2375e
SC
6005 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6006 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6007 vcpu->arch.nmi_pending) {
6008 /*
6009 * This CPU don't support us in finding the end of an
6010 * NMI-blocked window if the guest runs with IRQs
6011 * disabled. So we pull the trigger after 1 s of
6012 * futile waiting, but inform the user about this.
6013 */
6014 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6015 "state on VCPU %d after 1 s timeout\n",
6016 __func__, vcpu->vcpu_id);
6017 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6018 }
6019 }
50c28f21 6020
404d5d7b 6021 if (exit_fastpath != EXIT_FASTPATH_NONE)
1e9e2622 6022 return 1;
c926f2f7 6023
a6bdda1f 6024 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
c926f2f7 6025 goto unexpected_vmexit;
4289d272 6026#ifdef CONFIG_RETPOLINE
a6bdda1f 6027 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
c926f2f7 6028 return kvm_emulate_wrmsr(vcpu);
a6bdda1f 6029 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
c926f2f7 6030 return handle_preemption_timer(vcpu);
a6bdda1f 6031 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
c926f2f7 6032 return handle_interrupt_window(vcpu);
a6bdda1f 6033 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
c926f2f7 6034 return handle_external_interrupt(vcpu);
a6bdda1f 6035 else if (exit_reason.basic == EXIT_REASON_HLT)
c926f2f7 6036 return kvm_emulate_halt(vcpu);
a6bdda1f 6037 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
c926f2f7 6038 return handle_ept_misconfig(vcpu);
4289d272 6039#endif
c926f2f7 6040
a6bdda1f
SC
6041 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6042 kvm_vmx_max_exit_handlers);
6043 if (!kvm_vmx_exit_handlers[exit_handler_index])
c926f2f7
MP
6044 goto unexpected_vmexit;
6045
a6bdda1f 6046 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
c926f2f7
MP
6047
6048unexpected_vmexit:
a6bdda1f
SC
6049 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6050 exit_reason.full);
c926f2f7
MP
6051 dump_vmcs();
6052 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6053 vcpu->run->internal.suberror =
7396d337 6054 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
1aa561b1 6055 vcpu->run->internal.ndata = 2;
a6bdda1f 6056 vcpu->run->internal.data[0] = exit_reason.full;
8a14fe4f 6057 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
c926f2f7 6058 return 0;
9ed38ffa
LP
6059}
6060
efebf0aa 6061/*
55d2375e
SC
6062 * Software based L1D cache flush which is used when microcode providing
6063 * the cache control MSR is not loaded.
efebf0aa 6064 *
55d2375e
SC
6065 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6066 * flush it is required to read in 64 KiB because the replacement algorithm
6067 * is not exactly LRU. This could be sized at runtime via topology
6068 * information but as all relevant affected CPUs have 32KiB L1D cache size
6069 * there is no point in doing so.
efebf0aa 6070 */
3ebccdf3 6071static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
fe3ef05c 6072{
55d2375e 6073 int size = PAGE_SIZE << L1D_CACHE_ORDER;
25a2e4fe
PB
6074
6075 /*
55d2375e
SC
6076 * This code is only executed when the the flush mode is 'cond' or
6077 * 'always'
25a2e4fe 6078 */
55d2375e
SC
6079 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6080 bool flush_l1d;
25a2e4fe 6081
55d2375e
SC
6082 /*
6083 * Clear the per-vcpu flush bit, it gets set again
6084 * either from vcpu_run() or from one of the unsafe
6085 * VMEXIT handlers.
6086 */
6087 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6088 vcpu->arch.l1tf_flush_l1d = false;
25a2e4fe 6089
55d2375e
SC
6090 /*
6091 * Clear the per-cpu flush bit, it gets set again from
6092 * the interrupt handlers.
6093 */
6094 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6095 kvm_clear_cpu_l1tf_flush_l1d();
25a2e4fe 6096
55d2375e
SC
6097 if (!flush_l1d)
6098 return;
6099 }
09abe320 6100
55d2375e 6101 vcpu->stat.l1d_flush++;
25a2e4fe 6102
55d2375e 6103 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
3ebccdf3 6104 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
55d2375e
SC
6105 return;
6106 }
25a2e4fe 6107
55d2375e
SC
6108 asm volatile(
6109 /* First ensure the pages are in the TLB */
6110 "xorl %%eax, %%eax\n"
6111 ".Lpopulate_tlb:\n\t"
6112 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6113 "addl $4096, %%eax\n\t"
6114 "cmpl %%eax, %[size]\n\t"
6115 "jne .Lpopulate_tlb\n\t"
6116 "xorl %%eax, %%eax\n\t"
6117 "cpuid\n\t"
6118 /* Now fill the cache */
6119 "xorl %%eax, %%eax\n"
6120 ".Lfill_cache:\n"
6121 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6122 "addl $64, %%eax\n\t"
6123 "cmpl %%eax, %[size]\n\t"
6124 "jne .Lfill_cache\n\t"
6125 "lfence\n"
6126 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6127 [size] "r" (size)
6128 : "eax", "ebx", "ecx", "edx");
09abe320 6129}
25a2e4fe 6130
55d2375e 6131static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
09abe320 6132{
55d2375e 6133 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
132f4f7e 6134 int tpr_threshold;
09abe320 6135
55d2375e
SC
6136 if (is_guest_mode(vcpu) &&
6137 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6138 return;
25a2e4fe 6139
132f4f7e 6140 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
02d496cf
LA
6141 if (is_guest_mode(vcpu))
6142 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6143 else
6144 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
8665c3f9
PB
6145}
6146
55d2375e 6147void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
8665c3f9 6148{
fe7f895d 6149 struct vcpu_vmx *vmx = to_vmx(vcpu);
55d2375e 6150 u32 sec_exec_control;
8665c3f9 6151
55d2375e
SC
6152 if (!lapic_in_kernel(vcpu))
6153 return;
9314006d 6154
55d2375e
SC
6155 if (!flexpriority_enabled &&
6156 !cpu_has_vmx_virtualize_x2apic_mode())
6157 return;
705699a1 6158
55d2375e
SC
6159 /* Postpone execution until vmcs01 is the current VMCS. */
6160 if (is_guest_mode(vcpu)) {
fe7f895d 6161 vmx->nested.change_vmcs01_virtual_apic_mode = true;
55d2375e 6162 return;
6beb7bd5 6163 }
fe3ef05c 6164
fe7f895d 6165 sec_exec_control = secondary_exec_controls_get(vmx);
55d2375e
SC
6166 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6167 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
09abe320 6168
55d2375e
SC
6169 switch (kvm_get_apic_mode(vcpu)) {
6170 case LAPIC_MODE_INVALID:
6171 WARN_ONCE(true, "Invalid local APIC state");
6172 case LAPIC_MODE_DISABLED:
6173 break;
6174 case LAPIC_MODE_XAPIC:
6175 if (flexpriority_enabled) {
6176 sec_exec_control |=
6177 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4de1f9d4
SC
6178 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6179
6180 /*
6181 * Flush the TLB, reloading the APIC access page will
6182 * only do so if its physical address has changed, but
6183 * the guest may have inserted a non-APIC mapping into
6184 * the TLB while the APIC access page was disabled.
6185 */
6186 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
55d2375e
SC
6187 }
6188 break;
6189 case LAPIC_MODE_X2APIC:
6190 if (cpu_has_vmx_virtualize_x2apic_mode())
6191 sec_exec_control |=
6192 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6193 break;
09abe320 6194 }
fe7f895d 6195 secondary_exec_controls_set(vmx, sec_exec_control);
09abe320 6196
55d2375e
SC
6197 vmx_update_msr_bitmap(vcpu);
6198}
0238ea91 6199
a4148b7c 6200static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
55d2375e 6201{
a4148b7c
SC
6202 struct page *page;
6203
1196cb97
SC
6204 /* Defer reload until vmcs01 is the current VMCS. */
6205 if (is_guest_mode(vcpu)) {
6206 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6207 return;
55d2375e 6208 }
1196cb97 6209
4de1f9d4
SC
6210 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6211 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6212 return;
6213
a4148b7c
SC
6214 page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6215 if (is_error_page(page))
6216 return;
6217
6218 vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
1196cb97 6219 vmx_flush_tlb_current(vcpu);
a4148b7c
SC
6220
6221 /*
6222 * Do not pin apic access page in memory, the MMU notifier
6223 * will call us again if it is migrated or swapped out.
6224 */
6225 put_page(page);
55d2375e 6226}
fe3ef05c 6227
55d2375e
SC
6228static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6229{
6230 u16 status;
6231 u8 old;
32c7acf0 6232
55d2375e
SC
6233 if (max_isr == -1)
6234 max_isr = 0;
608406e2 6235
55d2375e
SC
6236 status = vmcs_read16(GUEST_INTR_STATUS);
6237 old = status >> 8;
6238 if (max_isr != old) {
6239 status &= 0xff;
6240 status |= max_isr << 8;
6241 vmcs_write16(GUEST_INTR_STATUS, status);
6242 }
6243}
6beb7bd5 6244
55d2375e
SC
6245static void vmx_set_rvi(int vector)
6246{
6247 u16 status;
6248 u8 old;
0b665d30 6249
55d2375e
SC
6250 if (vector == -1)
6251 vector = 0;
fe3ef05c 6252
55d2375e
SC
6253 status = vmcs_read16(GUEST_INTR_STATUS);
6254 old = (u8)status & 0xff;
6255 if ((u8)vector != old) {
6256 status &= ~0xff;
6257 status |= (u8)vector;
6258 vmcs_write16(GUEST_INTR_STATUS, status);
09abe320 6259 }
55d2375e 6260}
09abe320 6261
55d2375e
SC
6262static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6263{
09abe320 6264 /*
55d2375e
SC
6265 * When running L2, updating RVI is only relevant when
6266 * vmcs12 virtual-interrupt-delivery enabled.
6267 * However, it can be enabled only when L1 also
6268 * intercepts external-interrupts and in that case
6269 * we should not update vmcs02 RVI but instead intercept
6270 * interrupt. Therefore, do nothing when running L2.
fe3ef05c 6271 */
55d2375e
SC
6272 if (!is_guest_mode(vcpu))
6273 vmx_set_rvi(max_irr);
6274}
fe3ef05c 6275
55d2375e
SC
6276static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6277{
6278 struct vcpu_vmx *vmx = to_vmx(vcpu);
6279 int max_irr;
6280 bool max_irr_updated;
a7c0b07d 6281
55d2375e
SC
6282 WARN_ON(!vcpu->arch.apicv_active);
6283 if (pi_test_on(&vmx->pi_desc)) {
6284 pi_clear_on(&vmx->pi_desc);
6285 /*
d9ff2744 6286 * IOMMU can write to PID.ON, so the barrier matters even on UP.
55d2375e
SC
6287 * But on x86 this is just a compiler barrier anyway.
6288 */
6289 smp_mb__after_atomic();
6290 max_irr_updated =
6291 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
c4ebd629
VK
6292
6293 /*
55d2375e
SC
6294 * If we are running L2 and L1 has a new pending interrupt
6295 * which can be injected, we should re-evaluate
6296 * what should be done with this new L1 interrupt.
6297 * If L1 intercepts external-interrupts, we should
6298 * exit from L2 to L1. Otherwise, interrupt should be
6299 * delivered directly to L2.
c4ebd629 6300 */
55d2375e
SC
6301 if (is_guest_mode(vcpu) && max_irr_updated) {
6302 if (nested_exit_on_intr(vcpu))
6303 kvm_vcpu_exiting_guest_mode(vcpu);
6304 else
6305 kvm_make_request(KVM_REQ_EVENT, vcpu);
c4ebd629 6306 }
55d2375e
SC
6307 } else {
6308 max_irr = kvm_lapic_find_highest_irr(vcpu);
a7c0b07d 6309 }
55d2375e
SC
6310 vmx_hwapic_irr_update(vcpu, max_irr);
6311 return max_irr;
6312}
a7c0b07d 6313
55d2375e
SC
6314static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6315{
6316 if (!kvm_vcpu_apicv_active(vcpu))
6317 return;
25a2e4fe 6318
55d2375e
SC
6319 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6320 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6321 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6322 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
8665c3f9
PB
6323}
6324
55d2375e 6325static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
8665c3f9
PB
6326{
6327 struct vcpu_vmx *vmx = to_vmx(vcpu);
9d1887ef 6328
55d2375e
SC
6329 pi_clear_on(&vmx->pi_desc);
6330 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6331}
8665c3f9 6332
535f7ef2
SC
6333void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6334
1a5488ef
SC
6335static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu, u32 intr_info)
6336{
6337 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6338 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6339
6340 kvm_before_interrupt(vcpu);
6341 vmx_do_interrupt_nmi_irqoff(gate_offset(desc));
6342 kvm_after_interrupt(vcpu);
6343}
6344
95b5a48c 6345static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
55d2375e 6346{
87915858 6347 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
fe3ef05c 6348
55d2375e 6349 /* if exit due to PF check for async PF */
1a5488ef 6350 if (is_page_fault(intr_info))
68fd66f1 6351 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
55d2375e 6352 /* Handle machine checks before interrupts are enabled */
1a5488ef 6353 else if (is_machine_check(intr_info))
55d2375e 6354 kvm_machine_check();
55d2375e 6355 /* We need to handle NMIs before interrupts are enabled */
1a5488ef
SC
6356 else if (is_nmi(intr_info))
6357 handle_interrupt_nmi_irqoff(&vmx->vcpu, intr_info);
55d2375e 6358}
fe3ef05c 6359
95b5a48c 6360static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
55d2375e 6361{
87915858 6362 u32 intr_info = vmx_get_intr_info(vcpu);
fe3ef05c 6363
49def500
SC
6364 if (WARN_ONCE(!is_external_intr(intr_info),
6365 "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6366 return;
6367
1a5488ef 6368 handle_interrupt_nmi_irqoff(vcpu, intr_info);
55d2375e 6369}
95b5a48c 6370
a9ab13ff 6371static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
95b5a48c
SC
6372{
6373 struct vcpu_vmx *vmx = to_vmx(vcpu);
6374
a6bdda1f 6375 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
95b5a48c 6376 handle_external_interrupt_irqoff(vcpu);
a6bdda1f 6377 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
95b5a48c
SC
6378 handle_exception_nmi_irqoff(vmx);
6379}
5a6a9748 6380
5719455f
TL
6381/*
6382 * The kvm parameter can be NULL (module initialization, or invocation before
6383 * VM creation). Be sure to check the kvm parameter before using it.
6384 */
6385static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
55d2375e
SC
6386{
6387 switch (index) {
6388 case MSR_IA32_SMBASE:
6389 /*
6390 * We cannot do SMM unless we can run the guest in big
6391 * real mode.
6392 */
6393 return enable_unrestricted_guest || emulate_invalid_guest_state;
95c5c7c7
PB
6394 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6395 return nested;
55d2375e
SC
6396 case MSR_AMD64_VIRT_SPEC_CTRL:
6397 /* This is AMD only. */
6398 return false;
6399 default:
6400 return true;
3184a995 6401 }
55d2375e 6402}
2bb8cafe 6403
55d2375e
SC
6404static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6405{
6406 u32 exit_intr_info;
6407 bool unblock_nmi;
6408 u8 vector;
6409 bool idtv_info_valid;
7ca29de2 6410
55d2375e 6411 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
feaf0c7d 6412
55d2375e
SC
6413 if (enable_vnmi) {
6414 if (vmx->loaded_vmcs->nmi_known_unmasked)
6415 return;
87915858
SC
6416
6417 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
55d2375e
SC
6418 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6419 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6420 /*
6421 * SDM 3: 27.7.1.2 (September 2008)
6422 * Re-set bit "block by NMI" before VM entry if vmexit caused by
6423 * a guest IRET fault.
6424 * SDM 3: 23.2.2 (September 2008)
6425 * Bit 12 is undefined in any of the following cases:
6426 * If the VM exit sets the valid bit in the IDT-vectoring
6427 * information field.
6428 * If the VM exit is due to a double fault.
6429 */
6430 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6431 vector != DF_VECTOR && !idtv_info_valid)
6432 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6433 GUEST_INTR_STATE_NMI);
6434 else
6435 vmx->loaded_vmcs->nmi_known_unmasked =
6436 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6437 & GUEST_INTR_STATE_NMI);
6438 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6439 vmx->loaded_vmcs->vnmi_blocked_time +=
6440 ktime_to_ns(ktime_sub(ktime_get(),
6441 vmx->loaded_vmcs->entry_time));
fe3ef05c
NHE
6442}
6443
55d2375e
SC
6444static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6445 u32 idt_vectoring_info,
6446 int instr_len_field,
6447 int error_code_field)
0c7f650e 6448{
55d2375e
SC
6449 u8 vector;
6450 int type;
6451 bool idtv_info_valid;
0c7f650e 6452
55d2375e 6453 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
0c7f650e 6454
55d2375e
SC
6455 vcpu->arch.nmi_injected = false;
6456 kvm_clear_exception_queue(vcpu);
6457 kvm_clear_interrupt_queue(vcpu);
27c42a1b 6458
55d2375e
SC
6459 if (!idtv_info_valid)
6460 return;
c7c2c709 6461
55d2375e 6462 kvm_make_request(KVM_REQ_EVENT, vcpu);
ca0bde28 6463
55d2375e
SC
6464 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6465 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
64a919f7 6466
55d2375e
SC
6467 switch (type) {
6468 case INTR_TYPE_NMI_INTR:
6469 vcpu->arch.nmi_injected = true;
6470 /*
6471 * SDM 3: 27.7.1.2 (September 2008)
6472 * Clear bit "block by NMI" before VM entry if a NMI
6473 * delivery faulted.
6474 */
6475 vmx_set_nmi_mask(vcpu, false);
6476 break;
6477 case INTR_TYPE_SOFT_EXCEPTION:
6478 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
df561f66 6479 fallthrough;
55d2375e
SC
6480 case INTR_TYPE_HARD_EXCEPTION:
6481 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6482 u32 err = vmcs_read32(error_code_field);
6483 kvm_requeue_exception_e(vcpu, vector, err);
6484 } else
6485 kvm_requeue_exception(vcpu, vector);
6486 break;
6487 case INTR_TYPE_SOFT_INTR:
6488 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
df561f66 6489 fallthrough;
55d2375e
SC
6490 case INTR_TYPE_EXT_INTR:
6491 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6492 break;
6493 default:
6494 break;
0447378a 6495 }
ca0bde28
JM
6496}
6497
55d2375e 6498static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
f145d90d 6499{
55d2375e
SC
6500 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6501 VM_EXIT_INSTRUCTION_LEN,
6502 IDT_VECTORING_ERROR_CODE);
f145d90d
LA
6503}
6504
55d2375e 6505static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
ca0bde28 6506{
55d2375e
SC
6507 __vmx_complete_interrupts(vcpu,
6508 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6509 VM_ENTRY_INSTRUCTION_LEN,
6510 VM_ENTRY_EXCEPTION_ERROR_CODE);
f1b026a3 6511
55d2375e 6512 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
ca0bde28
JM
6513}
6514
55d2375e 6515static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
52017608 6516{
55d2375e
SC
6517 int i, nr_msrs;
6518 struct perf_guest_switch_msr *msrs;
7c177938 6519
55d2375e 6520 msrs = perf_guest_get_msrs(&nr_msrs);
384bb783 6521
55d2375e
SC
6522 if (!msrs)
6523 return;
f1b026a3 6524
55d2375e
SC
6525 for (i = 0; i < nr_msrs; i++)
6526 if (msrs[i].host == msrs[i].guest)
6527 clear_atomic_switch_msr(vmx, msrs[i].msr);
6528 else
6529 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6530 msrs[i].host, false);
ca0bde28 6531}
52017608 6532
55d2375e 6533static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
858e25c0
JM
6534{
6535 struct vcpu_vmx *vmx = to_vmx(vcpu);
55d2375e
SC
6536 u64 tscl;
6537 u32 delta_tsc;
52017608 6538
55d2375e 6539 if (vmx->req_immediate_exit) {
804939ea
SC
6540 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6541 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6542 } else if (vmx->hv_deadline_tsc != -1) {
55d2375e
SC
6543 tscl = rdtsc();
6544 if (vmx->hv_deadline_tsc > tscl)
6545 /* set_hv_timer ensures the delta fits in 32-bits */
6546 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6547 cpu_preemption_timer_multi);
6548 else
6549 delta_tsc = 0;
858e25c0 6550
804939ea
SC
6551 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6552 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6553 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6554 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6555 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
7f7f1ba3 6556 }
858e25c0
JM
6557}
6558
3ebccdf3 6559void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
ca0bde28 6560{
c09b03eb
SC
6561 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6562 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6563 vmcs_writel(HOST_RSP, host_rsp);
6564 }
5ad6ece8 6565}
5f3d5799 6566
404d5d7b 6567static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
dcf068da 6568{
a6bdda1f 6569 switch (to_vmx(vcpu)->exit_reason.basic) {
dcf068da
WL
6570 case EXIT_REASON_MSR_WRITE:
6571 return handle_fastpath_set_msr_irqoff(vcpu);
26efe2fd
WL
6572 case EXIT_REASON_PREEMPTION_TIMER:
6573 return handle_fastpath_preemption_timer(vcpu);
dcf068da
WL
6574 default:
6575 return EXIT_FASTPATH_NONE;
6576 }
6577}
6578
fc2ba5a2 6579bool __vmx_vcpu_run(struct vcpu_vmx *vmx, unsigned long *regs, bool launched);
5ad6ece8 6580
3ebccdf3
TG
6581static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6582 struct vcpu_vmx *vmx)
6583{
6584 /*
6585 * VMENTER enables interrupts (host state), but the kernel state is
6586 * interrupts disabled when this is invoked. Also tell RCU about
6587 * it. This is the same logic as for exit_to_user_mode().
6588 *
6589 * This ensures that e.g. latency analysis on the host observes
6590 * guest mode as interrupt enabled.
6591 *
6592 * guest_enter_irqoff() informs context tracking about the
6593 * transition to guest mode and if enabled adjusts RCU state
6594 * accordingly.
6595 */
6596 instrumentation_begin();
6597 trace_hardirqs_on_prepare();
6598 lockdep_hardirqs_on_prepare(CALLER_ADDR0);
6599 instrumentation_end();
6600
6601 guest_enter_irqoff();
6602 lockdep_hardirqs_on(CALLER_ADDR0);
6603
6604 /* L1D Flush includes CPU buffer clear to mitigate MDS */
6605 if (static_branch_unlikely(&vmx_l1d_should_flush))
6606 vmx_l1d_flush(vcpu);
6607 else if (static_branch_unlikely(&mds_user_clear))
6608 mds_clear_cpu_buffers();
6609
2245d398
TG
6610 if (vcpu->arch.cr2 != native_read_cr2())
6611 native_write_cr2(vcpu->arch.cr2);
3ebccdf3
TG
6612
6613 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6614 vmx->loaded_vmcs->launched);
6615
2245d398 6616 vcpu->arch.cr2 = native_read_cr2();
3ebccdf3
TG
6617
6618 /*
6619 * VMEXIT disables interrupts (host state), but tracing and lockdep
6620 * have them in state 'on' as recorded before entering guest mode.
6621 * Same as enter_from_user_mode().
6622 *
6623 * guest_exit_irqoff() restores host context and reinstates RCU if
6624 * enabled and required.
6625 *
6626 * This needs to be done before the below as native_read_msr()
6627 * contains a tracepoint and x86_spec_ctrl_restore_host() calls
6628 * into world and some more.
6629 */
6630 lockdep_hardirqs_off(CALLER_ADDR0);
6631 guest_exit_irqoff();
6632
6633 instrumentation_begin();
6634 trace_hardirqs_off_finish();
6635 instrumentation_end();
6636}
6637
404d5d7b 6638static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
5ad6ece8 6639{
404d5d7b 6640 fastpath_t exit_fastpath;
5ad6ece8
SC
6641 struct vcpu_vmx *vmx = to_vmx(vcpu);
6642 unsigned long cr3, cr4;
6643
404d5d7b 6644reenter_guest:
5ad6ece8
SC
6645 /* Record the guest's net vcpu time for enforced NMI injections. */
6646 if (unlikely(!enable_vnmi &&
6647 vmx->loaded_vmcs->soft_vnmi_blocked))
6648 vmx->loaded_vmcs->entry_time = ktime_get();
6649
6650 /* Don't enter VMX if guest state is invalid, let the exit handler
6651 start emulation until we arrive back to a valid state */
6652 if (vmx->emulation_required)
a9ab13ff 6653 return EXIT_FASTPATH_NONE;
5ad6ece8 6654
d95df951
LB
6655 trace_kvm_entry(vcpu);
6656
5ad6ece8
SC
6657 if (vmx->ple_window_dirty) {
6658 vmx->ple_window_dirty = false;
6659 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6660 }
6661
c9dfd3fb 6662 /*
6663 * We did this in prepare_switch_to_guest, because it needs to
6664 * be within srcu_read_lock.
6665 */
6666 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
5ad6ece8 6667
cb3c1e2f 6668 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
5ad6ece8 6669 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
cb3c1e2f 6670 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
5ad6ece8
SC
6671 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6672
6673 cr3 = __get_current_cr3_fast();
6674 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6675 vmcs_writel(HOST_CR3, cr3);
6676 vmx->loaded_vmcs->host_state.cr3 = cr3;
6677 }
6678
6679 cr4 = cr4_read_shadow();
6680 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6681 vmcs_writel(HOST_CR4, cr4);
6682 vmx->loaded_vmcs->host_state.cr4 = cr4;
6683 }
6684
6685 /* When single-stepping over STI and MOV SS, we must clear the
6686 * corresponding interruptibility bits in the guest state. Otherwise
6687 * vmentry fails as it then expects bit 14 (BS) in pending debug
6688 * exceptions being set, but that's not correct for the guest debugging
6689 * case. */
6690 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6691 vmx_set_interrupt_shadow(vcpu, 0);
6692
139a12cf 6693 kvm_load_guest_xsave_state(vcpu);
1811d979 6694
5ad6ece8
SC
6695 pt_guest_enter(vmx);
6696
49097762 6697 atomic_switch_perf_msrs(vmx);
5ad6ece8 6698
804939ea
SC
6699 if (enable_preemption_timer)
6700 vmx_update_hv_timer(vcpu);
5ad6ece8 6701
010fd37f 6702 kvm_wait_lapic_expire(vcpu);
b6c4bc65 6703
5ad6ece8
SC
6704 /*
6705 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6706 * it's non-zero. Since vmentry is serialising on affected CPUs, there
6707 * is no need to worry about the conditional branch over the wrmsr
6708 * being speculatively taken.
6709 */
6710 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6711
3ebccdf3
TG
6712 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6713 vmx_vcpu_enter_exit(vcpu, vmx);
b6b8a145 6714
55d2375e
SC
6715 /*
6716 * We do not use IBRS in the kernel. If this vCPU has used the
6717 * SPEC_CTRL MSR it may have left it on; save the value and
6718 * turn it off. This is much more efficient than blindly adding
6719 * it to the atomic save/restore list. Especially as the former
6720 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6721 *
6722 * For non-nested case:
6723 * If the L01 MSR bitmap does not intercept the MSR, then we need to
6724 * save it.
6725 *
6726 * For nested case:
6727 * If the L02 MSR bitmap does not intercept the MSR, then we need to
6728 * save it.
6729 */
6730 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6731 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
b6b8a145 6732
55d2375e 6733 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
d264ee0c 6734
55d2375e
SC
6735 /* All fields are clean at this point */
6736 if (static_branch_unlikely(&enable_evmcs))
6737 current_evmcs->hv_clean_fields |=
6738 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
f4124500 6739
6f6a657c
VK
6740 if (static_branch_unlikely(&enable_evmcs))
6741 current_evmcs->hv_vp_id = vcpu->arch.hyperv.vp_index;
6742
55d2375e
SC
6743 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6744 if (vmx->host_debugctlmsr)
6745 update_debugctlmsr(vmx->host_debugctlmsr);
f4124500 6746
55d2375e
SC
6747#ifndef CONFIG_X86_64
6748 /*
6749 * The sysexit path does not restore ds/es, so we must set them to
6750 * a reasonable value ourselves.
6751 *
6752 * We can't defer this to vmx_prepare_switch_to_host() since that
6753 * function may be executed in interrupt context, which saves and
6754 * restore segments around it, nullifying its effect.
6755 */
6756 loadsegment(ds, __USER_DS);
6757 loadsegment(es, __USER_DS);
6758#endif
4704d0be 6759
e5d03de5 6760 vmx_register_cache_reset(vcpu);
7854cbca 6761
2ef444f1
CP
6762 pt_guest_exit(vmx);
6763
139a12cf 6764 kvm_load_host_xsave_state(vcpu);
1811d979 6765
55d2375e
SC
6766 vmx->nested.nested_run_pending = 0;
6767 vmx->idt_vectoring_info = 0;
119a9c01 6768
873e1da1 6769 if (unlikely(vmx->fail)) {
a6bdda1f 6770 vmx->exit_reason.full = 0xdead;
a9ab13ff 6771 return EXIT_FASTPATH_NONE;
873e1da1
SC
6772 }
6773
a6bdda1f
SC
6774 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
6775 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
beb8d93b
SC
6776 kvm_machine_check();
6777
a6bdda1f 6778 trace_kvm_exit(vmx->exit_reason.full, vcpu, KVM_ISA_VMX);
dcf068da 6779
a6bdda1f 6780 if (unlikely(vmx->exit_reason.failed_vmentry))
a9ab13ff
WL
6781 return EXIT_FASTPATH_NONE;
6782
55d2375e
SC
6783 vmx->loaded_vmcs->launched = 1;
6784 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
c18911a2 6785
55d2375e
SC
6786 vmx_recover_nmi_blocking(vmx);
6787 vmx_complete_interrupts(vmx);
a9ab13ff 6788
dcf068da
WL
6789 if (is_guest_mode(vcpu))
6790 return EXIT_FASTPATH_NONE;
6791
6792 exit_fastpath = vmx_exit_handlers_fastpath(vcpu);
404d5d7b
WL
6793 if (exit_fastpath == EXIT_FASTPATH_REENTER_GUEST) {
6794 if (!kvm_vcpu_exit_request(vcpu)) {
6795 /*
6796 * FIXME: this goto should be a loop in vcpu_enter_guest,
6797 * but it would incur the cost of a retpoline for now.
6798 * Revisit once static calls are available.
6799 */
379a3c8e
WL
6800 if (vcpu->arch.apicv_active)
6801 vmx_sync_pir_to_irr(vcpu);
404d5d7b
WL
6802 goto reenter_guest;
6803 }
6804 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
6805 }
6806
a9ab13ff 6807 return exit_fastpath;
55d2375e 6808}
2996fca0 6809
55d2375e 6810static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
cf8b84f4 6811{
55d2375e 6812 struct vcpu_vmx *vmx = to_vmx(vcpu);
4704d0be 6813
55d2375e
SC
6814 if (enable_pml)
6815 vmx_destroy_pml_buffer(vmx);
6816 free_vpid(vmx->vpid);
55d2375e
SC
6817 nested_vmx_free_vcpu(vcpu);
6818 free_loaded_vmcs(vmx->loaded_vmcs);
55d2375e 6819}
4704d0be 6820
987b2594 6821static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
55d2375e 6822{
41836839 6823 struct vcpu_vmx *vmx;
34109c04 6824 int i, cpu, err;
4704d0be 6825
a9dd6f09
SC
6826 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6827 vmx = to_vmx(vcpu);
d9a710e5 6828
55d2375e 6829 err = -ENOMEM;
b666a4b6 6830
55d2375e 6831 vmx->vpid = allocate_vpid();
7cdc2d62 6832
5f3d5799 6833 /*
55d2375e
SC
6834 * If PML is turned on, failure on enabling PML just results in failure
6835 * of creating the vcpu, therefore we can simplify PML logic (by
6836 * avoiding dealing with cases, such as enabling PML partially on vcpus
67b0ae43 6837 * for the guest), etc.
5f3d5799 6838 */
55d2375e 6839 if (enable_pml) {
41836839 6840 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
55d2375e 6841 if (!vmx->pml_pg)
987b2594 6842 goto free_vpid;
55d2375e 6843 }
4704d0be 6844
14a61b64 6845 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
4704d0be 6846
14a61b64
SC
6847 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i) {
6848 u32 index = vmx_uret_msrs_list[i];
4be53410 6849 u32 data_low, data_high;
fbc18007 6850 int j = vmx->nr_uret_msrs;
4be53410
XL
6851
6852 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6853 continue;
6854 if (wrmsr_safe(index, data_low, data_high) < 0)
6855 continue;
46f4f0aa 6856
802145c5 6857 vmx->guest_uret_msrs[j].slot = i;
eb3db1b1 6858 vmx->guest_uret_msrs[j].data = 0;
46f4f0aa
PB
6859 switch (index) {
6860 case MSR_IA32_TSX_CTRL:
6861 /*
7131636e
PB
6862 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID
6863 * interception. Keep the host value unchanged to avoid
6864 * changing CPUID bits under the host kernel's feet.
6865 *
6866 * hle=0, rtm=0, tsx_ctrl=1 can be found with some
6867 * combinations of new kernel and old userspace. If
6868 * those guests run on a tsx=off host, do allow guests
6869 * to use TSX_CTRL, but do not change the value on the
6870 * host so that TSX remains always disabled.
46f4f0aa 6871 */
7131636e
PB
6872 if (boot_cpu_has(X86_FEATURE_RTM))
6873 vmx->guest_uret_msrs[j].mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6874 else
6875 vmx->guest_uret_msrs[j].mask = 0;
46f4f0aa
PB
6876 break;
6877 default:
eb3db1b1 6878 vmx->guest_uret_msrs[j].mask = -1ull;
46f4f0aa
PB
6879 break;
6880 }
fbc18007 6881 ++vmx->nr_uret_msrs;
4be53410
XL
6882 }
6883
55d2375e
SC
6884 err = alloc_loaded_vmcs(&vmx->vmcs01);
6885 if (err < 0)
7d73710d 6886 goto free_pml;
cb61de2f 6887
3eb90017
AG
6888 /* The MSR bitmap starts with all ones */
6889 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6890 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
6891
476c9bd8
AL
6892 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
6893 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
6894 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
6895 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6896 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6897 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6898 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
987b2594 6899 if (kvm_cstate_in_guest(vcpu->kvm)) {
476c9bd8
AL
6900 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
6901 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6902 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6903 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
b5170063 6904 }
55d2375e 6905 vmx->msr_bitmap_mode = 0;
4704d0be 6906
55d2375e
SC
6907 vmx->loaded_vmcs = &vmx->vmcs01;
6908 cpu = get_cpu();
34109c04
SC
6909 vmx_vcpu_load(vcpu, cpu);
6910 vcpu->cpu = cpu;
1b84292b 6911 init_vmcs(vmx);
34109c04 6912 vmx_vcpu_put(vcpu);
55d2375e 6913 put_cpu();
34109c04 6914 if (cpu_need_virtualize_apic_accesses(vcpu)) {
987b2594 6915 err = alloc_apic_access_page(vcpu->kvm);
55d2375e
SC
6916 if (err)
6917 goto free_vmcs;
6918 }
6919
6920 if (enable_ept && !enable_unrestricted_guest) {
987b2594 6921 err = init_rmode_identity_map(vcpu->kvm);
55d2375e
SC
6922 if (err)
6923 goto free_vmcs;
6924 }
4704d0be 6925
55d2375e 6926 if (nested)
b9757a4b 6927 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
55d2375e
SC
6928 else
6929 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
bd18bffc 6930
55d2375e
SC
6931 vmx->nested.posted_intr_nv = -1;
6932 vmx->nested.current_vmptr = -1ull;
bd18bffc 6933
bab0c318 6934 vcpu->arch.microcode_version = 0x100000000ULL;
32ad73db 6935 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
feaf0c7d 6936
6f1e03bc 6937 /*
55d2375e
SC
6938 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6939 * or POSTED_INTR_WAKEUP_VECTOR.
6f1e03bc 6940 */
55d2375e
SC
6941 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6942 vmx->pi_desc.sn = 1;
4704d0be 6943
53963a70
LT
6944 vmx->ept_pointer = INVALID_PAGE;
6945
a9dd6f09 6946 return 0;
4704d0be 6947
55d2375e
SC
6948free_vmcs:
6949 free_loaded_vmcs(vmx->loaded_vmcs);
55d2375e
SC
6950free_pml:
6951 vmx_destroy_pml_buffer(vmx);
987b2594 6952free_vpid:
55d2375e 6953 free_vpid(vmx->vpid);
a9dd6f09 6954 return err;
55d2375e 6955}
36be0b9d 6956
65fd4cb6
TG
6957#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"
6958#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"
21feb4eb 6959
55d2375e
SC
6960static int vmx_vm_init(struct kvm *kvm)
6961{
6962 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
ff651cb6 6963
55d2375e
SC
6964 if (!ple_gap)
6965 kvm->arch.pause_in_guest = true;
3af18d9c 6966
55d2375e
SC
6967 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6968 switch (l1tf_mitigation) {
6969 case L1TF_MITIGATION_OFF:
6970 case L1TF_MITIGATION_FLUSH_NOWARN:
6971 /* 'I explicitly don't care' is set */
6972 break;
6973 case L1TF_MITIGATION_FLUSH:
6974 case L1TF_MITIGATION_FLUSH_NOSMT:
6975 case L1TF_MITIGATION_FULL:
6976 /*
6977 * Warn upon starting the first VM in a potentially
6978 * insecure environment.
6979 */
b284909a 6980 if (sched_smt_active())
55d2375e
SC
6981 pr_warn_once(L1TF_MSG_SMT);
6982 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
6983 pr_warn_once(L1TF_MSG_L1D);
6984 break;
6985 case L1TF_MITIGATION_FULL_FORCE:
6986 /* Flush is enforced */
6987 break;
6988 }
6989 }
4e19c36f 6990 kvm_apicv_init(kvm, enable_apicv);
55d2375e 6991 return 0;
4704d0be
NHE
6992}
6993
f257d6dc 6994static int __init vmx_check_processor_compat(void)
bd18bffc 6995{
55d2375e
SC
6996 struct vmcs_config vmcs_conf;
6997 struct vmx_capability vmx_cap;
bd18bffc 6998
ff10e22e
SC
6999 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7000 !this_cpu_has(X86_FEATURE_VMX)) {
7001 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7002 return -EIO;
7003 }
7004
55d2375e 7005 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
f257d6dc 7006 return -EIO;
55d2375e 7007 if (nested)
a4443267 7008 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
55d2375e
SC
7009 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7010 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7011 smp_processor_id());
f257d6dc 7012 return -EIO;
bd18bffc 7013 }
f257d6dc 7014 return 0;
bd18bffc
SC
7015}
7016
55d2375e 7017static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
bd18bffc 7018{
55d2375e
SC
7019 u8 cache;
7020 u64 ipat = 0;
bd18bffc 7021
222f06e7
CW
7022 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7023 * memory aliases with conflicting memory types and sometimes MCEs.
7024 * We have to be careful as to what are honored and when.
7025 *
7026 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7027 * UC. The effective memory type is UC or WC depending on guest PAT.
7028 * This was historically the source of MCEs and we want to be
7029 * conservative.
7030 *
7031 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7032 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7033 * EPT memory type is set to WB. The effective memory type is forced
7034 * WB.
7035 *
7036 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7037 * EPT memory type is used to emulate guest CD/MTRR.
bd18bffc 7038 */
222f06e7 7039
55d2375e
SC
7040 if (is_mmio) {
7041 cache = MTRR_TYPE_UNCACHABLE;
7042 goto exit;
7043 }
bd18bffc 7044
55d2375e
SC
7045 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7046 ipat = VMX_EPT_IPAT_BIT;
7047 cache = MTRR_TYPE_WRBACK;
7048 goto exit;
7049 }
bd18bffc 7050
55d2375e
SC
7051 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7052 ipat = VMX_EPT_IPAT_BIT;
7053 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7054 cache = MTRR_TYPE_WRBACK;
7055 else
7056 cache = MTRR_TYPE_UNCACHABLE;
7057 goto exit;
7058 }
bd18bffc 7059
55d2375e 7060 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
bd18bffc 7061
55d2375e
SC
7062exit:
7063 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7064}
bd18bffc 7065
fe7f895d 7066static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
55d2375e 7067{
bd18bffc 7068 /*
55d2375e
SC
7069 * These bits in the secondary execution controls field
7070 * are dynamic, the others are mostly based on the hypervisor
7071 * architecture and the guest's CPUID. Do not touch the
7072 * dynamic bits.
bd18bffc 7073 */
55d2375e
SC
7074 u32 mask =
7075 SECONDARY_EXEC_SHADOW_VMCS |
7076 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7077 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7078 SECONDARY_EXEC_DESC;
bd18bffc 7079
fe7f895d
SC
7080 u32 new_ctl = vmx->secondary_exec_control;
7081 u32 cur_ctl = secondary_exec_controls_get(vmx);
bd18bffc 7082
fe7f895d 7083 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
bd18bffc
SC
7084}
7085
4704d0be 7086/*
55d2375e
SC
7087 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7088 * (indicating "allowed-1") if they are supported in the guest's CPUID.
4704d0be 7089 */
55d2375e 7090static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
4704d0be
NHE
7091{
7092 struct vcpu_vmx *vmx = to_vmx(vcpu);
55d2375e 7093 struct kvm_cpuid_entry2 *entry;
4704d0be 7094
55d2375e
SC
7095 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7096 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
e79f245d 7097
55d2375e
SC
7098#define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7099 if (entry && (entry->_reg & (_cpuid_mask))) \
7100 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7101} while (0)
ff651cb6 7102
55d2375e 7103 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
87382003
SC
7104 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7105 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7106 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7107 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7108 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7109 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7110 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7111 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7112 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7113 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7114 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7115 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7116 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7117 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
61ada748 7118
55d2375e 7119 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
87382003
SC
7120 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7121 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7122 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7123 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7124 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7125 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
cf3215d9 7126
55d2375e
SC
7127#undef cr4_fixed1_update
7128}
36c3cc42 7129
55d2375e
SC
7130static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7131{
7132 struct vcpu_vmx *vmx = to_vmx(vcpu);
f459a707 7133
55d2375e
SC
7134 if (kvm_mpx_supported()) {
7135 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
4704d0be 7136
55d2375e
SC
7137 if (mpx_enabled) {
7138 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7139 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7140 } else {
7141 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7142 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7143 }
dccbfcf5 7144 }
55d2375e 7145}
4704d0be 7146
6c0f0bba
LK
7147static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7148{
7149 struct vcpu_vmx *vmx = to_vmx(vcpu);
7150 struct kvm_cpuid_entry2 *best = NULL;
7151 int i;
7152
7153 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7154 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7155 if (!best)
7156 return;
7157 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7158 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7159 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7160 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7161 }
7162
7163 /* Get the number of configurable Address Ranges for filtering */
7164 vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7165 PT_CAP_num_address_ranges);
7166
7167 /* Initialize and clear the no dependency bits */
7168 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7169 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7170
7171 /*
7172 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7173 * will inject an #GP
7174 */
7175 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7176 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7177
7178 /*
7179 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7180 * PSBFreq can be set
7181 */
7182 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7183 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7184 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7185
7186 /*
7187 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7188 * MTCFreq can be set
7189 */
7190 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7191 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7192 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7193
7194 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7195 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7196 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7197 RTIT_CTL_PTW_EN);
7198
7199 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7200 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7201 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7202
7203 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7204 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7205 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7206
7207 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
7208 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7209 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7210
7211 /* unmask address range configure area */
7212 for (i = 0; i < vmx->pt_desc.addr_range; i++)
d14eff1b 7213 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
6c0f0bba
LK
7214}
7215
7c1b761b 7216static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
55d2375e
SC
7217{
7218 struct vcpu_vmx *vmx = to_vmx(vcpu);
4704d0be 7219
7204160e
AL
7220 /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7221 vcpu->arch.xsaves_enabled = false;
7222
55d2375e
SC
7223 if (cpu_has_secondary_exec_ctrls()) {
7224 vmx_compute_secondary_exec_control(vmx);
fe7f895d 7225 vmcs_set_secondary_exec_control(vmx);
705699a1 7226 }
4704d0be 7227
55d2375e
SC
7228 if (nested_vmx_allowed(vcpu))
7229 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
32ad73db
SC
7230 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7231 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
55d2375e
SC
7232 else
7233 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
32ad73db
SC
7234 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7235 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
4f350c6d 7236
55d2375e
SC
7237 if (nested_vmx_allowed(vcpu)) {
7238 nested_vmx_cr_fixed1_bits_update(vcpu);
7239 nested_vmx_entry_exit_ctls_update(vcpu);
4f350c6d 7240 }
6c0f0bba
LK
7241
7242 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7243 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7244 update_intel_pt_cfg(vcpu);
b07a5c53
PB
7245
7246 if (boot_cpu_has(X86_FEATURE_RTM)) {
eb3db1b1 7247 struct vmx_uret_msr *msr;
d85a8034 7248 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
b07a5c53
PB
7249 if (msr) {
7250 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7bf662bb 7251 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
b07a5c53
PB
7252 }
7253 }
a6337a35 7254
2ed41aa6
SC
7255 set_cr4_guest_host_mask(vmx);
7256
a6337a35
SC
7257 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7258 update_exception_bitmap(vcpu);
55d2375e 7259}
09abb5e3 7260
3ec6fd8c 7261static __init void vmx_set_cpu_caps(void)
55d2375e 7262{
3ec6fd8c
SC
7263 kvm_set_cpu_caps();
7264
7265 /* CPUID 0x1 */
7266 if (nested)
7267 kvm_cpu_cap_set(X86_FEATURE_VMX);
7268
7269 /* CPUID 0x7 */
8721f5b0
SC
7270 if (kvm_mpx_supported())
7271 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7272 if (cpu_has_vmx_invpcid())
7273 kvm_cpu_cap_check_and_set(X86_FEATURE_INVPCID);
7274 if (vmx_pt_mode_is_host_guest())
7275 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
3ec6fd8c 7276
90d2f60f
SC
7277 if (vmx_umip_emulated())
7278 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7279
b3d895d5 7280 /* CPUID 0xD.1 */
408e9a31 7281 supported_xss = 0;
becdad85 7282 if (!cpu_has_vmx_xsaves())
b3d895d5
SC
7283 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7284
3ec6fd8c
SC
7285 /* CPUID 0x80000001 */
7286 if (!cpu_has_vmx_rdtscp())
7287 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
0abcc8f6 7288
becdad85 7289 if (cpu_has_vmx_waitpkg())
0abcc8f6 7290 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
4704d0be
NHE
7291}
7292
55d2375e 7293static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
42124925 7294{
55d2375e 7295 to_vmx(vcpu)->req_immediate_exit = true;
7c177938
NHE
7296}
7297
35a57134
OU
7298static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7299 struct x86_instruction_info *info)
7300{
7301 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7302 unsigned short port;
7303 bool intercept;
7304 int size;
7305
7306 if (info->intercept == x86_intercept_in ||
7307 info->intercept == x86_intercept_ins) {
7308 port = info->src_val;
7309 size = info->dst_bytes;
7310 } else {
7311 port = info->dst_val;
7312 size = info->src_bytes;
7313 }
7314
7315 /*
7316 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7317 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7318 * control.
7319 *
7320 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7321 */
7322 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7323 intercept = nested_cpu_has(vmcs12,
7324 CPU_BASED_UNCOND_IO_EXITING);
7325 else
7326 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7327
86f7e90c 7328 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
35a57134
OU
7329 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7330}
7331
8a76d7f2
JR
7332static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7333 struct x86_instruction_info *info,
21f1b8f2
SC
7334 enum x86_intercept_stage stage,
7335 struct x86_exception *exception)
8a76d7f2 7336{
fb6d4d34 7337 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
fb6d4d34 7338
35a57134 7339 switch (info->intercept) {
fb6d4d34
PB
7340 /*
7341 * RDPID causes #UD if disabled through secondary execution controls.
7342 * Because it is marked as EmulateOnUD, we need to intercept it here.
7343 */
35a57134 7344 case x86_intercept_rdtscp:
7f3603b6 7345 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
21f1b8f2
SC
7346 exception->vector = UD_VECTOR;
7347 exception->error_code_valid = false;
35a57134
OU
7348 return X86EMUL_PROPAGATE_FAULT;
7349 }
7350 break;
7351
7352 case x86_intercept_in:
7353 case x86_intercept_ins:
7354 case x86_intercept_out:
7355 case x86_intercept_outs:
7356 return vmx_check_intercept_io(vcpu, info);
fb6d4d34 7357
86f7e90c
OU
7358 case x86_intercept_lgdt:
7359 case x86_intercept_lidt:
7360 case x86_intercept_lldt:
7361 case x86_intercept_ltr:
7362 case x86_intercept_sgdt:
7363 case x86_intercept_sidt:
7364 case x86_intercept_sldt:
7365 case x86_intercept_str:
7366 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7367 return X86EMUL_CONTINUE;
7368
7369 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7370 break;
7371
fb6d4d34 7372 /* TODO: check more intercepts... */
35a57134
OU
7373 default:
7374 break;
7375 }
7376
07721fee 7377 return X86EMUL_UNHANDLEABLE;
8a76d7f2
JR
7378}
7379
64672c95
YJ
7380#ifdef CONFIG_X86_64
7381/* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7382static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7383 u64 divisor, u64 *result)
7384{
7385 u64 low = a << shift, high = a >> (64 - shift);
7386
7387 /* To avoid the overflow on divq */
7388 if (high >= divisor)
7389 return 1;
7390
7391 /* Low hold the result, high hold rem which is discarded */
7392 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7393 "rm" (divisor), "0" (low), "1" (high));
7394 *result = low;
7395
7396 return 0;
7397}
7398
f9927982
SC
7399static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7400 bool *expired)
64672c95 7401{
386c6ddb 7402 struct vcpu_vmx *vmx;
c5ce8235 7403 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
39497d76 7404 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
386c6ddb 7405
386c6ddb
KA
7406 vmx = to_vmx(vcpu);
7407 tscl = rdtsc();
7408 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7409 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
39497d76
SC
7410 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7411 ktimer->timer_advance_ns);
c5ce8235
WL
7412
7413 if (delta_tsc > lapic_timer_advance_cycles)
7414 delta_tsc -= lapic_timer_advance_cycles;
7415 else
7416 delta_tsc = 0;
64672c95
YJ
7417
7418 /* Convert to host delta tsc if tsc scaling is enabled */
7419 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
0967fa1c 7420 delta_tsc && u64_shl_div_u64(delta_tsc,
64672c95 7421 kvm_tsc_scaling_ratio_frac_bits,
0967fa1c 7422 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
64672c95
YJ
7423 return -ERANGE;
7424
7425 /*
7426 * If the delta tsc can't fit in the 32 bit after the multi shift,
7427 * we can't use the preemption timer.
7428 * It's possible that it fits on later vmentries, but checking
7429 * on every vmentry is costly so we just use an hrtimer.
7430 */
7431 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7432 return -ERANGE;
7433
7434 vmx->hv_deadline_tsc = tscl + delta_tsc;
f9927982
SC
7435 *expired = !delta_tsc;
7436 return 0;
64672c95
YJ
7437}
7438
7439static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7440{
f459a707 7441 to_vmx(vcpu)->hv_deadline_tsc = -1;
64672c95
YJ
7442}
7443#endif
7444
48d89b92 7445static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
ae97a3b8 7446{
b31c114b 7447 if (!kvm_pause_in_guest(vcpu->kvm))
b4a2d31d 7448 shrink_ple_window(vcpu);
ae97a3b8
RK
7449}
7450
843e4330
KH
7451static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7452 struct kvm_memory_slot *slot)
7453{
3c9bd400
JZ
7454 if (!kvm_dirty_log_manual_protect_and_init_set(kvm))
7455 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
843e4330
KH
7456 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7457}
7458
7459static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7460 struct kvm_memory_slot *slot)
7461{
7462 kvm_mmu_slot_set_dirty(kvm, slot);
7463}
7464
7465static void vmx_flush_log_dirty(struct kvm *kvm)
7466{
7467 kvm_flush_pml_buffers(kvm);
7468}
7469
7470static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7471 struct kvm_memory_slot *memslot,
7472 gfn_t offset, unsigned long mask)
7473{
7474 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7475}
7476
bc22512b
YJ
7477static int vmx_pre_block(struct kvm_vcpu *vcpu)
7478{
7479 if (pi_pre_block(vcpu))
7480 return 1;
7481
64672c95
YJ
7482 if (kvm_lapic_hv_timer_in_use(vcpu))
7483 kvm_lapic_switch_to_sw_timer(vcpu);
7484
bc22512b
YJ
7485 return 0;
7486}
7487
bc22512b
YJ
7488static void vmx_post_block(struct kvm_vcpu *vcpu)
7489{
afaf0b2f 7490 if (kvm_x86_ops.set_hv_timer)
64672c95
YJ
7491 kvm_lapic_switch_to_hv_timer(vcpu);
7492
bc22512b
YJ
7493 pi_post_block(vcpu);
7494}
7495
c45dcc71
AR
7496static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7497{
7498 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7499 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
32ad73db 7500 FEAT_CTL_LMCE_ENABLED;
c45dcc71
AR
7501 else
7502 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
32ad73db 7503 ~FEAT_CTL_LMCE_ENABLED;
c45dcc71
AR
7504}
7505
c9d40913 7506static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
72d7b374 7507{
72e9cbdb
LP
7508 /* we need a nested vmexit to enter SMM, postpone if run is pending */
7509 if (to_vmx(vcpu)->nested.nested_run_pending)
c9d40913 7510 return -EBUSY;
a9fa7cb6 7511 return !is_smm(vcpu);
72d7b374
LP
7512}
7513
0234bf88
LP
7514static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7515{
72e9cbdb
LP
7516 struct vcpu_vmx *vmx = to_vmx(vcpu);
7517
7518 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7519 if (vmx->nested.smm.guest_mode)
7520 nested_vmx_vmexit(vcpu, -1, 0, 0);
7521
7522 vmx->nested.smm.vmxon = vmx->nested.vmxon;
7523 vmx->nested.vmxon = false;
caa057a2 7524 vmx_clear_hlt(vcpu);
0234bf88
LP
7525 return 0;
7526}
7527
ed19321f 7528static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
0234bf88 7529{
72e9cbdb
LP
7530 struct vcpu_vmx *vmx = to_vmx(vcpu);
7531 int ret;
7532
7533 if (vmx->nested.smm.vmxon) {
7534 vmx->nested.vmxon = true;
7535 vmx->nested.smm.vmxon = false;
7536 }
7537
7538 if (vmx->nested.smm.guest_mode) {
a633e41e 7539 ret = nested_vmx_enter_non_root_mode(vcpu, false);
72e9cbdb
LP
7540 if (ret)
7541 return ret;
7542
7543 vmx->nested.smm.guest_mode = false;
7544 }
0234bf88
LP
7545 return 0;
7546}
7547
c9d40913 7548static void enable_smi_window(struct kvm_vcpu *vcpu)
cc3d967f 7549{
c9d40913 7550 /* RSM will cause a vmexit anyway. */
cc3d967f
LP
7551}
7552
4b9852f4
LA
7553static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7554{
1c96dcce 7555 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
4b9852f4
LA
7556}
7557
93dff2fe
JM
7558static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7559{
7560 if (is_guest_mode(vcpu)) {
7561 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7562
7563 if (hrtimer_try_to_cancel(timer) == 1)
7564 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7565 }
7566}
7567
6e4fd06f 7568static void hardware_unsetup(void)
484014fa
SC
7569{
7570 if (nested)
7571 nested_vmx_hardware_unsetup();
7572
7573 free_kvm_area();
7574}
7575
7576static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7577{
7578 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7579 BIT(APICV_INHIBIT_REASON_HYPERV);
7580
7581 return supported & BIT(bit);
7582}
7583
fb04a1ed
PX
7584static int vmx_cpu_dirty_log_size(void)
7585{
7586 return enable_pml ? PML_ENTITY_NUM : 0;
7587}
7588
e286ac0e 7589static struct kvm_x86_ops vmx_x86_ops __initdata = {
484014fa
SC
7590 .hardware_unsetup = hardware_unsetup,
7591
7592 .hardware_enable = hardware_enable,
7593 .hardware_disable = hardware_disable,
7594 .cpu_has_accelerated_tpr = report_flexpriority,
7595 .has_emulated_msr = vmx_has_emulated_msr,
7596
7597 .vm_size = sizeof(struct kvm_vmx),
7598 .vm_init = vmx_vm_init,
7599
7600 .vcpu_create = vmx_create_vcpu,
7601 .vcpu_free = vmx_free_vcpu,
7602 .vcpu_reset = vmx_vcpu_reset,
7603
7604 .prepare_guest_switch = vmx_prepare_switch_to_guest,
7605 .vcpu_load = vmx_vcpu_load,
7606 .vcpu_put = vmx_vcpu_put,
7607
6986982f 7608 .update_exception_bitmap = update_exception_bitmap,
484014fa
SC
7609 .get_msr_feature = vmx_get_msr_feature,
7610 .get_msr = vmx_get_msr,
7611 .set_msr = vmx_set_msr,
7612 .get_segment_base = vmx_get_segment_base,
7613 .get_segment = vmx_get_segment,
7614 .set_segment = vmx_set_segment,
7615 .get_cpl = vmx_get_cpl,
7616 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
484014fa 7617 .set_cr0 = vmx_set_cr0,
c2fe3cd4 7618 .is_valid_cr4 = vmx_is_valid_cr4,
484014fa
SC
7619 .set_cr4 = vmx_set_cr4,
7620 .set_efer = vmx_set_efer,
7621 .get_idt = vmx_get_idt,
7622 .set_idt = vmx_set_idt,
7623 .get_gdt = vmx_get_gdt,
7624 .set_gdt = vmx_set_gdt,
484014fa
SC
7625 .set_dr7 = vmx_set_dr7,
7626 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7627 .cache_reg = vmx_cache_reg,
7628 .get_rflags = vmx_get_rflags,
7629 .set_rflags = vmx_set_rflags,
7630
7780938c 7631 .tlb_flush_all = vmx_flush_tlb_all,
eeeb4f67 7632 .tlb_flush_current = vmx_flush_tlb_current,
484014fa 7633 .tlb_flush_gva = vmx_flush_tlb_gva,
e64419d9 7634 .tlb_flush_guest = vmx_flush_tlb_guest,
484014fa
SC
7635
7636 .run = vmx_vcpu_run,
7637 .handle_exit = vmx_handle_exit,
7638 .skip_emulated_instruction = vmx_skip_emulated_instruction,
7639 .update_emulated_instruction = vmx_update_emulated_instruction,
7640 .set_interrupt_shadow = vmx_set_interrupt_shadow,
7641 .get_interrupt_shadow = vmx_get_interrupt_shadow,
7642 .patch_hypercall = vmx_patch_hypercall,
7643 .set_irq = vmx_inject_irq,
7644 .set_nmi = vmx_inject_nmi,
7645 .queue_exception = vmx_queue_exception,
7646 .cancel_injection = vmx_cancel_injection,
7647 .interrupt_allowed = vmx_interrupt_allowed,
7648 .nmi_allowed = vmx_nmi_allowed,
7649 .get_nmi_mask = vmx_get_nmi_mask,
7650 .set_nmi_mask = vmx_set_nmi_mask,
7651 .enable_nmi_window = enable_nmi_window,
7652 .enable_irq_window = enable_irq_window,
7653 .update_cr8_intercept = update_cr8_intercept,
7654 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7655 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7656 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7657 .load_eoi_exitmap = vmx_load_eoi_exitmap,
7658 .apicv_post_state_restore = vmx_apicv_post_state_restore,
7659 .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7660 .hwapic_irr_update = vmx_hwapic_irr_update,
7661 .hwapic_isr_update = vmx_hwapic_isr_update,
7662 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7663 .sync_pir_to_irr = vmx_sync_pir_to_irr,
7664 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
8888cdd0 7665 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
484014fa
SC
7666
7667 .set_tss_addr = vmx_set_tss_addr,
7668 .set_identity_map_addr = vmx_set_identity_map_addr,
484014fa
SC
7669 .get_mt_mask = vmx_get_mt_mask,
7670
7671 .get_exit_info = vmx_get_exit_info,
7672
7c1b761b 7673 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
484014fa
SC
7674
7675 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7676
484014fa
SC
7677 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7678
7679 .load_mmu_pgd = vmx_load_mmu_pgd,
7680
7681 .check_intercept = vmx_check_intercept,
7682 .handle_exit_irqoff = vmx_handle_exit_irqoff,
7683
7684 .request_immediate_exit = vmx_request_immediate_exit,
7685
7686 .sched_in = vmx_sched_in,
7687
7688 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7689 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7690 .flush_log_dirty = vmx_flush_log_dirty,
7691 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
484014fa
SC
7692
7693 .pre_block = vmx_pre_block,
7694 .post_block = vmx_post_block,
7695
7696 .pmu_ops = &intel_pmu_ops,
33b22172 7697 .nested_ops = &vmx_nested_ops,
484014fa 7698
8888cdd0 7699 .update_pi_irte = pi_update_irte,
484014fa
SC
7700
7701#ifdef CONFIG_X86_64
7702 .set_hv_timer = vmx_set_hv_timer,
7703 .cancel_hv_timer = vmx_cancel_hv_timer,
7704#endif
7705
7706 .setup_mce = vmx_setup_mce,
7707
7708 .smi_allowed = vmx_smi_allowed,
7709 .pre_enter_smm = vmx_pre_enter_smm,
7710 .pre_leave_smm = vmx_pre_leave_smm,
7711 .enable_smi_window = enable_smi_window,
7712
09e3e2a1 7713 .can_emulate_instruction = vmx_can_emulate_instruction,
484014fa 7714 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
93dff2fe 7715 .migrate_timers = vmx_migrate_timers,
3eb90017
AG
7716
7717 .msr_filter_changed = vmx_msr_filter_changed,
f9a4d621 7718 .complete_emulated_msr = kvm_complete_insn_gp,
fb04a1ed 7719 .cpu_dirty_log_size = vmx_cpu_dirty_log_size,
647daca2
TL
7720
7721 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
484014fa
SC
7722};
7723
a3203381
SC
7724static __init int hardware_setup(void)
7725{
7726 unsigned long host_bndcfgs;
2342080c 7727 struct desc_ptr dt;
703c335d 7728 int r, i, ept_lpage_level;
a3203381 7729
2342080c
SC
7730 store_idt(&dt);
7731 host_idt_base = dt.address;
7732
14a61b64
SC
7733 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
7734 kvm_define_user_return_msr(i, vmx_uret_msrs_list[i]);
a3203381
SC
7735
7736 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7737 return -EIO;
7738
7739 if (boot_cpu_has(X86_FEATURE_NX))
7740 kvm_enable_efer_bits(EFER_NX);
7741
7742 if (boot_cpu_has(X86_FEATURE_MPX)) {
7743 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7744 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7745 }
7746
7f5581f5 7747 if (!cpu_has_vmx_mpx())
cfc48181
SC
7748 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
7749 XFEATURE_MASK_BNDCSR);
7750
a3203381
SC
7751 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7752 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7753 enable_vpid = 0;
7754
7755 if (!cpu_has_vmx_ept() ||
7756 !cpu_has_vmx_ept_4levels() ||
7757 !cpu_has_vmx_ept_mt_wb() ||
7758 !cpu_has_vmx_invept_global())
7759 enable_ept = 0;
7760
7761 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7762 enable_ept_ad_bits = 0;
7763
7764 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7765 enable_unrestricted_guest = 0;
7766
7767 if (!cpu_has_vmx_flexpriority())
7768 flexpriority_enabled = 0;
7769
7770 if (!cpu_has_virtual_nmis())
7771 enable_vnmi = 0;
7772
7773 /*
7774 * set_apic_access_page_addr() is used to reload apic access
7775 * page upon invalidation. No need to do anything if not
7776 * using the APIC_ACCESS_ADDR VMCS field.
7777 */
7778 if (!flexpriority_enabled)
72b0eaa9 7779 vmx_x86_ops.set_apic_access_page_addr = NULL;
a3203381
SC
7780
7781 if (!cpu_has_vmx_tpr_shadow())
72b0eaa9 7782 vmx_x86_ops.update_cr8_intercept = NULL;
a3203381
SC
7783
7784#if IS_ENABLED(CONFIG_HYPERV)
7785 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
1f3a3e46 7786 && enable_ept) {
72b0eaa9
SC
7787 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
7788 vmx_x86_ops.tlb_remote_flush_with_range =
1f3a3e46
LT
7789 hv_remote_flush_tlb_with_range;
7790 }
a3203381
SC
7791#endif
7792
7793 if (!cpu_has_vmx_ple()) {
7794 ple_gap = 0;
7795 ple_window = 0;
7796 ple_window_grow = 0;
7797 ple_window_max = 0;
7798 ple_window_shrink = 0;
7799 }
7800
7801 if (!cpu_has_vmx_apicv()) {
7802 enable_apicv = 0;
72b0eaa9 7803 vmx_x86_ops.sync_pir_to_irr = NULL;
a3203381
SC
7804 }
7805
7806 if (cpu_has_vmx_tsc_scaling()) {
7807 kvm_has_tsc_control = true;
7808 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7809 kvm_tsc_scaling_ratio_frac_bits = 48;
7810 }
7811
7812 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7813
7814 if (enable_ept)
7815 vmx_enable_tdp();
703c335d
SC
7816
7817 if (!enable_ept)
7818 ept_lpage_level = 0;
7819 else if (cpu_has_vmx_ept_1g_page())
3bae0459 7820 ept_lpage_level = PG_LEVEL_1G;
703c335d 7821 else if (cpu_has_vmx_ept_2m_page())
3bae0459 7822 ept_lpage_level = PG_LEVEL_2M;
a3203381 7823 else
3bae0459 7824 ept_lpage_level = PG_LEVEL_4K;
83013059 7825 kvm_configure_mmu(enable_ept, vmx_get_max_tdp_level(), ept_lpage_level);
a3203381 7826
a3203381
SC
7827 /*
7828 * Only enable PML when hardware supports PML feature, and both EPT
7829 * and EPT A/D bit features are enabled -- PML depends on them to work.
7830 */
7831 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7832 enable_pml = 0;
7833
7834 if (!enable_pml) {
72b0eaa9
SC
7835 vmx_x86_ops.slot_enable_log_dirty = NULL;
7836 vmx_x86_ops.slot_disable_log_dirty = NULL;
7837 vmx_x86_ops.flush_log_dirty = NULL;
7838 vmx_x86_ops.enable_log_dirty_pt_masked = NULL;
fb04a1ed 7839 vmx_x86_ops.cpu_dirty_log_size = NULL;
a3203381
SC
7840 }
7841
7842 if (!cpu_has_vmx_preemption_timer())
804939ea 7843 enable_preemption_timer = false;
a3203381 7844
804939ea
SC
7845 if (enable_preemption_timer) {
7846 u64 use_timer_freq = 5000ULL * 1000 * 1000;
a3203381
SC
7847 u64 vmx_msr;
7848
7849 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7850 cpu_preemption_timer_multi =
7851 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
804939ea
SC
7852
7853 if (tsc_khz)
7854 use_timer_freq = (u64)tsc_khz * 1000;
7855 use_timer_freq >>= cpu_preemption_timer_multi;
7856
7857 /*
7858 * KVM "disables" the preemption timer by setting it to its max
7859 * value. Don't use the timer if it might cause spurious exits
7860 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
7861 */
7862 if (use_timer_freq > 0xffffffffu / 10)
7863 enable_preemption_timer = false;
7864 }
7865
7866 if (!enable_preemption_timer) {
72b0eaa9
SC
7867 vmx_x86_ops.set_hv_timer = NULL;
7868 vmx_x86_ops.cancel_hv_timer = NULL;
7869 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
a3203381
SC
7870 }
7871
8888cdd0 7872 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
a3203381
SC
7873
7874 kvm_mce_cap_supported |= MCG_LMCE_P;
7875
f99e3daf
CP
7876 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
7877 return -EINVAL;
7878 if (!enable_ept || !cpu_has_vmx_intel_pt())
7879 pt_mode = PT_MODE_SYSTEM;
7880
a3203381 7881 if (nested) {
3e8eaccc 7882 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
a4443267 7883 vmx_capability.ept);
3e8eaccc 7884
6c1c6e58 7885 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
a3203381
SC
7886 if (r)
7887 return r;
7888 }
7889
3ec6fd8c 7890 vmx_set_cpu_caps();
66a6950f 7891
a3203381
SC
7892 r = alloc_kvm_area();
7893 if (r)
7894 nested_vmx_hardware_unsetup();
7895 return r;
7896}
7897
d008dfdb 7898static struct kvm_x86_init_ops vmx_init_ops __initdata = {
6aa8b732
AK
7899 .cpu_has_kvm_support = cpu_has_kvm_support,
7900 .disabled_by_bios = vmx_disabled_by_bios,
002c7f7c 7901 .check_processor_compatibility = vmx_check_processor_compat,
d008dfdb 7902 .hardware_setup = hardware_setup,
57b119da 7903
d008dfdb 7904 .runtime_ops = &vmx_x86_ops,
6aa8b732
AK
7905};
7906
72c6d2db 7907static void vmx_cleanup_l1d_flush(void)
a47dd5f0
PB
7908{
7909 if (vmx_l1d_flush_pages) {
7910 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
7911 vmx_l1d_flush_pages = NULL;
7912 }
72c6d2db
TG
7913 /* Restore state so sysfs ignores VMX */
7914 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
a399477e
KRW
7915}
7916
a7b9020b
TG
7917static void vmx_exit(void)
7918{
7919#ifdef CONFIG_KEXEC_CORE
7920 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
7921 synchronize_rcu();
7922#endif
7923
7924 kvm_exit();
7925
7926#if IS_ENABLED(CONFIG_HYPERV)
7927 if (static_branch_unlikely(&enable_evmcs)) {
7928 int cpu;
7929 struct hv_vp_assist_page *vp_ap;
7930 /*
7931 * Reset everything to support using non-enlightened VMCS
7932 * access later (e.g. when we reload the module with
7933 * enlightened_vmcs=0)
7934 */
7935 for_each_online_cpu(cpu) {
7936 vp_ap = hv_get_vp_assist_page(cpu);
7937
7938 if (!vp_ap)
7939 continue;
7940
6f6a657c 7941 vp_ap->nested_control.features.directhypercall = 0;
a7b9020b
TG
7942 vp_ap->current_nested_vmcs = 0;
7943 vp_ap->enlighten_vmentry = 0;
7944 }
7945
7946 static_branch_disable(&enable_evmcs);
7947 }
7948#endif
7949 vmx_cleanup_l1d_flush();
7950}
7951module_exit(vmx_exit);
7952
6aa8b732
AK
7953static int __init vmx_init(void)
7954{
dbef2808 7955 int r, cpu;
773e8a04
VK
7956
7957#if IS_ENABLED(CONFIG_HYPERV)
7958 /*
7959 * Enlightened VMCS usage should be recommended and the host needs
7960 * to support eVMCS v1 or above. We can also disable eVMCS support
7961 * with module parameter.
7962 */
7963 if (enlightened_vmcs &&
7964 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
7965 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
7966 KVM_EVMCS_VERSION) {
7967 int cpu;
7968
7969 /* Check that we have assist pages on all online CPUs */
7970 for_each_online_cpu(cpu) {
7971 if (!hv_get_vp_assist_page(cpu)) {
7972 enlightened_vmcs = false;
7973 break;
7974 }
7975 }
7976
7977 if (enlightened_vmcs) {
7978 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
7979 static_branch_enable(&enable_evmcs);
7980 }
6f6a657c
VK
7981
7982 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
7983 vmx_x86_ops.enable_direct_tlbflush
7984 = hv_enable_direct_tlbflush;
7985
773e8a04
VK
7986 } else {
7987 enlightened_vmcs = false;
7988 }
7989#endif
7990
d008dfdb 7991 r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
a7b9020b 7992 __alignof__(struct vcpu_vmx), THIS_MODULE);
fdef3ad1 7993 if (r)
34a1cd60 7994 return r;
25c5f225 7995
a7b9020b 7996 /*
7db92e16
TG
7997 * Must be called after kvm_init() so enable_ept is properly set
7998 * up. Hand the parameter mitigation value in which was stored in
7999 * the pre module init parser. If no parameter was given, it will
8000 * contain 'auto' which will be turned into the default 'cond'
8001 * mitigation mode.
8002 */
19a36d32
WL
8003 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8004 if (r) {
8005 vmx_exit();
8006 return r;
a47dd5f0 8007 }
25c5f225 8008
dbef2808
VK
8009 for_each_possible_cpu(cpu) {
8010 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8888cdd0 8011
a3ff25fc 8012 pi_init_cpu(cpu);
dbef2808
VK
8013 }
8014
2965faa5 8015#ifdef CONFIG_KEXEC_CORE
8f536b76
ZY
8016 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8017 crash_vmclear_local_loaded_vmcss);
8018#endif
21ebf53b 8019 vmx_check_vmcs12_offsets();
8f536b76 8020
3edd6839 8021 /*
b96e6506
MG
8022 * Shadow paging doesn't have a (further) performance penalty
8023 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8024 * by default
3edd6839 8025 */
b96e6506
MG
8026 if (!enable_ept)
8027 allow_smaller_maxphyaddr = true;
3edd6839 8028
fdef3ad1 8029 return 0;
6aa8b732 8030}
a7b9020b 8031module_init(vmx_init);