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