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