1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
7 *
8 * Copyright (C) 2006 Qumranet, Inc.
9 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10 *
11 * Authors:
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
14 */
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16
17 #include <linux/highmem.h>
18 #include <linux/hrtimer.h>
19 #include <linux/kernel.h>
20 #include <linux/kvm_host.h>
21 #include <linux/module.h>
22 #include <linux/moduleparam.h>
23 #include <linux/mod_devicetable.h>
24 #include <linux/mm.h>
25 #include <linux/objtool.h>
26 #include <linux/sched.h>
27 #include <linux/sched/smt.h>
28 #include <linux/slab.h>
29 #include <linux/tboot.h>
30 #include <linux/trace_events.h>
31 #include <linux/entry-kvm.h>
32
33 #include <asm/apic.h>
34 #include <asm/asm.h>
35 #include <asm/cpu.h>
36 #include <asm/cpu_device_id.h>
37 #include <asm/debugreg.h>
38 #include <asm/desc.h>
39 #include <asm/fpu/api.h>
40 #include <asm/fpu/xstate.h>
41 #include <asm/idtentry.h>
42 #include <asm/io.h>
43 #include <asm/irq_remapping.h>
44 #include <asm/reboot.h>
45 #include <asm/perf_event.h>
46 #include <asm/mmu_context.h>
47 #include <asm/mshyperv.h>
48 #include <asm/mwait.h>
49 #include <asm/spec-ctrl.h>
50 #include <asm/vmx.h>
51
52 #include "capabilities.h"
53 #include "cpuid.h"
54 #include "hyperv.h"
55 #include "kvm_onhyperv.h"
56 #include "irq.h"
57 #include "kvm_cache_regs.h"
58 #include "lapic.h"
59 #include "mmu.h"
60 #include "nested.h"
61 #include "pmu.h"
62 #include "sgx.h"
63 #include "trace.h"
64 #include "vmcs.h"
65 #include "vmcs12.h"
66 #include "vmx.h"
67 #include "x86.h"
68 #include "smm.h"
69 #include "vmx_onhyperv.h"
70 #include "posted_intr.h"
71
72 MODULE_AUTHOR("Qumranet");
73 MODULE_LICENSE("GPL");
74
75 #ifdef MODULE
76 static const struct x86_cpu_id vmx_cpu_id[] = {
77 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
78 {}
79 };
80 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
81 #endif
82
83 bool __read_mostly enable_vpid = 1;
84 module_param_named(vpid, enable_vpid, bool, 0444);
85
86 static bool __read_mostly enable_vnmi = 1;
87 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
88
89 bool __read_mostly flexpriority_enabled = 1;
90 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
91
92 bool __read_mostly enable_ept = 1;
93 module_param_named(ept, enable_ept, bool, S_IRUGO);
94
95 bool __read_mostly enable_unrestricted_guest = 1;
96 module_param_named(unrestricted_guest,
97 enable_unrestricted_guest, bool, S_IRUGO);
98
99 bool __read_mostly enable_ept_ad_bits = 1;
100 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
101
102 static bool __read_mostly emulate_invalid_guest_state = true;
103 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
104
105 static bool __read_mostly fasteoi = 1;
106 module_param(fasteoi, bool, S_IRUGO);
107
108 module_param(enable_apicv, bool, S_IRUGO);
109
110 bool __read_mostly enable_ipiv = true;
111 module_param(enable_ipiv, bool, 0444);
112
113 /*
114 * If nested=1, nested virtualization is supported, i.e., guests may use
115 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
116 * use VMX instructions.
117 */
118 static bool __read_mostly nested = 1;
119 module_param(nested, bool, S_IRUGO);
120
121 bool __read_mostly enable_pml = 1;
122 module_param_named(pml, enable_pml, bool, S_IRUGO);
123
124 static bool __read_mostly error_on_inconsistent_vmcs_config = true;
125 module_param(error_on_inconsistent_vmcs_config, bool, 0444);
126
127 static bool __read_mostly dump_invalid_vmcs = 0;
128 module_param(dump_invalid_vmcs, bool, 0644);
129
130 #define MSR_BITMAP_MODE_X2APIC 1
131 #define MSR_BITMAP_MODE_X2APIC_APICV 2
132
133 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
134
135 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
136 static int __read_mostly cpu_preemption_timer_multi;
137 static bool __read_mostly enable_preemption_timer = 1;
138 #ifdef CONFIG_X86_64
139 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
140 #endif
141
142 extern bool __read_mostly allow_smaller_maxphyaddr;
143 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
144
145 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
146 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
147 #define KVM_VM_CR0_ALWAYS_ON \
148 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
149
150 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
151 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
152 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
153
154 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
155
156 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
157 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
158 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
159 RTIT_STATUS_BYTECNT))
160
161 /*
162 * List of MSRs that can be directly passed to the guest.
163 * In addition to these x2apic and PT MSRs are handled specially.
164 */
165 static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
166 MSR_IA32_SPEC_CTRL,
167 MSR_IA32_PRED_CMD,
168 MSR_IA32_FLUSH_CMD,
169 MSR_IA32_TSC,
170 #ifdef CONFIG_X86_64
171 MSR_FS_BASE,
172 MSR_GS_BASE,
173 MSR_KERNEL_GS_BASE,
174 MSR_IA32_XFD,
175 MSR_IA32_XFD_ERR,
176 #endif
177 MSR_IA32_SYSENTER_CS,
178 MSR_IA32_SYSENTER_ESP,
179 MSR_IA32_SYSENTER_EIP,
180 MSR_CORE_C1_RES,
181 MSR_CORE_C3_RESIDENCY,
182 MSR_CORE_C6_RESIDENCY,
183 MSR_CORE_C7_RESIDENCY,
184 };
185
186 /*
187 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
188 * ple_gap: upper bound on the amount of time between two successive
189 * executions of PAUSE in a loop. Also indicate if ple enabled.
190 * According to test, this time is usually smaller than 128 cycles.
191 * ple_window: upper bound on the amount of time a guest is allowed to execute
192 * in a PAUSE loop. Tests indicate that most spinlocks are held for
193 * less than 2^12 cycles
194 * Time is measured based on a counter that runs at the same rate as the TSC,
195 * refer SDM volume 3b section 21.6.13 & 22.1.3.
196 */
197 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
198 module_param(ple_gap, uint, 0444);
199
200 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
201 module_param(ple_window, uint, 0444);
202
203 /* Default doubles per-vcpu window every exit. */
204 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
205 module_param(ple_window_grow, uint, 0444);
206
207 /* Default resets per-vcpu window every exit to ple_window. */
208 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
209 module_param(ple_window_shrink, uint, 0444);
210
211 /* Default is to compute the maximum so we can never overflow. */
212 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
213 module_param(ple_window_max, uint, 0444);
214
215 /* Default is SYSTEM mode, 1 for host-guest mode (which is BROKEN) */
216 int __read_mostly pt_mode = PT_MODE_SYSTEM;
217 #ifdef CONFIG_BROKEN
218 module_param(pt_mode, int, S_IRUGO);
219 #endif
220
221 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
222 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
223 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
224
225 /* Storage for pre module init parameter parsing */
226 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
227
228 static const struct {
229 const char *option;
230 bool for_parse;
231 } vmentry_l1d_param[] = {
232 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
233 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
234 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
235 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
236 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
237 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
238 };
239
240 #define L1D_CACHE_ORDER 4
241 static void *vmx_l1d_flush_pages;
242
vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)243 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
244 {
245 struct page *page;
246 unsigned int i;
247
248 if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
249 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
250 return 0;
251 }
252
253 if (!enable_ept) {
254 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
255 return 0;
256 }
257
258 if (host_arch_capabilities & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
259 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
260 return 0;
261 }
262
263 /* If set to auto use the default l1tf mitigation method */
264 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
265 switch (l1tf_mitigation) {
266 case L1TF_MITIGATION_OFF:
267 l1tf = VMENTER_L1D_FLUSH_NEVER;
268 break;
269 case L1TF_MITIGATION_FLUSH_NOWARN:
270 case L1TF_MITIGATION_FLUSH:
271 case L1TF_MITIGATION_FLUSH_NOSMT:
272 l1tf = VMENTER_L1D_FLUSH_COND;
273 break;
274 case L1TF_MITIGATION_FULL:
275 case L1TF_MITIGATION_FULL_FORCE:
276 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
277 break;
278 }
279 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
280 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
281 }
282
283 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
284 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
285 /*
286 * This allocation for vmx_l1d_flush_pages is not tied to a VM
287 * lifetime and so should not be charged to a memcg.
288 */
289 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
290 if (!page)
291 return -ENOMEM;
292 vmx_l1d_flush_pages = page_address(page);
293
294 /*
295 * Initialize each page with a different pattern in
296 * order to protect against KSM in the nested
297 * virtualization case.
298 */
299 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
300 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
301 PAGE_SIZE);
302 }
303 }
304
305 l1tf_vmx_mitigation = l1tf;
306
307 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
308 static_branch_enable(&vmx_l1d_should_flush);
309 else
310 static_branch_disable(&vmx_l1d_should_flush);
311
312 if (l1tf == VMENTER_L1D_FLUSH_COND)
313 static_branch_enable(&vmx_l1d_flush_cond);
314 else
315 static_branch_disable(&vmx_l1d_flush_cond);
316 return 0;
317 }
318
vmentry_l1d_flush_parse(const char * s)319 static int vmentry_l1d_flush_parse(const char *s)
320 {
321 unsigned int i;
322
323 if (s) {
324 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
325 if (vmentry_l1d_param[i].for_parse &&
326 sysfs_streq(s, vmentry_l1d_param[i].option))
327 return i;
328 }
329 }
330 return -EINVAL;
331 }
332
vmentry_l1d_flush_set(const char * s,const struct kernel_param * kp)333 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
334 {
335 int l1tf, ret;
336
337 l1tf = vmentry_l1d_flush_parse(s);
338 if (l1tf < 0)
339 return l1tf;
340
341 if (!boot_cpu_has(X86_BUG_L1TF))
342 return 0;
343
344 /*
345 * Has vmx_init() run already? If not then this is the pre init
346 * parameter parsing. In that case just store the value and let
347 * vmx_init() do the proper setup after enable_ept has been
348 * established.
349 */
350 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
351 vmentry_l1d_flush_param = l1tf;
352 return 0;
353 }
354
355 mutex_lock(&vmx_l1d_flush_mutex);
356 ret = vmx_setup_l1d_flush(l1tf);
357 mutex_unlock(&vmx_l1d_flush_mutex);
358 return ret;
359 }
360
vmentry_l1d_flush_get(char * s,const struct kernel_param * kp)361 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
362 {
363 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
364 return sysfs_emit(s, "???\n");
365
366 return sysfs_emit(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
367 }
368
vmx_disable_fb_clear(struct vcpu_vmx * vmx)369 static __always_inline void vmx_disable_fb_clear(struct vcpu_vmx *vmx)
370 {
371 u64 msr;
372
373 if (!vmx->disable_fb_clear)
374 return;
375
376 msr = __rdmsr(MSR_IA32_MCU_OPT_CTRL);
377 msr |= FB_CLEAR_DIS;
378 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, msr);
379 /* Cache the MSR value to avoid reading it later */
380 vmx->msr_ia32_mcu_opt_ctrl = msr;
381 }
382
vmx_enable_fb_clear(struct vcpu_vmx * vmx)383 static __always_inline void vmx_enable_fb_clear(struct vcpu_vmx *vmx)
384 {
385 if (!vmx->disable_fb_clear)
386 return;
387
388 vmx->msr_ia32_mcu_opt_ctrl &= ~FB_CLEAR_DIS;
389 native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, vmx->msr_ia32_mcu_opt_ctrl);
390 }
391
vmx_update_fb_clear_dis(struct kvm_vcpu * vcpu,struct vcpu_vmx * vmx)392 static void vmx_update_fb_clear_dis(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx)
393 {
394 /*
395 * Disable VERW's behavior of clearing CPU buffers for the guest if the
396 * CPU isn't affected by MDS/TAA, and the host hasn't forcefully enabled
397 * the mitigation. Disabling the clearing behavior provides a
398 * performance boost for guests that aren't aware that manually clearing
399 * CPU buffers is unnecessary, at the cost of MSR accesses on VM-Entry
400 * and VM-Exit.
401 */
402 vmx->disable_fb_clear = !cpu_feature_enabled(X86_FEATURE_CLEAR_CPU_BUF) &&
403 (host_arch_capabilities & ARCH_CAP_FB_CLEAR_CTRL) &&
404 !boot_cpu_has_bug(X86_BUG_MDS) &&
405 !boot_cpu_has_bug(X86_BUG_TAA);
406
407 /*
408 * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS
409 * at VMEntry. Skip the MSR read/write when a guest has no use case to
410 * execute VERW.
411 */
412 if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) ||
413 ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) &&
414 (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) &&
415 (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) &&
416 (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) &&
417 (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO)))
418 vmx->disable_fb_clear = false;
419 }
420
421 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
422 .set = vmentry_l1d_flush_set,
423 .get = vmentry_l1d_flush_get,
424 };
425 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
426
427 static u32 vmx_segment_access_rights(struct kvm_segment *var);
428
429 void vmx_vmexit(void);
430
431 #define vmx_insn_failed(fmt...) \
432 do { \
433 WARN_ONCE(1, fmt); \
434 pr_warn_ratelimited(fmt); \
435 } while (0)
436
vmread_error(unsigned long field)437 noinline void vmread_error(unsigned long field)
438 {
439 vmx_insn_failed("vmread failed: field=%lx\n", field);
440 }
441
442 #ifndef CONFIG_CC_HAS_ASM_GOTO_OUTPUT
vmread_error_trampoline2(unsigned long field,bool fault)443 noinstr void vmread_error_trampoline2(unsigned long field, bool fault)
444 {
445 if (fault) {
446 kvm_spurious_fault();
447 } else {
448 instrumentation_begin();
449 vmread_error(field);
450 instrumentation_end();
451 }
452 }
453 #endif
454
vmwrite_error(unsigned long field,unsigned long value)455 noinline void vmwrite_error(unsigned long field, unsigned long value)
456 {
457 vmx_insn_failed("vmwrite failed: field=%lx val=%lx err=%u\n",
458 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
459 }
460
vmclear_error(struct vmcs * vmcs,u64 phys_addr)461 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
462 {
463 vmx_insn_failed("vmclear failed: %p/%llx err=%u\n",
464 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
465 }
466
vmptrld_error(struct vmcs * vmcs,u64 phys_addr)467 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
468 {
469 vmx_insn_failed("vmptrld failed: %p/%llx err=%u\n",
470 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
471 }
472
invvpid_error(unsigned long ext,u16 vpid,gva_t gva)473 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
474 {
475 vmx_insn_failed("invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
476 ext, vpid, gva);
477 }
478
invept_error(unsigned long ext,u64 eptp,gpa_t gpa)479 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
480 {
481 vmx_insn_failed("invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
482 ext, eptp, gpa);
483 }
484
485 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
486 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
487 /*
488 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
489 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
490 */
491 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
492
493 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
494 static DEFINE_SPINLOCK(vmx_vpid_lock);
495
496 struct vmcs_config vmcs_config __ro_after_init;
497 struct vmx_capability vmx_capability __ro_after_init;
498
499 #define VMX_SEGMENT_FIELD(seg) \
500 [VCPU_SREG_##seg] = { \
501 .selector = GUEST_##seg##_SELECTOR, \
502 .base = GUEST_##seg##_BASE, \
503 .limit = GUEST_##seg##_LIMIT, \
504 .ar_bytes = GUEST_##seg##_AR_BYTES, \
505 }
506
507 static const struct kvm_vmx_segment_field {
508 unsigned selector;
509 unsigned base;
510 unsigned limit;
511 unsigned ar_bytes;
512 } kvm_vmx_segment_fields[] = {
513 VMX_SEGMENT_FIELD(CS),
514 VMX_SEGMENT_FIELD(DS),
515 VMX_SEGMENT_FIELD(ES),
516 VMX_SEGMENT_FIELD(FS),
517 VMX_SEGMENT_FIELD(GS),
518 VMX_SEGMENT_FIELD(SS),
519 VMX_SEGMENT_FIELD(TR),
520 VMX_SEGMENT_FIELD(LDTR),
521 };
522
vmx_segment_cache_clear(struct vcpu_vmx * vmx)523 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
524 {
525 vmx->segment_cache.bitmask = 0;
526 }
527
528 static unsigned long host_idt_base;
529
530 #if IS_ENABLED(CONFIG_HYPERV)
531 static struct kvm_x86_ops vmx_x86_ops __initdata;
532
533 static bool __read_mostly enlightened_vmcs = true;
534 module_param(enlightened_vmcs, bool, 0444);
535
hv_enable_l2_tlb_flush(struct kvm_vcpu * vcpu)536 static int hv_enable_l2_tlb_flush(struct kvm_vcpu *vcpu)
537 {
538 struct hv_enlightened_vmcs *evmcs;
539 struct hv_partition_assist_pg **p_hv_pa_pg =
540 &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
541 /*
542 * Synthetic VM-Exit is not enabled in current code and so All
543 * evmcs in singe VM shares same assist page.
544 */
545 if (!*p_hv_pa_pg)
546 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
547
548 if (!*p_hv_pa_pg)
549 return -ENOMEM;
550
551 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
552
553 evmcs->partition_assist_page =
554 __pa(*p_hv_pa_pg);
555 evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
556 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
557
558 return 0;
559 }
560
hv_init_evmcs(void)561 static __init void hv_init_evmcs(void)
562 {
563 int cpu;
564
565 if (!enlightened_vmcs)
566 return;
567
568 /*
569 * Enlightened VMCS usage should be recommended and the host needs
570 * to support eVMCS v1 or above.
571 */
572 if (ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
573 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
574 KVM_EVMCS_VERSION) {
575
576 /* Check that we have assist pages on all online CPUs */
577 for_each_online_cpu(cpu) {
578 if (!hv_get_vp_assist_page(cpu)) {
579 enlightened_vmcs = false;
580 break;
581 }
582 }
583
584 if (enlightened_vmcs) {
585 pr_info("Using Hyper-V Enlightened VMCS\n");
586 static_branch_enable(&__kvm_is_using_evmcs);
587 }
588
589 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
590 vmx_x86_ops.enable_l2_tlb_flush
591 = hv_enable_l2_tlb_flush;
592
593 } else {
594 enlightened_vmcs = false;
595 }
596 }
597
hv_reset_evmcs(void)598 static void hv_reset_evmcs(void)
599 {
600 struct hv_vp_assist_page *vp_ap;
601
602 if (!kvm_is_using_evmcs())
603 return;
604
605 /*
606 * KVM should enable eVMCS if and only if all CPUs have a VP assist
607 * page, and should reject CPU onlining if eVMCS is enabled the CPU
608 * doesn't have a VP assist page allocated.
609 */
610 vp_ap = hv_get_vp_assist_page(smp_processor_id());
611 if (WARN_ON_ONCE(!vp_ap))
612 return;
613
614 /*
615 * Reset everything to support using non-enlightened VMCS access later
616 * (e.g. when we reload the module with enlightened_vmcs=0)
617 */
618 vp_ap->nested_control.features.directhypercall = 0;
619 vp_ap->current_nested_vmcs = 0;
620 vp_ap->enlighten_vmentry = 0;
621 }
622
623 #else /* IS_ENABLED(CONFIG_HYPERV) */
hv_init_evmcs(void)624 static void hv_init_evmcs(void) {}
hv_reset_evmcs(void)625 static void hv_reset_evmcs(void) {}
626 #endif /* IS_ENABLED(CONFIG_HYPERV) */
627
628 /*
629 * Comment's format: document - errata name - stepping - processor name.
630 * Refer from
631 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
632 */
633 static u32 vmx_preemption_cpu_tfms[] = {
634 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
635 0x000206E6,
636 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
637 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
638 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
639 0x00020652,
640 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
641 0x00020655,
642 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
643 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
644 /*
645 * 320767.pdf - AAP86 - B1 -
646 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
647 */
648 0x000106E5,
649 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
650 0x000106A0,
651 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
652 0x000106A1,
653 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
654 0x000106A4,
655 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
656 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
657 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
658 0x000106A5,
659 /* Xeon E3-1220 V2 */
660 0x000306A8,
661 };
662
cpu_has_broken_vmx_preemption_timer(void)663 static inline bool cpu_has_broken_vmx_preemption_timer(void)
664 {
665 u32 eax = cpuid_eax(0x00000001), i;
666
667 /* Clear the reserved bits */
668 eax &= ~(0x3U << 14 | 0xfU << 28);
669 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
670 if (eax == vmx_preemption_cpu_tfms[i])
671 return true;
672
673 return false;
674 }
675
cpu_need_virtualize_apic_accesses(struct kvm_vcpu * vcpu)676 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
677 {
678 return flexpriority_enabled && lapic_in_kernel(vcpu);
679 }
680
possible_passthrough_msr_slot(u32 msr)681 static int possible_passthrough_msr_slot(u32 msr)
682 {
683 u32 i;
684
685 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
686 if (vmx_possible_passthrough_msrs[i] == msr)
687 return i;
688
689 return -ENOENT;
690 }
691
is_valid_passthrough_msr(u32 msr)692 static bool is_valid_passthrough_msr(u32 msr)
693 {
694 bool r;
695
696 switch (msr) {
697 case 0x800 ... 0x8ff:
698 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
699 return true;
700 case MSR_IA32_RTIT_STATUS:
701 case MSR_IA32_RTIT_OUTPUT_BASE:
702 case MSR_IA32_RTIT_OUTPUT_MASK:
703 case MSR_IA32_RTIT_CR3_MATCH:
704 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
705 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
706 case MSR_LBR_SELECT:
707 case MSR_LBR_TOS:
708 case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
709 case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
710 case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
711 case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
712 case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
713 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
714 return true;
715 }
716
717 r = possible_passthrough_msr_slot(msr) != -ENOENT;
718
719 WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
720
721 return r;
722 }
723
vmx_find_uret_msr(struct vcpu_vmx * vmx,u32 msr)724 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
725 {
726 int i;
727
728 i = kvm_find_user_return_msr(msr);
729 if (i >= 0)
730 return &vmx->guest_uret_msrs[i];
731 return NULL;
732 }
733
vmx_set_guest_uret_msr(struct vcpu_vmx * vmx,struct vmx_uret_msr * msr,u64 data)734 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
735 struct vmx_uret_msr *msr, u64 data)
736 {
737 unsigned int slot = msr - vmx->guest_uret_msrs;
738 int ret = 0;
739
740 if (msr->load_into_hardware) {
741 preempt_disable();
742 ret = kvm_set_user_return_msr(slot, data, msr->mask);
743 preempt_enable();
744 }
745 if (!ret)
746 msr->data = data;
747 return ret;
748 }
749
750 /*
751 * Disable VMX and clear CR4.VMXE (even if VMXOFF faults)
752 *
753 * Note, VMXOFF causes a #UD if the CPU is !post-VMXON, but it's impossible to
754 * atomically track post-VMXON state, e.g. this may be called in NMI context.
755 * Eat all faults as all other faults on VMXOFF faults are mode related, i.e.
756 * faults are guaranteed to be due to the !post-VMXON check unless the CPU is
757 * magically in RM, VM86, compat mode, or at CPL>0.
758 */
kvm_cpu_vmxoff(void)759 static int kvm_cpu_vmxoff(void)
760 {
761 asm goto("1: vmxoff\n\t"
762 _ASM_EXTABLE(1b, %l[fault])
763 ::: "cc", "memory" : fault);
764
765 cr4_clear_bits(X86_CR4_VMXE);
766 return 0;
767
768 fault:
769 cr4_clear_bits(X86_CR4_VMXE);
770 return -EIO;
771 }
772
vmx_emergency_disable(void)773 static void vmx_emergency_disable(void)
774 {
775 int cpu = raw_smp_processor_id();
776 struct loaded_vmcs *v;
777
778 kvm_rebooting = true;
779
780 /*
781 * Note, CR4.VMXE can be _cleared_ in NMI context, but it can only be
782 * set in task context. If this races with VMX is disabled by an NMI,
783 * VMCLEAR and VMXOFF may #UD, but KVM will eat those faults due to
784 * kvm_rebooting set.
785 */
786 if (!(__read_cr4() & X86_CR4_VMXE))
787 return;
788
789 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
790 loaded_vmcss_on_cpu_link)
791 vmcs_clear(v->vmcs);
792
793 kvm_cpu_vmxoff();
794 }
795
__loaded_vmcs_clear(void * arg)796 static void __loaded_vmcs_clear(void *arg)
797 {
798 struct loaded_vmcs *loaded_vmcs = arg;
799 int cpu = raw_smp_processor_id();
800
801 if (loaded_vmcs->cpu != cpu)
802 return; /* vcpu migration can race with cpu offline */
803 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
804 per_cpu(current_vmcs, cpu) = NULL;
805
806 vmcs_clear(loaded_vmcs->vmcs);
807 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
808 vmcs_clear(loaded_vmcs->shadow_vmcs);
809
810 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
811
812 /*
813 * Ensure all writes to loaded_vmcs, including deleting it from its
814 * current percpu list, complete before setting loaded_vmcs->cpu to
815 * -1, otherwise a different cpu can see loaded_vmcs->cpu == -1 first
816 * and add loaded_vmcs to its percpu list before it's deleted from this
817 * cpu's list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
818 */
819 smp_wmb();
820
821 loaded_vmcs->cpu = -1;
822 loaded_vmcs->launched = 0;
823 }
824
loaded_vmcs_clear(struct loaded_vmcs * loaded_vmcs)825 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
826 {
827 int cpu = loaded_vmcs->cpu;
828
829 if (cpu != -1)
830 smp_call_function_single(cpu,
831 __loaded_vmcs_clear, loaded_vmcs, 1);
832 }
833
vmx_segment_cache_test_set(struct vcpu_vmx * vmx,unsigned seg,unsigned field)834 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
835 unsigned field)
836 {
837 bool ret;
838 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
839
840 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
841 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
842 vmx->segment_cache.bitmask = 0;
843 }
844 ret = vmx->segment_cache.bitmask & mask;
845 vmx->segment_cache.bitmask |= mask;
846 return ret;
847 }
848
vmx_read_guest_seg_selector(struct vcpu_vmx * vmx,unsigned seg)849 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
850 {
851 u16 *p = &vmx->segment_cache.seg[seg].selector;
852
853 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
854 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
855 return *p;
856 }
857
vmx_read_guest_seg_base(struct vcpu_vmx * vmx,unsigned seg)858 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
859 {
860 ulong *p = &vmx->segment_cache.seg[seg].base;
861
862 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
863 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
864 return *p;
865 }
866
vmx_read_guest_seg_limit(struct vcpu_vmx * vmx,unsigned seg)867 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
868 {
869 u32 *p = &vmx->segment_cache.seg[seg].limit;
870
871 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
872 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
873 return *p;
874 }
875
vmx_read_guest_seg_ar(struct vcpu_vmx * vmx,unsigned seg)876 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
877 {
878 u32 *p = &vmx->segment_cache.seg[seg].ar;
879
880 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
881 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
882 return *p;
883 }
884
vmx_update_exception_bitmap(struct kvm_vcpu * vcpu)885 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
886 {
887 u32 eb;
888
889 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
890 (1u << DB_VECTOR) | (1u << AC_VECTOR);
891 /*
892 * Guest access to VMware backdoor ports could legitimately
893 * trigger #GP because of TSS I/O permission bitmap.
894 * We intercept those #GP and allow access to them anyway
895 * as VMware does.
896 */
897 if (enable_vmware_backdoor)
898 eb |= (1u << GP_VECTOR);
899 if ((vcpu->guest_debug &
900 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
901 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
902 eb |= 1u << BP_VECTOR;
903 if (to_vmx(vcpu)->rmode.vm86_active)
904 eb = ~0;
905 if (!vmx_need_pf_intercept(vcpu))
906 eb &= ~(1u << PF_VECTOR);
907
908 /* When we are running a nested L2 guest and L1 specified for it a
909 * certain exception bitmap, we must trap the same exceptions and pass
910 * them to L1. When running L2, we will only handle the exceptions
911 * specified above if L1 did not want them.
912 */
913 if (is_guest_mode(vcpu))
914 eb |= get_vmcs12(vcpu)->exception_bitmap;
915 else {
916 int mask = 0, match = 0;
917
918 if (enable_ept && (eb & (1u << PF_VECTOR))) {
919 /*
920 * If EPT is enabled, #PF is currently only intercepted
921 * if MAXPHYADDR is smaller on the guest than on the
922 * host. In that case we only care about present,
923 * non-reserved faults. For vmcs02, however, PFEC_MASK
924 * and PFEC_MATCH are set in prepare_vmcs02_rare.
925 */
926 mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK;
927 match = PFERR_PRESENT_MASK;
928 }
929 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
930 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match);
931 }
932
933 /*
934 * Disabling xfd interception indicates that dynamic xfeatures
935 * might be used in the guest. Always trap #NM in this case
936 * to save guest xfd_err timely.
937 */
938 if (vcpu->arch.xfd_no_write_intercept)
939 eb |= (1u << NM_VECTOR);
940
941 vmcs_write32(EXCEPTION_BITMAP, eb);
942 }
943
944 /*
945 * Check if MSR is intercepted for currently loaded MSR bitmap.
946 */
msr_write_intercepted(struct vcpu_vmx * vmx,u32 msr)947 static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr)
948 {
949 if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS))
950 return true;
951
952 return vmx_test_msr_bitmap_write(vmx->loaded_vmcs->msr_bitmap, msr);
953 }
954
__vmx_vcpu_run_flags(struct vcpu_vmx * vmx)955 unsigned int __vmx_vcpu_run_flags(struct vcpu_vmx *vmx)
956 {
957 unsigned int flags = 0;
958
959 if (vmx->loaded_vmcs->launched)
960 flags |= VMX_RUN_VMRESUME;
961
962 /*
963 * If writes to the SPEC_CTRL MSR aren't intercepted, the guest is free
964 * to change it directly without causing a vmexit. In that case read
965 * it after vmexit and store it in vmx->spec_ctrl.
966 */
967 if (!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL))
968 flags |= VMX_RUN_SAVE_SPEC_CTRL;
969
970 return flags;
971 }
972
clear_atomic_switch_msr_special(struct vcpu_vmx * vmx,unsigned long entry,unsigned long exit)973 static __always_inline void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
974 unsigned long entry, unsigned long exit)
975 {
976 vm_entry_controls_clearbit(vmx, entry);
977 vm_exit_controls_clearbit(vmx, exit);
978 }
979
vmx_find_loadstore_msr_slot(struct vmx_msrs * m,u32 msr)980 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
981 {
982 unsigned int i;
983
984 for (i = 0; i < m->nr; ++i) {
985 if (m->val[i].index == msr)
986 return i;
987 }
988 return -ENOENT;
989 }
990
clear_atomic_switch_msr(struct vcpu_vmx * vmx,unsigned msr)991 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
992 {
993 int i;
994 struct msr_autoload *m = &vmx->msr_autoload;
995
996 switch (msr) {
997 case MSR_EFER:
998 if (cpu_has_load_ia32_efer()) {
999 clear_atomic_switch_msr_special(vmx,
1000 VM_ENTRY_LOAD_IA32_EFER,
1001 VM_EXIT_LOAD_IA32_EFER);
1002 return;
1003 }
1004 break;
1005 case MSR_CORE_PERF_GLOBAL_CTRL:
1006 if (cpu_has_load_perf_global_ctrl()) {
1007 clear_atomic_switch_msr_special(vmx,
1008 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1009 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
1010 return;
1011 }
1012 break;
1013 }
1014 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
1015 if (i < 0)
1016 goto skip_guest;
1017 --m->guest.nr;
1018 m->guest.val[i] = m->guest.val[m->guest.nr];
1019 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1020
1021 skip_guest:
1022 i = vmx_find_loadstore_msr_slot(&m->host, msr);
1023 if (i < 0)
1024 return;
1025
1026 --m->host.nr;
1027 m->host.val[i] = m->host.val[m->host.nr];
1028 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1029 }
1030
add_atomic_switch_msr_special(struct vcpu_vmx * vmx,unsigned long entry,unsigned long exit,unsigned long guest_val_vmcs,unsigned long host_val_vmcs,u64 guest_val,u64 host_val)1031 static __always_inline void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
1032 unsigned long entry, unsigned long exit,
1033 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
1034 u64 guest_val, u64 host_val)
1035 {
1036 vmcs_write64(guest_val_vmcs, guest_val);
1037 if (host_val_vmcs != HOST_IA32_EFER)
1038 vmcs_write64(host_val_vmcs, host_val);
1039 vm_entry_controls_setbit(vmx, entry);
1040 vm_exit_controls_setbit(vmx, exit);
1041 }
1042
add_atomic_switch_msr(struct vcpu_vmx * vmx,unsigned msr,u64 guest_val,u64 host_val,bool entry_only)1043 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
1044 u64 guest_val, u64 host_val, bool entry_only)
1045 {
1046 int i, j = 0;
1047 struct msr_autoload *m = &vmx->msr_autoload;
1048
1049 switch (msr) {
1050 case MSR_EFER:
1051 if (cpu_has_load_ia32_efer()) {
1052 add_atomic_switch_msr_special(vmx,
1053 VM_ENTRY_LOAD_IA32_EFER,
1054 VM_EXIT_LOAD_IA32_EFER,
1055 GUEST_IA32_EFER,
1056 HOST_IA32_EFER,
1057 guest_val, host_val);
1058 return;
1059 }
1060 break;
1061 case MSR_CORE_PERF_GLOBAL_CTRL:
1062 if (cpu_has_load_perf_global_ctrl()) {
1063 add_atomic_switch_msr_special(vmx,
1064 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
1065 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
1066 GUEST_IA32_PERF_GLOBAL_CTRL,
1067 HOST_IA32_PERF_GLOBAL_CTRL,
1068 guest_val, host_val);
1069 return;
1070 }
1071 break;
1072 case MSR_IA32_PEBS_ENABLE:
1073 /* PEBS needs a quiescent period after being disabled (to write
1074 * a record). Disabling PEBS through VMX MSR swapping doesn't
1075 * provide that period, so a CPU could write host's record into
1076 * guest's memory.
1077 */
1078 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
1079 }
1080
1081 i = vmx_find_loadstore_msr_slot(&m->guest, msr);
1082 if (!entry_only)
1083 j = vmx_find_loadstore_msr_slot(&m->host, msr);
1084
1085 if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
1086 (j < 0 && m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
1087 printk_once(KERN_WARNING "Not enough msr switch entries. "
1088 "Can't add msr %x\n", msr);
1089 return;
1090 }
1091 if (i < 0) {
1092 i = m->guest.nr++;
1093 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
1094 }
1095 m->guest.val[i].index = msr;
1096 m->guest.val[i].value = guest_val;
1097
1098 if (entry_only)
1099 return;
1100
1101 if (j < 0) {
1102 j = m->host.nr++;
1103 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
1104 }
1105 m->host.val[j].index = msr;
1106 m->host.val[j].value = host_val;
1107 }
1108
update_transition_efer(struct vcpu_vmx * vmx)1109 static bool update_transition_efer(struct vcpu_vmx *vmx)
1110 {
1111 u64 guest_efer = vmx->vcpu.arch.efer;
1112 u64 ignore_bits = 0;
1113 int i;
1114
1115 /* Shadow paging assumes NX to be available. */
1116 if (!enable_ept)
1117 guest_efer |= EFER_NX;
1118
1119 /*
1120 * LMA and LME handled by hardware; SCE meaningless outside long mode.
1121 */
1122 ignore_bits |= EFER_SCE;
1123 #ifdef CONFIG_X86_64
1124 ignore_bits |= EFER_LMA | EFER_LME;
1125 /* SCE is meaningful only in long mode on Intel */
1126 if (guest_efer & EFER_LMA)
1127 ignore_bits &= ~(u64)EFER_SCE;
1128 #endif
1129
1130 /*
1131 * On EPT, we can't emulate NX, so we must switch EFER atomically.
1132 * On CPUs that support "load IA32_EFER", always switch EFER
1133 * atomically, since it's faster than switching it manually.
1134 */
1135 if (cpu_has_load_ia32_efer() ||
1136 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1137 if (!(guest_efer & EFER_LMA))
1138 guest_efer &= ~EFER_LME;
1139 if (guest_efer != host_efer)
1140 add_atomic_switch_msr(vmx, MSR_EFER,
1141 guest_efer, host_efer, false);
1142 else
1143 clear_atomic_switch_msr(vmx, MSR_EFER);
1144 return false;
1145 }
1146
1147 i = kvm_find_user_return_msr(MSR_EFER);
1148 if (i < 0)
1149 return false;
1150
1151 clear_atomic_switch_msr(vmx, MSR_EFER);
1152
1153 guest_efer &= ~ignore_bits;
1154 guest_efer |= host_efer & ignore_bits;
1155
1156 vmx->guest_uret_msrs[i].data = guest_efer;
1157 vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1158
1159 return true;
1160 }
1161
1162 #ifdef CONFIG_X86_32
1163 /*
1164 * On 32-bit kernels, VM exits still load the FS and GS bases from the
1165 * VMCS rather than the segment table. KVM uses this helper to figure
1166 * out the current bases to poke them into the VMCS before entry.
1167 */
segment_base(u16 selector)1168 static unsigned long segment_base(u16 selector)
1169 {
1170 struct desc_struct *table;
1171 unsigned long v;
1172
1173 if (!(selector & ~SEGMENT_RPL_MASK))
1174 return 0;
1175
1176 table = get_current_gdt_ro();
1177
1178 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1179 u16 ldt_selector = kvm_read_ldt();
1180
1181 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1182 return 0;
1183
1184 table = (struct desc_struct *)segment_base(ldt_selector);
1185 }
1186 v = get_desc_base(&table[selector >> 3]);
1187 return v;
1188 }
1189 #endif
1190
pt_can_write_msr(struct vcpu_vmx * vmx)1191 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1192 {
1193 return vmx_pt_mode_is_host_guest() &&
1194 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1195 }
1196
pt_output_base_valid(struct kvm_vcpu * vcpu,u64 base)1197 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1198 {
1199 /* The base must be 128-byte aligned and a legal physical address. */
1200 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1201 }
1202
pt_load_msr(struct pt_ctx * ctx,u32 addr_range)1203 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1204 {
1205 u32 i;
1206
1207 wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1208 wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1209 wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1210 wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1211 for (i = 0; i < addr_range; i++) {
1212 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1213 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1214 }
1215 }
1216
pt_save_msr(struct pt_ctx * ctx,u32 addr_range)1217 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1218 {
1219 u32 i;
1220
1221 rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1222 rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1223 rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1224 rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1225 for (i = 0; i < addr_range; i++) {
1226 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1227 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1228 }
1229 }
1230
pt_guest_enter(struct vcpu_vmx * vmx)1231 static void pt_guest_enter(struct vcpu_vmx *vmx)
1232 {
1233 if (vmx_pt_mode_is_system())
1234 return;
1235
1236 /*
1237 * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1238 * Save host state before VM entry.
1239 */
1240 rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1241 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1242 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1243 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1244 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1245 }
1246 }
1247
pt_guest_exit(struct vcpu_vmx * vmx)1248 static void pt_guest_exit(struct vcpu_vmx *vmx)
1249 {
1250 if (vmx_pt_mode_is_system())
1251 return;
1252
1253 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1254 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1255 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1256 }
1257
1258 /*
1259 * KVM requires VM_EXIT_CLEAR_IA32_RTIT_CTL to expose PT to the guest,
1260 * i.e. RTIT_CTL is always cleared on VM-Exit. Restore it if necessary.
1261 */
1262 if (vmx->pt_desc.host.ctl)
1263 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1264 }
1265
vmx_set_host_fs_gs(struct vmcs_host_state * host,u16 fs_sel,u16 gs_sel,unsigned long fs_base,unsigned long gs_base)1266 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1267 unsigned long fs_base, unsigned long gs_base)
1268 {
1269 if (unlikely(fs_sel != host->fs_sel)) {
1270 if (!(fs_sel & 7))
1271 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1272 else
1273 vmcs_write16(HOST_FS_SELECTOR, 0);
1274 host->fs_sel = fs_sel;
1275 }
1276 if (unlikely(gs_sel != host->gs_sel)) {
1277 if (!(gs_sel & 7))
1278 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1279 else
1280 vmcs_write16(HOST_GS_SELECTOR, 0);
1281 host->gs_sel = gs_sel;
1282 }
1283 if (unlikely(fs_base != host->fs_base)) {
1284 vmcs_writel(HOST_FS_BASE, fs_base);
1285 host->fs_base = fs_base;
1286 }
1287 if (unlikely(gs_base != host->gs_base)) {
1288 vmcs_writel(HOST_GS_BASE, gs_base);
1289 host->gs_base = gs_base;
1290 }
1291 }
1292
vmx_prepare_switch_to_guest(struct kvm_vcpu * vcpu)1293 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1294 {
1295 struct vcpu_vmx *vmx = to_vmx(vcpu);
1296 struct vmcs_host_state *host_state;
1297 #ifdef CONFIG_X86_64
1298 int cpu = raw_smp_processor_id();
1299 #endif
1300 unsigned long fs_base, gs_base;
1301 u16 fs_sel, gs_sel;
1302 int i;
1303
1304 vmx->req_immediate_exit = false;
1305
1306 /*
1307 * Note that guest MSRs to be saved/restored can also be changed
1308 * when guest state is loaded. This happens when guest transitions
1309 * to/from long-mode by setting MSR_EFER.LMA.
1310 */
1311 if (!vmx->guest_uret_msrs_loaded) {
1312 vmx->guest_uret_msrs_loaded = true;
1313 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
1314 if (!vmx->guest_uret_msrs[i].load_into_hardware)
1315 continue;
1316
1317 kvm_set_user_return_msr(i,
1318 vmx->guest_uret_msrs[i].data,
1319 vmx->guest_uret_msrs[i].mask);
1320 }
1321 }
1322
1323 if (vmx->nested.need_vmcs12_to_shadow_sync)
1324 nested_sync_vmcs12_to_shadow(vcpu);
1325
1326 if (vmx->guest_state_loaded)
1327 return;
1328
1329 host_state = &vmx->loaded_vmcs->host_state;
1330
1331 /*
1332 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
1333 * allow segment selectors with cpl > 0 or ti == 1.
1334 */
1335 host_state->ldt_sel = kvm_read_ldt();
1336
1337 #ifdef CONFIG_X86_64
1338 savesegment(ds, host_state->ds_sel);
1339 savesegment(es, host_state->es_sel);
1340
1341 gs_base = cpu_kernelmode_gs_base(cpu);
1342 if (likely(is_64bit_mm(current->mm))) {
1343 current_save_fsgs();
1344 fs_sel = current->thread.fsindex;
1345 gs_sel = current->thread.gsindex;
1346 fs_base = current->thread.fsbase;
1347 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1348 } else {
1349 savesegment(fs, fs_sel);
1350 savesegment(gs, gs_sel);
1351 fs_base = read_msr(MSR_FS_BASE);
1352 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1353 }
1354
1355 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1356 #else
1357 savesegment(fs, fs_sel);
1358 savesegment(gs, gs_sel);
1359 fs_base = segment_base(fs_sel);
1360 gs_base = segment_base(gs_sel);
1361 #endif
1362
1363 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1364 vmx->guest_state_loaded = true;
1365 }
1366
vmx_prepare_switch_to_host(struct vcpu_vmx * vmx)1367 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1368 {
1369 struct vmcs_host_state *host_state;
1370
1371 if (!vmx->guest_state_loaded)
1372 return;
1373
1374 host_state = &vmx->loaded_vmcs->host_state;
1375
1376 ++vmx->vcpu.stat.host_state_reload;
1377
1378 #ifdef CONFIG_X86_64
1379 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1380 #endif
1381 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1382 kvm_load_ldt(host_state->ldt_sel);
1383 #ifdef CONFIG_X86_64
1384 load_gs_index(host_state->gs_sel);
1385 #else
1386 loadsegment(gs, host_state->gs_sel);
1387 #endif
1388 }
1389 if (host_state->fs_sel & 7)
1390 loadsegment(fs, host_state->fs_sel);
1391 #ifdef CONFIG_X86_64
1392 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1393 loadsegment(ds, host_state->ds_sel);
1394 loadsegment(es, host_state->es_sel);
1395 }
1396 #endif
1397 invalidate_tss_limit();
1398 #ifdef CONFIG_X86_64
1399 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1400 #endif
1401 load_fixmap_gdt(raw_smp_processor_id());
1402 vmx->guest_state_loaded = false;
1403 vmx->guest_uret_msrs_loaded = false;
1404 }
1405
1406 #ifdef CONFIG_X86_64
vmx_read_guest_kernel_gs_base(struct vcpu_vmx * vmx)1407 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1408 {
1409 preempt_disable();
1410 if (vmx->guest_state_loaded)
1411 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1412 preempt_enable();
1413 return vmx->msr_guest_kernel_gs_base;
1414 }
1415
vmx_write_guest_kernel_gs_base(struct vcpu_vmx * vmx,u64 data)1416 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1417 {
1418 preempt_disable();
1419 if (vmx->guest_state_loaded)
1420 wrmsrl(MSR_KERNEL_GS_BASE, data);
1421 preempt_enable();
1422 vmx->msr_guest_kernel_gs_base = data;
1423 }
1424 #endif
1425
vmx_vcpu_load_vmcs(struct kvm_vcpu * vcpu,int cpu,struct loaded_vmcs * buddy)1426 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1427 struct loaded_vmcs *buddy)
1428 {
1429 struct vcpu_vmx *vmx = to_vmx(vcpu);
1430 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1431 struct vmcs *prev;
1432
1433 if (!already_loaded) {
1434 loaded_vmcs_clear(vmx->loaded_vmcs);
1435 local_irq_disable();
1436
1437 /*
1438 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1439 * this cpu's percpu list, otherwise it may not yet be deleted
1440 * from its previous cpu's percpu list. Pairs with the
1441 * smb_wmb() in __loaded_vmcs_clear().
1442 */
1443 smp_rmb();
1444
1445 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1446 &per_cpu(loaded_vmcss_on_cpu, cpu));
1447 local_irq_enable();
1448 }
1449
1450 prev = per_cpu(current_vmcs, cpu);
1451 if (prev != vmx->loaded_vmcs->vmcs) {
1452 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1453 vmcs_load(vmx->loaded_vmcs->vmcs);
1454
1455 /*
1456 * No indirect branch prediction barrier needed when switching
1457 * the active VMCS within a vCPU, unless IBRS is advertised to
1458 * the vCPU. To minimize the number of IBPBs executed, KVM
1459 * performs IBPB on nested VM-Exit (a single nested transition
1460 * may switch the active VMCS multiple times).
1461 */
1462 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1463 indirect_branch_prediction_barrier();
1464 }
1465
1466 if (!already_loaded) {
1467 void *gdt = get_current_gdt_ro();
1468
1469 /*
1470 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1471 * TLB entries from its previous association with the vCPU.
1472 */
1473 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1474
1475 /*
1476 * Linux uses per-cpu TSS and GDT, so set these when switching
1477 * processors. See 22.2.4.
1478 */
1479 vmcs_writel(HOST_TR_BASE,
1480 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1481 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
1482
1483 if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) {
1484 /* 22.2.3 */
1485 vmcs_writel(HOST_IA32_SYSENTER_ESP,
1486 (unsigned long)(cpu_entry_stack(cpu) + 1));
1487 }
1488
1489 vmx->loaded_vmcs->cpu = cpu;
1490 }
1491 }
1492
1493 /*
1494 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1495 * vcpu mutex is already taken.
1496 */
vmx_vcpu_load(struct kvm_vcpu * vcpu,int cpu)1497 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1498 {
1499 struct vcpu_vmx *vmx = to_vmx(vcpu);
1500
1501 vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1502
1503 vmx_vcpu_pi_load(vcpu, cpu);
1504
1505 vmx->host_debugctlmsr = get_debugctlmsr();
1506 }
1507
vmx_vcpu_put(struct kvm_vcpu * vcpu)1508 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1509 {
1510 vmx_vcpu_pi_put(vcpu);
1511
1512 vmx_prepare_switch_to_host(to_vmx(vcpu));
1513 }
1514
vmx_emulation_required(struct kvm_vcpu * vcpu)1515 bool vmx_emulation_required(struct kvm_vcpu *vcpu)
1516 {
1517 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1518 }
1519
vmx_get_rflags(struct kvm_vcpu * vcpu)1520 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1521 {
1522 struct vcpu_vmx *vmx = to_vmx(vcpu);
1523 unsigned long rflags, save_rflags;
1524
1525 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1526 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1527 rflags = vmcs_readl(GUEST_RFLAGS);
1528 if (vmx->rmode.vm86_active) {
1529 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1530 save_rflags = vmx->rmode.save_rflags;
1531 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1532 }
1533 vmx->rflags = rflags;
1534 }
1535 return vmx->rflags;
1536 }
1537
vmx_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)1538 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1539 {
1540 struct vcpu_vmx *vmx = to_vmx(vcpu);
1541 unsigned long old_rflags;
1542
1543 /*
1544 * Unlike CR0 and CR4, RFLAGS handling requires checking if the vCPU
1545 * is an unrestricted guest in order to mark L2 as needing emulation
1546 * if L1 runs L2 as a restricted guest.
1547 */
1548 if (is_unrestricted_guest(vcpu)) {
1549 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1550 vmx->rflags = rflags;
1551 vmcs_writel(GUEST_RFLAGS, rflags);
1552 return;
1553 }
1554
1555 old_rflags = vmx_get_rflags(vcpu);
1556 vmx->rflags = rflags;
1557 if (vmx->rmode.vm86_active) {
1558 vmx->rmode.save_rflags = rflags;
1559 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1560 }
1561 vmcs_writel(GUEST_RFLAGS, rflags);
1562
1563 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1564 vmx->emulation_required = vmx_emulation_required(vcpu);
1565 }
1566
vmx_get_if_flag(struct kvm_vcpu * vcpu)1567 static bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
1568 {
1569 return vmx_get_rflags(vcpu) & X86_EFLAGS_IF;
1570 }
1571
vmx_get_interrupt_shadow(struct kvm_vcpu * vcpu)1572 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1573 {
1574 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1575 int ret = 0;
1576
1577 if (interruptibility & GUEST_INTR_STATE_STI)
1578 ret |= KVM_X86_SHADOW_INT_STI;
1579 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1580 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1581
1582 return ret;
1583 }
1584
vmx_set_interrupt_shadow(struct kvm_vcpu * vcpu,int mask)1585 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1586 {
1587 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1588 u32 interruptibility = interruptibility_old;
1589
1590 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1591
1592 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1593 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1594 else if (mask & KVM_X86_SHADOW_INT_STI)
1595 interruptibility |= GUEST_INTR_STATE_STI;
1596
1597 if ((interruptibility != interruptibility_old))
1598 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1599 }
1600
vmx_rtit_ctl_check(struct kvm_vcpu * vcpu,u64 data)1601 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1602 {
1603 struct vcpu_vmx *vmx = to_vmx(vcpu);
1604 unsigned long value;
1605
1606 /*
1607 * Any MSR write that attempts to change bits marked reserved will
1608 * case a #GP fault.
1609 */
1610 if (data & vmx->pt_desc.ctl_bitmask)
1611 return 1;
1612
1613 /*
1614 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1615 * result in a #GP unless the same write also clears TraceEn.
1616 */
1617 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1618 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1619 return 1;
1620
1621 /*
1622 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1623 * and FabricEn would cause #GP, if
1624 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1625 */
1626 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1627 !(data & RTIT_CTL_FABRIC_EN) &&
1628 !intel_pt_validate_cap(vmx->pt_desc.caps,
1629 PT_CAP_single_range_output))
1630 return 1;
1631
1632 /*
1633 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1634 * utilize encodings marked reserved will cause a #GP fault.
1635 */
1636 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1637 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1638 !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1639 RTIT_CTL_MTC_RANGE_OFFSET, &value))
1640 return 1;
1641 value = intel_pt_validate_cap(vmx->pt_desc.caps,
1642 PT_CAP_cycle_thresholds);
1643 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1644 !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1645 RTIT_CTL_CYC_THRESH_OFFSET, &value))
1646 return 1;
1647 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1648 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1649 !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1650 RTIT_CTL_PSB_FREQ_OFFSET, &value))
1651 return 1;
1652
1653 /*
1654 * If ADDRx_CFG is reserved or the encodings is >2 will
1655 * cause a #GP fault.
1656 */
1657 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1658 if ((value && (vmx->pt_desc.num_address_ranges < 1)) || (value > 2))
1659 return 1;
1660 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1661 if ((value && (vmx->pt_desc.num_address_ranges < 2)) || (value > 2))
1662 return 1;
1663 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1664 if ((value && (vmx->pt_desc.num_address_ranges < 3)) || (value > 2))
1665 return 1;
1666 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1667 if ((value && (vmx->pt_desc.num_address_ranges < 4)) || (value > 2))
1668 return 1;
1669
1670 return 0;
1671 }
1672
vmx_can_emulate_instruction(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)1673 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
1674 void *insn, int insn_len)
1675 {
1676 /*
1677 * Emulation of instructions in SGX enclaves is impossible as RIP does
1678 * not point at the failing instruction, and even if it did, the code
1679 * stream is inaccessible. Inject #UD instead of exiting to userspace
1680 * so that guest userspace can't DoS the guest simply by triggering
1681 * emulation (enclaves are CPL3 only).
1682 */
1683 if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1684 kvm_queue_exception(vcpu, UD_VECTOR);
1685 return false;
1686 }
1687 return true;
1688 }
1689
skip_emulated_instruction(struct kvm_vcpu * vcpu)1690 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1691 {
1692 union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1693 unsigned long rip, orig_rip;
1694 u32 instr_len;
1695
1696 /*
1697 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1698 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1699 * set when EPT misconfig occurs. In practice, real hardware updates
1700 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1701 * (namely Hyper-V) don't set it due to it being undefined behavior,
1702 * i.e. we end up advancing IP with some random value.
1703 */
1704 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1705 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1706 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1707
1708 /*
1709 * Emulating an enclave's instructions isn't supported as KVM
1710 * cannot access the enclave's memory or its true RIP, e.g. the
1711 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1712 * the RIP that actually triggered the VM-Exit. But, because
1713 * most instructions that cause VM-Exit will #UD in an enclave,
1714 * most instruction-based VM-Exits simply do not occur.
1715 *
1716 * There are a few exceptions, notably the debug instructions
1717 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1718 * and generate #DB/#BP as expected, which KVM might intercept.
1719 * But again, the CPU does the dirty work and saves an instr
1720 * length of zero so VMMs don't shoot themselves in the foot.
1721 * WARN if KVM tries to skip a non-zero length instruction on
1722 * a VM-Exit from an enclave.
1723 */
1724 if (!instr_len)
1725 goto rip_updated;
1726
1727 WARN_ONCE(exit_reason.enclave_mode,
1728 "skipping instruction after SGX enclave VM-Exit");
1729
1730 orig_rip = kvm_rip_read(vcpu);
1731 rip = orig_rip + instr_len;
1732 #ifdef CONFIG_X86_64
1733 /*
1734 * We need to mask out the high 32 bits of RIP if not in 64-bit
1735 * mode, but just finding out that we are in 64-bit mode is
1736 * quite expensive. Only do it if there was a carry.
1737 */
1738 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1739 rip = (u32)rip;
1740 #endif
1741 kvm_rip_write(vcpu, rip);
1742 } else {
1743 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1744 return 0;
1745 }
1746
1747 rip_updated:
1748 /* skipping an emulated instruction also counts */
1749 vmx_set_interrupt_shadow(vcpu, 0);
1750
1751 return 1;
1752 }
1753
1754 /*
1755 * Recognizes a pending MTF VM-exit and records the nested state for later
1756 * delivery.
1757 */
vmx_update_emulated_instruction(struct kvm_vcpu * vcpu)1758 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1759 {
1760 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1761 struct vcpu_vmx *vmx = to_vmx(vcpu);
1762
1763 if (!is_guest_mode(vcpu))
1764 return;
1765
1766 /*
1767 * Per the SDM, MTF takes priority over debug-trap exceptions besides
1768 * TSS T-bit traps and ICEBP (INT1). KVM doesn't emulate T-bit traps
1769 * or ICEBP (in the emulator proper), and skipping of ICEBP after an
1770 * intercepted #DB deliberately avoids single-step #DB and MTF updates
1771 * as ICEBP is higher priority than both. As instruction emulation is
1772 * completed at this point (i.e. KVM is at the instruction boundary),
1773 * any #DB exception pending delivery must be a debug-trap of lower
1774 * priority than MTF. Record the pending MTF state to be delivered in
1775 * vmx_check_nested_events().
1776 */
1777 if (nested_cpu_has_mtf(vmcs12) &&
1778 (!vcpu->arch.exception.pending ||
1779 vcpu->arch.exception.vector == DB_VECTOR) &&
1780 (!vcpu->arch.exception_vmexit.pending ||
1781 vcpu->arch.exception_vmexit.vector == DB_VECTOR)) {
1782 vmx->nested.mtf_pending = true;
1783 kvm_make_request(KVM_REQ_EVENT, vcpu);
1784 } else {
1785 vmx->nested.mtf_pending = false;
1786 }
1787 }
1788
vmx_skip_emulated_instruction(struct kvm_vcpu * vcpu)1789 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1790 {
1791 vmx_update_emulated_instruction(vcpu);
1792 return skip_emulated_instruction(vcpu);
1793 }
1794
vmx_clear_hlt(struct kvm_vcpu * vcpu)1795 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1796 {
1797 /*
1798 * Ensure that we clear the HLT state in the VMCS. We don't need to
1799 * explicitly skip the instruction because if the HLT state is set,
1800 * then the instruction is already executing and RIP has already been
1801 * advanced.
1802 */
1803 if (kvm_hlt_in_guest(vcpu->kvm) &&
1804 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1805 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1806 }
1807
vmx_inject_exception(struct kvm_vcpu * vcpu)1808 static void vmx_inject_exception(struct kvm_vcpu *vcpu)
1809 {
1810 struct kvm_queued_exception *ex = &vcpu->arch.exception;
1811 u32 intr_info = ex->vector | INTR_INFO_VALID_MASK;
1812 struct vcpu_vmx *vmx = to_vmx(vcpu);
1813
1814 kvm_deliver_exception_payload(vcpu, ex);
1815
1816 if (ex->has_error_code) {
1817 /*
1818 * Despite the error code being architecturally defined as 32
1819 * bits, and the VMCS field being 32 bits, Intel CPUs and thus
1820 * VMX don't actually supporting setting bits 31:16. Hardware
1821 * will (should) never provide a bogus error code, but AMD CPUs
1822 * do generate error codes with bits 31:16 set, and so KVM's
1823 * ABI lets userspace shove in arbitrary 32-bit values. Drop
1824 * the upper bits to avoid VM-Fail, losing information that
1825 * does't really exist is preferable to killing the VM.
1826 */
1827 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)ex->error_code);
1828 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1829 }
1830
1831 if (vmx->rmode.vm86_active) {
1832 int inc_eip = 0;
1833 if (kvm_exception_is_soft(ex->vector))
1834 inc_eip = vcpu->arch.event_exit_inst_len;
1835 kvm_inject_realmode_interrupt(vcpu, ex->vector, inc_eip);
1836 return;
1837 }
1838
1839 WARN_ON_ONCE(vmx->emulation_required);
1840
1841 if (kvm_exception_is_soft(ex->vector)) {
1842 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1843 vmx->vcpu.arch.event_exit_inst_len);
1844 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1845 } else
1846 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1847
1848 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1849
1850 vmx_clear_hlt(vcpu);
1851 }
1852
vmx_setup_uret_msr(struct vcpu_vmx * vmx,unsigned int msr,bool load_into_hardware)1853 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
1854 bool load_into_hardware)
1855 {
1856 struct vmx_uret_msr *uret_msr;
1857
1858 uret_msr = vmx_find_uret_msr(vmx, msr);
1859 if (!uret_msr)
1860 return;
1861
1862 uret_msr->load_into_hardware = load_into_hardware;
1863 }
1864
1865 /*
1866 * Configuring user return MSRs to automatically save, load, and restore MSRs
1867 * that need to be shoved into hardware when running the guest. Note, omitting
1868 * an MSR here does _NOT_ mean it's not emulated, only that it will not be
1869 * loaded into hardware when running the guest.
1870 */
vmx_setup_uret_msrs(struct vcpu_vmx * vmx)1871 static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx)
1872 {
1873 #ifdef CONFIG_X86_64
1874 bool load_syscall_msrs;
1875
1876 /*
1877 * The SYSCALL MSRs are only needed on long mode guests, and only
1878 * when EFER.SCE is set.
1879 */
1880 load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
1881 (vmx->vcpu.arch.efer & EFER_SCE);
1882
1883 vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
1884 vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
1885 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
1886 #endif
1887 vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
1888
1889 vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
1890 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
1891 guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
1892
1893 /*
1894 * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
1895 * kernel and old userspace. If those guests run on a tsx=off host, do
1896 * allow guests to use TSX_CTRL, but don't change the value in hardware
1897 * so that TSX remains always disabled.
1898 */
1899 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
1900
1901 /*
1902 * The set of MSRs to load may have changed, reload MSRs before the
1903 * next VM-Enter.
1904 */
1905 vmx->guest_uret_msrs_loaded = false;
1906 }
1907
vmx_get_l2_tsc_offset(struct kvm_vcpu * vcpu)1908 u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1909 {
1910 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1911
1912 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING))
1913 return vmcs12->tsc_offset;
1914
1915 return 0;
1916 }
1917
vmx_get_l2_tsc_multiplier(struct kvm_vcpu * vcpu)1918 u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1919 {
1920 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1921
1922 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) &&
1923 nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
1924 return vmcs12->tsc_multiplier;
1925
1926 return kvm_caps.default_tsc_scaling_ratio;
1927 }
1928
vmx_write_tsc_offset(struct kvm_vcpu * vcpu)1929 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu)
1930 {
1931 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
1932 }
1933
vmx_write_tsc_multiplier(struct kvm_vcpu * vcpu)1934 static void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu)
1935 {
1936 vmcs_write64(TSC_MULTIPLIER, vcpu->arch.tsc_scaling_ratio);
1937 }
1938
1939 /*
1940 * Userspace is allowed to set any supported IA32_FEATURE_CONTROL regardless of
1941 * guest CPUID. Note, KVM allows userspace to set "VMX in SMX" to maintain
1942 * backwards compatibility even though KVM doesn't support emulating SMX. And
1943 * because userspace set "VMX in SMX", the guest must also be allowed to set it,
1944 * e.g. if the MSR is left unlocked and the guest does a RMW operation.
1945 */
1946 #define KVM_SUPPORTED_FEATURE_CONTROL (FEAT_CTL_LOCKED | \
1947 FEAT_CTL_VMX_ENABLED_INSIDE_SMX | \
1948 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX | \
1949 FEAT_CTL_SGX_LC_ENABLED | \
1950 FEAT_CTL_SGX_ENABLED | \
1951 FEAT_CTL_LMCE_ENABLED)
1952
is_vmx_feature_control_msr_valid(struct vcpu_vmx * vmx,struct msr_data * msr)1953 static inline bool is_vmx_feature_control_msr_valid(struct vcpu_vmx *vmx,
1954 struct msr_data *msr)
1955 {
1956 uint64_t valid_bits;
1957
1958 /*
1959 * Ensure KVM_SUPPORTED_FEATURE_CONTROL is updated when new bits are
1960 * exposed to the guest.
1961 */
1962 WARN_ON_ONCE(vmx->msr_ia32_feature_control_valid_bits &
1963 ~KVM_SUPPORTED_FEATURE_CONTROL);
1964
1965 if (!msr->host_initiated &&
1966 (vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED))
1967 return false;
1968
1969 if (msr->host_initiated)
1970 valid_bits = KVM_SUPPORTED_FEATURE_CONTROL;
1971 else
1972 valid_bits = vmx->msr_ia32_feature_control_valid_bits;
1973
1974 return !(msr->data & ~valid_bits);
1975 }
1976
vmx_get_msr_feature(struct kvm_msr_entry * msr)1977 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1978 {
1979 switch (msr->index) {
1980 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR:
1981 if (!nested)
1982 return 1;
1983 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1984 default:
1985 return KVM_MSR_RET_INVALID;
1986 }
1987 }
1988
1989 /*
1990 * Reads an msr value (of 'msr_info->index') into 'msr_info->data'.
1991 * Returns 0 on success, non-0 otherwise.
1992 * Assumes vcpu_load() was already called.
1993 */
vmx_get_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1994 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1995 {
1996 struct vcpu_vmx *vmx = to_vmx(vcpu);
1997 struct vmx_uret_msr *msr;
1998 u32 index;
1999
2000 switch (msr_info->index) {
2001 #ifdef CONFIG_X86_64
2002 case MSR_FS_BASE:
2003 msr_info->data = vmcs_readl(GUEST_FS_BASE);
2004 break;
2005 case MSR_GS_BASE:
2006 msr_info->data = vmcs_readl(GUEST_GS_BASE);
2007 break;
2008 case MSR_KERNEL_GS_BASE:
2009 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
2010 break;
2011 #endif
2012 case MSR_EFER:
2013 return kvm_get_msr_common(vcpu, msr_info);
2014 case MSR_IA32_TSX_CTRL:
2015 if (!msr_info->host_initiated &&
2016 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2017 return 1;
2018 goto find_uret_msr;
2019 case MSR_IA32_UMWAIT_CONTROL:
2020 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2021 return 1;
2022
2023 msr_info->data = vmx->msr_ia32_umwait_control;
2024 break;
2025 case MSR_IA32_SPEC_CTRL:
2026 if (!msr_info->host_initiated &&
2027 !guest_has_spec_ctrl_msr(vcpu))
2028 return 1;
2029
2030 msr_info->data = to_vmx(vcpu)->spec_ctrl;
2031 break;
2032 case MSR_IA32_SYSENTER_CS:
2033 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
2034 break;
2035 case MSR_IA32_SYSENTER_EIP:
2036 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
2037 break;
2038 case MSR_IA32_SYSENTER_ESP:
2039 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
2040 break;
2041 case MSR_IA32_BNDCFGS:
2042 if (!kvm_mpx_supported() ||
2043 (!msr_info->host_initiated &&
2044 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2045 return 1;
2046 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
2047 break;
2048 case MSR_IA32_MCG_EXT_CTL:
2049 if (!msr_info->host_initiated &&
2050 !(vmx->msr_ia32_feature_control &
2051 FEAT_CTL_LMCE_ENABLED))
2052 return 1;
2053 msr_info->data = vcpu->arch.mcg_ext_ctl;
2054 break;
2055 case MSR_IA32_FEAT_CTL:
2056 msr_info->data = vmx->msr_ia32_feature_control;
2057 break;
2058 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2059 if (!msr_info->host_initiated &&
2060 !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
2061 return 1;
2062 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
2063 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
2064 break;
2065 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR:
2066 if (!guest_can_use(vcpu, X86_FEATURE_VMX))
2067 return 1;
2068 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
2069 &msr_info->data))
2070 return 1;
2071 /*
2072 * Enlightened VMCS v1 doesn't have certain VMCS fields but
2073 * instead of just ignoring the features, different Hyper-V
2074 * versions are either trying to use them and fail or do some
2075 * sanity checking and refuse to boot. Filter all unsupported
2076 * features out.
2077 */
2078 if (!msr_info->host_initiated && guest_cpuid_has_evmcs(vcpu))
2079 nested_evmcs_filter_control_msr(vcpu, msr_info->index,
2080 &msr_info->data);
2081 break;
2082 case MSR_IA32_RTIT_CTL:
2083 if (!vmx_pt_mode_is_host_guest())
2084 return 1;
2085 msr_info->data = vmx->pt_desc.guest.ctl;
2086 break;
2087 case MSR_IA32_RTIT_STATUS:
2088 if (!vmx_pt_mode_is_host_guest())
2089 return 1;
2090 msr_info->data = vmx->pt_desc.guest.status;
2091 break;
2092 case MSR_IA32_RTIT_CR3_MATCH:
2093 if (!vmx_pt_mode_is_host_guest() ||
2094 !intel_pt_validate_cap(vmx->pt_desc.caps,
2095 PT_CAP_cr3_filtering))
2096 return 1;
2097 msr_info->data = vmx->pt_desc.guest.cr3_match;
2098 break;
2099 case MSR_IA32_RTIT_OUTPUT_BASE:
2100 if (!vmx_pt_mode_is_host_guest() ||
2101 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2102 PT_CAP_topa_output) &&
2103 !intel_pt_validate_cap(vmx->pt_desc.caps,
2104 PT_CAP_single_range_output)))
2105 return 1;
2106 msr_info->data = vmx->pt_desc.guest.output_base;
2107 break;
2108 case MSR_IA32_RTIT_OUTPUT_MASK:
2109 if (!vmx_pt_mode_is_host_guest() ||
2110 (!intel_pt_validate_cap(vmx->pt_desc.caps,
2111 PT_CAP_topa_output) &&
2112 !intel_pt_validate_cap(vmx->pt_desc.caps,
2113 PT_CAP_single_range_output)))
2114 return 1;
2115 msr_info->data = vmx->pt_desc.guest.output_mask;
2116 break;
2117 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2118 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2119 if (!vmx_pt_mode_is_host_guest() ||
2120 (index >= 2 * vmx->pt_desc.num_address_ranges))
2121 return 1;
2122 if (index % 2)
2123 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
2124 else
2125 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
2126 break;
2127 case MSR_IA32_DEBUGCTLMSR:
2128 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
2129 break;
2130 default:
2131 find_uret_msr:
2132 msr = vmx_find_uret_msr(vmx, msr_info->index);
2133 if (msr) {
2134 msr_info->data = msr->data;
2135 break;
2136 }
2137 return kvm_get_msr_common(vcpu, msr_info);
2138 }
2139
2140 return 0;
2141 }
2142
nested_vmx_truncate_sysenter_addr(struct kvm_vcpu * vcpu,u64 data)2143 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
2144 u64 data)
2145 {
2146 #ifdef CONFIG_X86_64
2147 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
2148 return (u32)data;
2149 #endif
2150 return (unsigned long)data;
2151 }
2152
vmx_get_supported_debugctl(struct kvm_vcpu * vcpu,bool host_initiated)2153 static u64 vmx_get_supported_debugctl(struct kvm_vcpu *vcpu, bool host_initiated)
2154 {
2155 u64 debugctl = 0;
2156
2157 if (boot_cpu_has(X86_FEATURE_BUS_LOCK_DETECT) &&
2158 (host_initiated || guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT)))
2159 debugctl |= DEBUGCTLMSR_BUS_LOCK_DETECT;
2160
2161 if ((kvm_caps.supported_perf_cap & PMU_CAP_LBR_FMT) &&
2162 (host_initiated || intel_pmu_lbr_is_enabled(vcpu)))
2163 debugctl |= DEBUGCTLMSR_LBR | DEBUGCTLMSR_FREEZE_LBRS_ON_PMI;
2164
2165 return debugctl;
2166 }
2167
2168 /*
2169 * Writes msr value into the appropriate "register".
2170 * Returns 0 on success, non-0 otherwise.
2171 * Assumes vcpu_load() was already called.
2172 */
vmx_set_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)2173 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2174 {
2175 struct vcpu_vmx *vmx = to_vmx(vcpu);
2176 struct vmx_uret_msr *msr;
2177 int ret = 0;
2178 u32 msr_index = msr_info->index;
2179 u64 data = msr_info->data;
2180 u32 index;
2181
2182 switch (msr_index) {
2183 case MSR_EFER:
2184 ret = kvm_set_msr_common(vcpu, msr_info);
2185 break;
2186 #ifdef CONFIG_X86_64
2187 case MSR_FS_BASE:
2188 vmx_segment_cache_clear(vmx);
2189 vmcs_writel(GUEST_FS_BASE, data);
2190 break;
2191 case MSR_GS_BASE:
2192 vmx_segment_cache_clear(vmx);
2193 vmcs_writel(GUEST_GS_BASE, data);
2194 break;
2195 case MSR_KERNEL_GS_BASE:
2196 vmx_write_guest_kernel_gs_base(vmx, data);
2197 break;
2198 case MSR_IA32_XFD:
2199 ret = kvm_set_msr_common(vcpu, msr_info);
2200 /*
2201 * Always intercepting WRMSR could incur non-negligible
2202 * overhead given xfd might be changed frequently in
2203 * guest context switch. Disable write interception
2204 * upon the first write with a non-zero value (indicating
2205 * potential usage on dynamic xfeatures). Also update
2206 * exception bitmap to trap #NM for proper virtualization
2207 * of guest xfd_err.
2208 */
2209 if (!ret && data) {
2210 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_XFD,
2211 MSR_TYPE_RW);
2212 vcpu->arch.xfd_no_write_intercept = true;
2213 vmx_update_exception_bitmap(vcpu);
2214 }
2215 break;
2216 #endif
2217 case MSR_IA32_SYSENTER_CS:
2218 if (is_guest_mode(vcpu))
2219 get_vmcs12(vcpu)->guest_sysenter_cs = data;
2220 vmcs_write32(GUEST_SYSENTER_CS, data);
2221 break;
2222 case MSR_IA32_SYSENTER_EIP:
2223 if (is_guest_mode(vcpu)) {
2224 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2225 get_vmcs12(vcpu)->guest_sysenter_eip = data;
2226 }
2227 vmcs_writel(GUEST_SYSENTER_EIP, data);
2228 break;
2229 case MSR_IA32_SYSENTER_ESP:
2230 if (is_guest_mode(vcpu)) {
2231 data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2232 get_vmcs12(vcpu)->guest_sysenter_esp = data;
2233 }
2234 vmcs_writel(GUEST_SYSENTER_ESP, data);
2235 break;
2236 case MSR_IA32_DEBUGCTLMSR: {
2237 u64 invalid;
2238
2239 invalid = data & ~vmx_get_supported_debugctl(vcpu, msr_info->host_initiated);
2240 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2241 kvm_pr_unimpl_wrmsr(vcpu, msr_index, data);
2242 data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2243 invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2244 }
2245
2246 if (invalid)
2247 return 1;
2248
2249 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2250 VM_EXIT_SAVE_DEBUG_CONTROLS)
2251 get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2252
2253 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2254 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2255 (data & DEBUGCTLMSR_LBR))
2256 intel_pmu_create_guest_lbr_event(vcpu);
2257 return 0;
2258 }
2259 case MSR_IA32_BNDCFGS:
2260 if (!kvm_mpx_supported() ||
2261 (!msr_info->host_initiated &&
2262 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2263 return 1;
2264 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2265 (data & MSR_IA32_BNDCFGS_RSVD))
2266 return 1;
2267
2268 if (is_guest_mode(vcpu) &&
2269 ((vmx->nested.msrs.entry_ctls_high & VM_ENTRY_LOAD_BNDCFGS) ||
2270 (vmx->nested.msrs.exit_ctls_high & VM_EXIT_CLEAR_BNDCFGS)))
2271 get_vmcs12(vcpu)->guest_bndcfgs = data;
2272
2273 vmcs_write64(GUEST_BNDCFGS, data);
2274 break;
2275 case MSR_IA32_UMWAIT_CONTROL:
2276 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2277 return 1;
2278
2279 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2280 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2281 return 1;
2282
2283 vmx->msr_ia32_umwait_control = data;
2284 break;
2285 case MSR_IA32_SPEC_CTRL:
2286 if (!msr_info->host_initiated &&
2287 !guest_has_spec_ctrl_msr(vcpu))
2288 return 1;
2289
2290 if (kvm_spec_ctrl_test_value(data))
2291 return 1;
2292
2293 vmx->spec_ctrl = data;
2294 if (!data)
2295 break;
2296
2297 /*
2298 * For non-nested:
2299 * When it's written (to non-zero) for the first time, pass
2300 * it through.
2301 *
2302 * For nested:
2303 * The handling of the MSR bitmap for L2 guests is done in
2304 * nested_vmx_prepare_msr_bitmap. We should not touch the
2305 * vmcs02.msr_bitmap here since it gets completely overwritten
2306 * in the merging. We update the vmcs01 here for L1 as well
2307 * since it will end up touching the MSR anyway now.
2308 */
2309 vmx_disable_intercept_for_msr(vcpu,
2310 MSR_IA32_SPEC_CTRL,
2311 MSR_TYPE_RW);
2312 break;
2313 case MSR_IA32_TSX_CTRL:
2314 if (!msr_info->host_initiated &&
2315 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2316 return 1;
2317 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2318 return 1;
2319 goto find_uret_msr;
2320 case MSR_IA32_CR_PAT:
2321 ret = kvm_set_msr_common(vcpu, msr_info);
2322 if (ret)
2323 break;
2324
2325 if (is_guest_mode(vcpu) &&
2326 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2327 get_vmcs12(vcpu)->guest_ia32_pat = data;
2328
2329 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
2330 vmcs_write64(GUEST_IA32_PAT, data);
2331 break;
2332 case MSR_IA32_MCG_EXT_CTL:
2333 if ((!msr_info->host_initiated &&
2334 !(to_vmx(vcpu)->msr_ia32_feature_control &
2335 FEAT_CTL_LMCE_ENABLED)) ||
2336 (data & ~MCG_EXT_CTL_LMCE_EN))
2337 return 1;
2338 vcpu->arch.mcg_ext_ctl = data;
2339 break;
2340 case MSR_IA32_FEAT_CTL:
2341 if (!is_vmx_feature_control_msr_valid(vmx, msr_info))
2342 return 1;
2343
2344 vmx->msr_ia32_feature_control = data;
2345 if (msr_info->host_initiated && data == 0)
2346 vmx_leave_nested(vcpu);
2347
2348 /* SGX may be enabled/disabled by guest's firmware */
2349 vmx_write_encls_bitmap(vcpu, NULL);
2350 break;
2351 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2352 /*
2353 * On real hardware, the LE hash MSRs are writable before
2354 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2355 * at which point SGX related bits in IA32_FEATURE_CONTROL
2356 * become writable.
2357 *
2358 * KVM does not emulate SGX activation for simplicity, so
2359 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2360 * is unlocked. This is technically not architectural
2361 * behavior, but it's close enough.
2362 */
2363 if (!msr_info->host_initiated &&
2364 (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2365 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2366 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2367 return 1;
2368 vmx->msr_ia32_sgxlepubkeyhash
2369 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2370 break;
2371 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR:
2372 if (!msr_info->host_initiated)
2373 return 1; /* they are read-only */
2374 if (!guest_can_use(vcpu, X86_FEATURE_VMX))
2375 return 1;
2376 return vmx_set_vmx_msr(vcpu, msr_index, data);
2377 case MSR_IA32_RTIT_CTL:
2378 if (!vmx_pt_mode_is_host_guest() ||
2379 vmx_rtit_ctl_check(vcpu, data) ||
2380 vmx->nested.vmxon)
2381 return 1;
2382 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2383 vmx->pt_desc.guest.ctl = data;
2384 pt_update_intercept_for_msr(vcpu);
2385 break;
2386 case MSR_IA32_RTIT_STATUS:
2387 if (!pt_can_write_msr(vmx))
2388 return 1;
2389 if (data & MSR_IA32_RTIT_STATUS_MASK)
2390 return 1;
2391 vmx->pt_desc.guest.status = data;
2392 break;
2393 case MSR_IA32_RTIT_CR3_MATCH:
2394 if (!pt_can_write_msr(vmx))
2395 return 1;
2396 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2397 PT_CAP_cr3_filtering))
2398 return 1;
2399 vmx->pt_desc.guest.cr3_match = data;
2400 break;
2401 case MSR_IA32_RTIT_OUTPUT_BASE:
2402 if (!pt_can_write_msr(vmx))
2403 return 1;
2404 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2405 PT_CAP_topa_output) &&
2406 !intel_pt_validate_cap(vmx->pt_desc.caps,
2407 PT_CAP_single_range_output))
2408 return 1;
2409 if (!pt_output_base_valid(vcpu, data))
2410 return 1;
2411 vmx->pt_desc.guest.output_base = data;
2412 break;
2413 case MSR_IA32_RTIT_OUTPUT_MASK:
2414 if (!pt_can_write_msr(vmx))
2415 return 1;
2416 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2417 PT_CAP_topa_output) &&
2418 !intel_pt_validate_cap(vmx->pt_desc.caps,
2419 PT_CAP_single_range_output))
2420 return 1;
2421 vmx->pt_desc.guest.output_mask = data;
2422 break;
2423 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2424 if (!pt_can_write_msr(vmx))
2425 return 1;
2426 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2427 if (index >= 2 * vmx->pt_desc.num_address_ranges)
2428 return 1;
2429 if (is_noncanonical_address(data, vcpu))
2430 return 1;
2431 if (index % 2)
2432 vmx->pt_desc.guest.addr_b[index / 2] = data;
2433 else
2434 vmx->pt_desc.guest.addr_a[index / 2] = data;
2435 break;
2436 case MSR_IA32_PERF_CAPABILITIES:
2437 if (data && !vcpu_to_pmu(vcpu)->version)
2438 return 1;
2439 if (data & PMU_CAP_LBR_FMT) {
2440 if ((data & PMU_CAP_LBR_FMT) !=
2441 (kvm_caps.supported_perf_cap & PMU_CAP_LBR_FMT))
2442 return 1;
2443 if (!cpuid_model_is_consistent(vcpu))
2444 return 1;
2445 }
2446 if (data & PERF_CAP_PEBS_FORMAT) {
2447 if ((data & PERF_CAP_PEBS_MASK) !=
2448 (kvm_caps.supported_perf_cap & PERF_CAP_PEBS_MASK))
2449 return 1;
2450 if (!guest_cpuid_has(vcpu, X86_FEATURE_DS))
2451 return 1;
2452 if (!guest_cpuid_has(vcpu, X86_FEATURE_DTES64))
2453 return 1;
2454 if (!cpuid_model_is_consistent(vcpu))
2455 return 1;
2456 }
2457 ret = kvm_set_msr_common(vcpu, msr_info);
2458 break;
2459
2460 default:
2461 find_uret_msr:
2462 msr = vmx_find_uret_msr(vmx, msr_index);
2463 if (msr)
2464 ret = vmx_set_guest_uret_msr(vmx, msr, data);
2465 else
2466 ret = kvm_set_msr_common(vcpu, msr_info);
2467 }
2468
2469 /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */
2470 if (msr_index == MSR_IA32_ARCH_CAPABILITIES)
2471 vmx_update_fb_clear_dis(vcpu, vmx);
2472
2473 return ret;
2474 }
2475
vmx_cache_reg(struct kvm_vcpu * vcpu,enum kvm_reg reg)2476 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2477 {
2478 unsigned long guest_owned_bits;
2479
2480 kvm_register_mark_available(vcpu, reg);
2481
2482 switch (reg) {
2483 case VCPU_REGS_RSP:
2484 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2485 break;
2486 case VCPU_REGS_RIP:
2487 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2488 break;
2489 case VCPU_EXREG_PDPTR:
2490 if (enable_ept)
2491 ept_save_pdptrs(vcpu);
2492 break;
2493 case VCPU_EXREG_CR0:
2494 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2495
2496 vcpu->arch.cr0 &= ~guest_owned_bits;
2497 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2498 break;
2499 case VCPU_EXREG_CR3:
2500 /*
2501 * When intercepting CR3 loads, e.g. for shadowing paging, KVM's
2502 * CR3 is loaded into hardware, not the guest's CR3.
2503 */
2504 if (!(exec_controls_get(to_vmx(vcpu)) & CPU_BASED_CR3_LOAD_EXITING))
2505 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2506 break;
2507 case VCPU_EXREG_CR4:
2508 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2509
2510 vcpu->arch.cr4 &= ~guest_owned_bits;
2511 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2512 break;
2513 default:
2514 KVM_BUG_ON(1, vcpu->kvm);
2515 break;
2516 }
2517 }
2518
2519 /*
2520 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2521 * directly instead of going through cpu_has(), to ensure KVM is trapping
2522 * ENCLS whenever it's supported in hardware. It does not matter whether
2523 * the host OS supports or has enabled SGX.
2524 */
cpu_has_sgx(void)2525 static bool cpu_has_sgx(void)
2526 {
2527 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2528 }
2529
2530 /*
2531 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2532 * can't be used due to errata where VM Exit may incorrectly clear
2533 * IA32_PERF_GLOBAL_CTRL[34:32]. Work around the errata by using the
2534 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2535 */
cpu_has_perf_global_ctrl_bug(void)2536 static bool cpu_has_perf_global_ctrl_bug(void)
2537 {
2538 if (boot_cpu_data.x86 == 0x6) {
2539 switch (boot_cpu_data.x86_model) {
2540 case INTEL_FAM6_NEHALEM_EP: /* AAK155 */
2541 case INTEL_FAM6_NEHALEM: /* AAP115 */
2542 case INTEL_FAM6_WESTMERE: /* AAT100 */
2543 case INTEL_FAM6_WESTMERE_EP: /* BC86,AAY89,BD102 */
2544 case INTEL_FAM6_NEHALEM_EX: /* BA97 */
2545 return true;
2546 default:
2547 break;
2548 }
2549 }
2550
2551 return false;
2552 }
2553
adjust_vmx_controls(u32 ctl_min,u32 ctl_opt,u32 msr,u32 * result)2554 static int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt, u32 msr, u32 *result)
2555 {
2556 u32 vmx_msr_low, vmx_msr_high;
2557 u32 ctl = ctl_min | ctl_opt;
2558
2559 rdmsr(msr, vmx_msr_low, vmx_msr_high);
2560
2561 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2562 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
2563
2564 /* Ensure minimum (required) set of control bits are supported. */
2565 if (ctl_min & ~ctl)
2566 return -EIO;
2567
2568 *result = ctl;
2569 return 0;
2570 }
2571
adjust_vmx_controls64(u64 ctl_opt,u32 msr)2572 static u64 adjust_vmx_controls64(u64 ctl_opt, u32 msr)
2573 {
2574 u64 allowed;
2575
2576 rdmsrl(msr, allowed);
2577
2578 return ctl_opt & allowed;
2579 }
2580
setup_vmcs_config(struct vmcs_config * vmcs_conf,struct vmx_capability * vmx_cap)2581 static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2582 struct vmx_capability *vmx_cap)
2583 {
2584 u32 vmx_msr_low, vmx_msr_high;
2585 u32 _pin_based_exec_control = 0;
2586 u32 _cpu_based_exec_control = 0;
2587 u32 _cpu_based_2nd_exec_control = 0;
2588 u64 _cpu_based_3rd_exec_control = 0;
2589 u32 _vmexit_control = 0;
2590 u32 _vmentry_control = 0;
2591 u64 misc_msr;
2592 int i;
2593
2594 /*
2595 * LOAD/SAVE_DEBUG_CONTROLS are absent because both are mandatory.
2596 * SAVE_IA32_PAT and SAVE_IA32_EFER are absent because KVM always
2597 * intercepts writes to PAT and EFER, i.e. never enables those controls.
2598 */
2599 struct {
2600 u32 entry_control;
2601 u32 exit_control;
2602 } const vmcs_entry_exit_pairs[] = {
2603 { VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL },
2604 { VM_ENTRY_LOAD_IA32_PAT, VM_EXIT_LOAD_IA32_PAT },
2605 { VM_ENTRY_LOAD_IA32_EFER, VM_EXIT_LOAD_IA32_EFER },
2606 { VM_ENTRY_LOAD_BNDCFGS, VM_EXIT_CLEAR_BNDCFGS },
2607 { VM_ENTRY_LOAD_IA32_RTIT_CTL, VM_EXIT_CLEAR_IA32_RTIT_CTL },
2608 };
2609
2610 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2611
2612 if (adjust_vmx_controls(KVM_REQUIRED_VMX_CPU_BASED_VM_EXEC_CONTROL,
2613 KVM_OPTIONAL_VMX_CPU_BASED_VM_EXEC_CONTROL,
2614 MSR_IA32_VMX_PROCBASED_CTLS,
2615 &_cpu_based_exec_control))
2616 return -EIO;
2617 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2618 if (adjust_vmx_controls(KVM_REQUIRED_VMX_SECONDARY_VM_EXEC_CONTROL,
2619 KVM_OPTIONAL_VMX_SECONDARY_VM_EXEC_CONTROL,
2620 MSR_IA32_VMX_PROCBASED_CTLS2,
2621 &_cpu_based_2nd_exec_control))
2622 return -EIO;
2623 }
2624 #ifndef CONFIG_X86_64
2625 if (!(_cpu_based_2nd_exec_control &
2626 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2627 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2628 #endif
2629
2630 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2631 _cpu_based_2nd_exec_control &= ~(
2632 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2633 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2634 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2635
2636 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2637 &vmx_cap->ept, &vmx_cap->vpid);
2638
2639 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
2640 vmx_cap->ept) {
2641 pr_warn_once("EPT CAP should not exist if not support "
2642 "1-setting enable EPT VM-execution control\n");
2643
2644 if (error_on_inconsistent_vmcs_config)
2645 return -EIO;
2646
2647 vmx_cap->ept = 0;
2648 }
2649 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2650 vmx_cap->vpid) {
2651 pr_warn_once("VPID CAP should not exist if not support "
2652 "1-setting enable VPID VM-execution control\n");
2653
2654 if (error_on_inconsistent_vmcs_config)
2655 return -EIO;
2656
2657 vmx_cap->vpid = 0;
2658 }
2659
2660 if (!cpu_has_sgx())
2661 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_ENCLS_EXITING;
2662
2663 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_TERTIARY_CONTROLS)
2664 _cpu_based_3rd_exec_control =
2665 adjust_vmx_controls64(KVM_OPTIONAL_VMX_TERTIARY_VM_EXEC_CONTROL,
2666 MSR_IA32_VMX_PROCBASED_CTLS3);
2667
2668 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_EXIT_CONTROLS,
2669 KVM_OPTIONAL_VMX_VM_EXIT_CONTROLS,
2670 MSR_IA32_VMX_EXIT_CTLS,
2671 &_vmexit_control))
2672 return -EIO;
2673
2674 if (adjust_vmx_controls(KVM_REQUIRED_VMX_PIN_BASED_VM_EXEC_CONTROL,
2675 KVM_OPTIONAL_VMX_PIN_BASED_VM_EXEC_CONTROL,
2676 MSR_IA32_VMX_PINBASED_CTLS,
2677 &_pin_based_exec_control))
2678 return -EIO;
2679
2680 if (cpu_has_broken_vmx_preemption_timer())
2681 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2682 if (!(_cpu_based_2nd_exec_control &
2683 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2684 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2685
2686 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_ENTRY_CONTROLS,
2687 KVM_OPTIONAL_VMX_VM_ENTRY_CONTROLS,
2688 MSR_IA32_VMX_ENTRY_CTLS,
2689 &_vmentry_control))
2690 return -EIO;
2691
2692 for (i = 0; i < ARRAY_SIZE(vmcs_entry_exit_pairs); i++) {
2693 u32 n_ctrl = vmcs_entry_exit_pairs[i].entry_control;
2694 u32 x_ctrl = vmcs_entry_exit_pairs[i].exit_control;
2695
2696 if (!(_vmentry_control & n_ctrl) == !(_vmexit_control & x_ctrl))
2697 continue;
2698
2699 pr_warn_once("Inconsistent VM-Entry/VM-Exit pair, entry = %x, exit = %x\n",
2700 _vmentry_control & n_ctrl, _vmexit_control & x_ctrl);
2701
2702 if (error_on_inconsistent_vmcs_config)
2703 return -EIO;
2704
2705 _vmentry_control &= ~n_ctrl;
2706 _vmexit_control &= ~x_ctrl;
2707 }
2708
2709 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2710
2711 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2712 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2713 return -EIO;
2714
2715 #ifdef CONFIG_X86_64
2716 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2717 if (vmx_msr_high & (1u<<16))
2718 return -EIO;
2719 #endif
2720
2721 /* Require Write-Back (WB) memory type for VMCS accesses. */
2722 if (((vmx_msr_high >> 18) & 15) != 6)
2723 return -EIO;
2724
2725 rdmsrl(MSR_IA32_VMX_MISC, misc_msr);
2726
2727 vmcs_conf->size = vmx_msr_high & 0x1fff;
2728 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2729
2730 vmcs_conf->revision_id = vmx_msr_low;
2731
2732 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2733 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2734 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2735 vmcs_conf->cpu_based_3rd_exec_ctrl = _cpu_based_3rd_exec_control;
2736 vmcs_conf->vmexit_ctrl = _vmexit_control;
2737 vmcs_conf->vmentry_ctrl = _vmentry_control;
2738 vmcs_conf->misc = misc_msr;
2739
2740 #if IS_ENABLED(CONFIG_HYPERV)
2741 if (enlightened_vmcs)
2742 evmcs_sanitize_exec_ctrls(vmcs_conf);
2743 #endif
2744
2745 return 0;
2746 }
2747
__kvm_is_vmx_supported(void)2748 static bool __kvm_is_vmx_supported(void)
2749 {
2750 int cpu = smp_processor_id();
2751
2752 if (!(cpuid_ecx(1) & feature_bit(VMX))) {
2753 pr_err("VMX not supported by CPU %d\n", cpu);
2754 return false;
2755 }
2756
2757 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2758 !this_cpu_has(X86_FEATURE_VMX)) {
2759 pr_err("VMX not enabled (by BIOS) in MSR_IA32_FEAT_CTL on CPU %d\n", cpu);
2760 return false;
2761 }
2762
2763 return true;
2764 }
2765
kvm_is_vmx_supported(void)2766 static bool kvm_is_vmx_supported(void)
2767 {
2768 bool supported;
2769
2770 migrate_disable();
2771 supported = __kvm_is_vmx_supported();
2772 migrate_enable();
2773
2774 return supported;
2775 }
2776
vmx_check_processor_compat(void)2777 static int vmx_check_processor_compat(void)
2778 {
2779 int cpu = raw_smp_processor_id();
2780 struct vmcs_config vmcs_conf;
2781 struct vmx_capability vmx_cap;
2782
2783 if (!__kvm_is_vmx_supported())
2784 return -EIO;
2785
2786 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0) {
2787 pr_err("Failed to setup VMCS config on CPU %d\n", cpu);
2788 return -EIO;
2789 }
2790 if (nested)
2791 nested_vmx_setup_ctls_msrs(&vmcs_conf, vmx_cap.ept);
2792 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config))) {
2793 pr_err("Inconsistent VMCS config on CPU %d\n", cpu);
2794 return -EIO;
2795 }
2796 return 0;
2797 }
2798
kvm_cpu_vmxon(u64 vmxon_pointer)2799 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2800 {
2801 u64 msr;
2802
2803 cr4_set_bits(X86_CR4_VMXE);
2804
2805 asm goto("1: vmxon %[vmxon_pointer]\n\t"
2806 _ASM_EXTABLE(1b, %l[fault])
2807 : : [vmxon_pointer] "m"(vmxon_pointer)
2808 : : fault);
2809 return 0;
2810
2811 fault:
2812 WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2813 rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2814 cr4_clear_bits(X86_CR4_VMXE);
2815
2816 return -EFAULT;
2817 }
2818
vmx_hardware_enable(void)2819 static int vmx_hardware_enable(void)
2820 {
2821 int cpu = raw_smp_processor_id();
2822 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2823 int r;
2824
2825 if (cr4_read_shadow() & X86_CR4_VMXE)
2826 return -EBUSY;
2827
2828 /*
2829 * This can happen if we hot-added a CPU but failed to allocate
2830 * VP assist page for it.
2831 */
2832 if (kvm_is_using_evmcs() && !hv_get_vp_assist_page(cpu))
2833 return -EFAULT;
2834
2835 intel_pt_handle_vmx(1);
2836
2837 r = kvm_cpu_vmxon(phys_addr);
2838 if (r) {
2839 intel_pt_handle_vmx(0);
2840 return r;
2841 }
2842
2843 if (enable_ept)
2844 ept_sync_global();
2845
2846 return 0;
2847 }
2848
vmclear_local_loaded_vmcss(void)2849 static void vmclear_local_loaded_vmcss(void)
2850 {
2851 int cpu = raw_smp_processor_id();
2852 struct loaded_vmcs *v, *n;
2853
2854 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2855 loaded_vmcss_on_cpu_link)
2856 __loaded_vmcs_clear(v);
2857 }
2858
vmx_hardware_disable(void)2859 static void vmx_hardware_disable(void)
2860 {
2861 vmclear_local_loaded_vmcss();
2862
2863 if (kvm_cpu_vmxoff())
2864 kvm_spurious_fault();
2865
2866 hv_reset_evmcs();
2867
2868 intel_pt_handle_vmx(0);
2869 }
2870
alloc_vmcs_cpu(bool shadow,int cpu,gfp_t flags)2871 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2872 {
2873 int node = cpu_to_node(cpu);
2874 struct page *pages;
2875 struct vmcs *vmcs;
2876
2877 pages = __alloc_pages_node(node, flags, 0);
2878 if (!pages)
2879 return NULL;
2880 vmcs = page_address(pages);
2881 memset(vmcs, 0, vmcs_config.size);
2882
2883 /* KVM supports Enlightened VMCS v1 only */
2884 if (kvm_is_using_evmcs())
2885 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2886 else
2887 vmcs->hdr.revision_id = vmcs_config.revision_id;
2888
2889 if (shadow)
2890 vmcs->hdr.shadow_vmcs = 1;
2891 return vmcs;
2892 }
2893
free_vmcs(struct vmcs * vmcs)2894 void free_vmcs(struct vmcs *vmcs)
2895 {
2896 free_page((unsigned long)vmcs);
2897 }
2898
2899 /*
2900 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2901 */
free_loaded_vmcs(struct loaded_vmcs * loaded_vmcs)2902 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2903 {
2904 if (!loaded_vmcs->vmcs)
2905 return;
2906 loaded_vmcs_clear(loaded_vmcs);
2907 free_vmcs(loaded_vmcs->vmcs);
2908 loaded_vmcs->vmcs = NULL;
2909 if (loaded_vmcs->msr_bitmap)
2910 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2911 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2912 }
2913
alloc_loaded_vmcs(struct loaded_vmcs * loaded_vmcs)2914 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2915 {
2916 loaded_vmcs->vmcs = alloc_vmcs(false);
2917 if (!loaded_vmcs->vmcs)
2918 return -ENOMEM;
2919
2920 vmcs_clear(loaded_vmcs->vmcs);
2921
2922 loaded_vmcs->shadow_vmcs = NULL;
2923 loaded_vmcs->hv_timer_soft_disabled = false;
2924 loaded_vmcs->cpu = -1;
2925 loaded_vmcs->launched = 0;
2926
2927 if (cpu_has_vmx_msr_bitmap()) {
2928 loaded_vmcs->msr_bitmap = (unsigned long *)
2929 __get_free_page(GFP_KERNEL_ACCOUNT);
2930 if (!loaded_vmcs->msr_bitmap)
2931 goto out_vmcs;
2932 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2933 }
2934
2935 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2936 memset(&loaded_vmcs->controls_shadow, 0,
2937 sizeof(struct vmcs_controls_shadow));
2938
2939 return 0;
2940
2941 out_vmcs:
2942 free_loaded_vmcs(loaded_vmcs);
2943 return -ENOMEM;
2944 }
2945
free_kvm_area(void)2946 static void free_kvm_area(void)
2947 {
2948 int cpu;
2949
2950 for_each_possible_cpu(cpu) {
2951 free_vmcs(per_cpu(vmxarea, cpu));
2952 per_cpu(vmxarea, cpu) = NULL;
2953 }
2954 }
2955
alloc_kvm_area(void)2956 static __init int alloc_kvm_area(void)
2957 {
2958 int cpu;
2959
2960 for_each_possible_cpu(cpu) {
2961 struct vmcs *vmcs;
2962
2963 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2964 if (!vmcs) {
2965 free_kvm_area();
2966 return -ENOMEM;
2967 }
2968
2969 /*
2970 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2971 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2972 * revision_id reported by MSR_IA32_VMX_BASIC.
2973 *
2974 * However, even though not explicitly documented by
2975 * TLFS, VMXArea passed as VMXON argument should
2976 * still be marked with revision_id reported by
2977 * physical CPU.
2978 */
2979 if (kvm_is_using_evmcs())
2980 vmcs->hdr.revision_id = vmcs_config.revision_id;
2981
2982 per_cpu(vmxarea, cpu) = vmcs;
2983 }
2984 return 0;
2985 }
2986
fix_pmode_seg(struct kvm_vcpu * vcpu,int seg,struct kvm_segment * save)2987 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2988 struct kvm_segment *save)
2989 {
2990 if (!emulate_invalid_guest_state) {
2991 /*
2992 * CS and SS RPL should be equal during guest entry according
2993 * to VMX spec, but in reality it is not always so. Since vcpu
2994 * is in the middle of the transition from real mode to
2995 * protected mode it is safe to assume that RPL 0 is a good
2996 * default value.
2997 */
2998 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2999 save->selector &= ~SEGMENT_RPL_MASK;
3000 save->dpl = save->selector & SEGMENT_RPL_MASK;
3001 save->s = 1;
3002 }
3003 __vmx_set_segment(vcpu, save, seg);
3004 }
3005
enter_pmode(struct kvm_vcpu * vcpu)3006 static void enter_pmode(struct kvm_vcpu *vcpu)
3007 {
3008 unsigned long flags;
3009 struct vcpu_vmx *vmx = to_vmx(vcpu);
3010
3011 /*
3012 * Update real mode segment cache. It may be not up-to-date if segment
3013 * register was written while vcpu was in a guest mode.
3014 */
3015 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3016 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3017 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3018 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3019 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3020 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3021
3022 vmx->rmode.vm86_active = 0;
3023
3024 __vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3025
3026 flags = vmcs_readl(GUEST_RFLAGS);
3027 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3028 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3029 vmcs_writel(GUEST_RFLAGS, flags);
3030
3031 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
3032 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
3033
3034 vmx_update_exception_bitmap(vcpu);
3035
3036 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3037 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3038 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3039 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3040 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3041 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3042 }
3043
fix_rmode_seg(int seg,struct kvm_segment * save)3044 static void fix_rmode_seg(int seg, struct kvm_segment *save)
3045 {
3046 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3047 struct kvm_segment var = *save;
3048
3049 var.dpl = 0x3;
3050 if (seg == VCPU_SREG_CS)
3051 var.type = 0x3;
3052
3053 if (!emulate_invalid_guest_state) {
3054 var.selector = var.base >> 4;
3055 var.base = var.base & 0xffff0;
3056 var.limit = 0xffff;
3057 var.g = 0;
3058 var.db = 0;
3059 var.present = 1;
3060 var.s = 1;
3061 var.l = 0;
3062 var.unusable = 0;
3063 var.type = 0x3;
3064 var.avl = 0;
3065 if (save->base & 0xf)
3066 pr_warn_once("segment base is not paragraph aligned "
3067 "when entering protected mode (seg=%d)", seg);
3068 }
3069
3070 vmcs_write16(sf->selector, var.selector);
3071 vmcs_writel(sf->base, var.base);
3072 vmcs_write32(sf->limit, var.limit);
3073 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
3074 }
3075
enter_rmode(struct kvm_vcpu * vcpu)3076 static void enter_rmode(struct kvm_vcpu *vcpu)
3077 {
3078 unsigned long flags;
3079 struct vcpu_vmx *vmx = to_vmx(vcpu);
3080 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
3081
3082 /*
3083 * KVM should never use VM86 to virtualize Real Mode when L2 is active,
3084 * as using VM86 is unnecessary if unrestricted guest is enabled, and
3085 * if unrestricted guest is disabled, VM-Enter (from L1) with CR0.PG=0
3086 * should VM-Fail and KVM should reject userspace attempts to stuff
3087 * CR0.PG=0 when L2 is active.
3088 */
3089 WARN_ON_ONCE(is_guest_mode(vcpu));
3090
3091 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3092 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3093 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3094 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3095 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3096 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3097 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3098
3099 vmx->rmode.vm86_active = 1;
3100
3101 vmx_segment_cache_clear(vmx);
3102
3103 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
3104 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
3105 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
3106
3107 flags = vmcs_readl(GUEST_RFLAGS);
3108 vmx->rmode.save_rflags = flags;
3109
3110 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3111
3112 vmcs_writel(GUEST_RFLAGS, flags);
3113 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
3114 vmx_update_exception_bitmap(vcpu);
3115
3116 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3117 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3118 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3119 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3120 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3121 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3122 }
3123
vmx_set_efer(struct kvm_vcpu * vcpu,u64 efer)3124 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
3125 {
3126 struct vcpu_vmx *vmx = to_vmx(vcpu);
3127
3128 /* Nothing to do if hardware doesn't support EFER. */
3129 if (!vmx_find_uret_msr(vmx, MSR_EFER))
3130 return 0;
3131
3132 vcpu->arch.efer = efer;
3133 #ifdef CONFIG_X86_64
3134 if (efer & EFER_LMA)
3135 vm_entry_controls_setbit(vmx, VM_ENTRY_IA32E_MODE);
3136 else
3137 vm_entry_controls_clearbit(vmx, VM_ENTRY_IA32E_MODE);
3138 #else
3139 if (KVM_BUG_ON(efer & EFER_LMA, vcpu->kvm))
3140 return 1;
3141 #endif
3142
3143 vmx_setup_uret_msrs(vmx);
3144 return 0;
3145 }
3146
3147 #ifdef CONFIG_X86_64
3148
enter_lmode(struct kvm_vcpu * vcpu)3149 static void enter_lmode(struct kvm_vcpu *vcpu)
3150 {
3151 u32 guest_tr_ar;
3152
3153 vmx_segment_cache_clear(to_vmx(vcpu));
3154
3155 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3156 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
3157 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3158 __func__);
3159 vmcs_write32(GUEST_TR_AR_BYTES,
3160 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
3161 | VMX_AR_TYPE_BUSY_64_TSS);
3162 }
3163 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3164 }
3165
exit_lmode(struct kvm_vcpu * vcpu)3166 static void exit_lmode(struct kvm_vcpu *vcpu)
3167 {
3168 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3169 }
3170
3171 #endif
3172
vmx_flush_tlb_all(struct kvm_vcpu * vcpu)3173 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
3174 {
3175 struct vcpu_vmx *vmx = to_vmx(vcpu);
3176
3177 /*
3178 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
3179 * the CPU is not required to invalidate guest-physical mappings on
3180 * VM-Entry, even if VPID is disabled. Guest-physical mappings are
3181 * associated with the root EPT structure and not any particular VPID
3182 * (INVVPID also isn't required to invalidate guest-physical mappings).
3183 */
3184 if (enable_ept) {
3185 ept_sync_global();
3186 } else if (enable_vpid) {
3187 if (cpu_has_vmx_invvpid_global()) {
3188 vpid_sync_vcpu_global();
3189 } else {
3190 vpid_sync_vcpu_single(vmx->vpid);
3191 vpid_sync_vcpu_single(vmx->nested.vpid02);
3192 }
3193 }
3194 }
3195
vmx_get_current_vpid(struct kvm_vcpu * vcpu)3196 static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu)
3197 {
3198 if (is_guest_mode(vcpu) && nested_cpu_has_vpid(get_vmcs12(vcpu)))
3199 return nested_get_vpid02(vcpu);
3200 return to_vmx(vcpu)->vpid;
3201 }
3202
vmx_flush_tlb_current(struct kvm_vcpu * vcpu)3203 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
3204 {
3205 struct kvm_mmu *mmu = vcpu->arch.mmu;
3206 u64 root_hpa = mmu->root.hpa;
3207
3208 /* No flush required if the current context is invalid. */
3209 if (!VALID_PAGE(root_hpa))
3210 return;
3211
3212 if (enable_ept)
3213 ept_sync_context(construct_eptp(vcpu, root_hpa,
3214 mmu->root_role.level));
3215 else
3216 vpid_sync_context(vmx_get_current_vpid(vcpu));
3217 }
3218
vmx_flush_tlb_gva(struct kvm_vcpu * vcpu,gva_t addr)3219 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3220 {
3221 /*
3222 * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in
3223 * vmx_flush_tlb_guest() for an explanation of why this is ok.
3224 */
3225 vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
3226 }
3227
vmx_flush_tlb_guest(struct kvm_vcpu * vcpu)3228 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3229 {
3230 /*
3231 * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
3232 * vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit are
3233 * required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3234 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3235 * i.e. no explicit INVVPID is necessary.
3236 */
3237 vpid_sync_context(vmx_get_current_vpid(vcpu));
3238 }
3239
vmx_ept_load_pdptrs(struct kvm_vcpu * vcpu)3240 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3241 {
3242 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3243
3244 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3245 return;
3246
3247 if (is_pae_paging(vcpu)) {
3248 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3249 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3250 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3251 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3252 }
3253 }
3254
ept_save_pdptrs(struct kvm_vcpu * vcpu)3255 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3256 {
3257 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3258
3259 if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3260 return;
3261
3262 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3263 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3264 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3265 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3266
3267 kvm_register_mark_available(vcpu, VCPU_EXREG_PDPTR);
3268 }
3269
3270 #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \
3271 CPU_BASED_CR3_STORE_EXITING)
3272
vmx_is_valid_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)3273 static bool vmx_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3274 {
3275 if (is_guest_mode(vcpu))
3276 return nested_guest_cr0_valid(vcpu, cr0);
3277
3278 if (to_vmx(vcpu)->nested.vmxon)
3279 return nested_host_cr0_valid(vcpu, cr0);
3280
3281 return true;
3282 }
3283
vmx_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)3284 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3285 {
3286 struct vcpu_vmx *vmx = to_vmx(vcpu);
3287 unsigned long hw_cr0, old_cr0_pg;
3288 u32 tmp;
3289
3290 old_cr0_pg = kvm_read_cr0_bits(vcpu, X86_CR0_PG);
3291
3292 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3293 if (enable_unrestricted_guest)
3294 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3295 else {
3296 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3297 if (!enable_ept)
3298 hw_cr0 |= X86_CR0_WP;
3299
3300 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3301 enter_pmode(vcpu);
3302
3303 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3304 enter_rmode(vcpu);
3305 }
3306
3307 vmcs_writel(CR0_READ_SHADOW, cr0);
3308 vmcs_writel(GUEST_CR0, hw_cr0);
3309 vcpu->arch.cr0 = cr0;
3310 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3311
3312 #ifdef CONFIG_X86_64
3313 if (vcpu->arch.efer & EFER_LME) {
3314 if (!old_cr0_pg && (cr0 & X86_CR0_PG))
3315 enter_lmode(vcpu);
3316 else if (old_cr0_pg && !(cr0 & X86_CR0_PG))
3317 exit_lmode(vcpu);
3318 }
3319 #endif
3320
3321 if (enable_ept && !enable_unrestricted_guest) {
3322 /*
3323 * Ensure KVM has an up-to-date snapshot of the guest's CR3. If
3324 * the below code _enables_ CR3 exiting, vmx_cache_reg() will
3325 * (correctly) stop reading vmcs.GUEST_CR3 because it thinks
3326 * KVM's CR3 is installed.
3327 */
3328 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3329 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3330
3331 /*
3332 * When running with EPT but not unrestricted guest, KVM must
3333 * intercept CR3 accesses when paging is _disabled_. This is
3334 * necessary because restricted guests can't actually run with
3335 * paging disabled, and so KVM stuffs its own CR3 in order to
3336 * run the guest when identity mapped page tables.
3337 *
3338 * Do _NOT_ check the old CR0.PG, e.g. to optimize away the
3339 * update, it may be stale with respect to CR3 interception,
3340 * e.g. after nested VM-Enter.
3341 *
3342 * Lastly, honor L1's desires, i.e. intercept CR3 loads and/or
3343 * stores to forward them to L1, even if KVM does not need to
3344 * intercept them to preserve its identity mapped page tables.
3345 */
3346 if (!(cr0 & X86_CR0_PG)) {
3347 exec_controls_setbit(vmx, CR3_EXITING_BITS);
3348 } else if (!is_guest_mode(vcpu)) {
3349 exec_controls_clearbit(vmx, CR3_EXITING_BITS);
3350 } else {
3351 tmp = exec_controls_get(vmx);
3352 tmp &= ~CR3_EXITING_BITS;
3353 tmp |= get_vmcs12(vcpu)->cpu_based_vm_exec_control & CR3_EXITING_BITS;
3354 exec_controls_set(vmx, tmp);
3355 }
3356
3357 /* Note, vmx_set_cr4() consumes the new vcpu->arch.cr0. */
3358 if ((old_cr0_pg ^ cr0) & X86_CR0_PG)
3359 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3360
3361 /*
3362 * When !CR0_PG -> CR0_PG, vcpu->arch.cr3 becomes active, but
3363 * GUEST_CR3 is still vmx->ept_identity_map_addr if EPT + !URG.
3364 */
3365 if (!(old_cr0_pg & X86_CR0_PG) && (cr0 & X86_CR0_PG))
3366 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
3367 }
3368
3369 /* depends on vcpu->arch.cr0 to be set to a new value */
3370 vmx->emulation_required = vmx_emulation_required(vcpu);
3371 }
3372
vmx_get_max_ept_level(void)3373 static int vmx_get_max_ept_level(void)
3374 {
3375 if (cpu_has_vmx_ept_5levels())
3376 return 5;
3377 return 4;
3378 }
3379
construct_eptp(struct kvm_vcpu * vcpu,hpa_t root_hpa,int root_level)3380 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3381 {
3382 u64 eptp = VMX_EPTP_MT_WB;
3383
3384 eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3385
3386 if (enable_ept_ad_bits &&
3387 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3388 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3389 eptp |= root_hpa;
3390
3391 return eptp;
3392 }
3393
vmx_load_mmu_pgd(struct kvm_vcpu * vcpu,hpa_t root_hpa,int root_level)3394 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3395 int root_level)
3396 {
3397 struct kvm *kvm = vcpu->kvm;
3398 bool update_guest_cr3 = true;
3399 unsigned long guest_cr3;
3400 u64 eptp;
3401
3402 if (enable_ept) {
3403 eptp = construct_eptp(vcpu, root_hpa, root_level);
3404 vmcs_write64(EPT_POINTER, eptp);
3405
3406 hv_track_root_tdp(vcpu, root_hpa);
3407
3408 if (!enable_unrestricted_guest && !is_paging(vcpu))
3409 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3410 else if (kvm_register_is_dirty(vcpu, VCPU_EXREG_CR3))
3411 guest_cr3 = vcpu->arch.cr3;
3412 else /* vmcs.GUEST_CR3 is already up-to-date. */
3413 update_guest_cr3 = false;
3414 vmx_ept_load_pdptrs(vcpu);
3415 } else {
3416 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3417 }
3418
3419 if (update_guest_cr3)
3420 vmcs_writel(GUEST_CR3, guest_cr3);
3421 }
3422
3423
vmx_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)3424 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3425 {
3426 /*
3427 * We operate under the default treatment of SMM, so VMX cannot be
3428 * enabled under SMM. Note, whether or not VMXE is allowed at all,
3429 * i.e. is a reserved bit, is handled by common x86 code.
3430 */
3431 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3432 return false;
3433
3434 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3435 return false;
3436
3437 return true;
3438 }
3439
vmx_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)3440 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3441 {
3442 unsigned long old_cr4 = kvm_read_cr4(vcpu);
3443 struct vcpu_vmx *vmx = to_vmx(vcpu);
3444 unsigned long hw_cr4;
3445
3446 /*
3447 * Pass through host's Machine Check Enable value to hw_cr4, which
3448 * is in force while we are in guest mode. Do not let guests control
3449 * this bit, even if host CR4.MCE == 0.
3450 */
3451 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3452 if (enable_unrestricted_guest)
3453 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3454 else if (vmx->rmode.vm86_active)
3455 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3456 else
3457 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3458
3459 if (vmx_umip_emulated()) {
3460 if (cr4 & X86_CR4_UMIP) {
3461 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3462 hw_cr4 &= ~X86_CR4_UMIP;
3463 } else if (!is_guest_mode(vcpu) ||
3464 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3465 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3466 }
3467 }
3468
3469 vcpu->arch.cr4 = cr4;
3470 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3471
3472 if (!enable_unrestricted_guest) {
3473 if (enable_ept) {
3474 if (!is_paging(vcpu)) {
3475 hw_cr4 &= ~X86_CR4_PAE;
3476 hw_cr4 |= X86_CR4_PSE;
3477 } else if (!(cr4 & X86_CR4_PAE)) {
3478 hw_cr4 &= ~X86_CR4_PAE;
3479 }
3480 }
3481
3482 /*
3483 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3484 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
3485 * to be manually disabled when guest switches to non-paging
3486 * mode.
3487 *
3488 * If !enable_unrestricted_guest, the CPU is always running
3489 * with CR0.PG=1 and CR4 needs to be modified.
3490 * If enable_unrestricted_guest, the CPU automatically
3491 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3492 */
3493 if (!is_paging(vcpu))
3494 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3495 }
3496
3497 vmcs_writel(CR4_READ_SHADOW, cr4);
3498 vmcs_writel(GUEST_CR4, hw_cr4);
3499
3500 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3501 kvm_update_cpuid_runtime(vcpu);
3502 }
3503
vmx_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)3504 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3505 {
3506 struct vcpu_vmx *vmx = to_vmx(vcpu);
3507 u32 ar;
3508
3509 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3510 *var = vmx->rmode.segs[seg];
3511 if (seg == VCPU_SREG_TR
3512 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3513 return;
3514 var->base = vmx_read_guest_seg_base(vmx, seg);
3515 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3516 return;
3517 }
3518 var->base = vmx_read_guest_seg_base(vmx, seg);
3519 var->limit = vmx_read_guest_seg_limit(vmx, seg);
3520 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3521 ar = vmx_read_guest_seg_ar(vmx, seg);
3522 var->unusable = (ar >> 16) & 1;
3523 var->type = ar & 15;
3524 var->s = (ar >> 4) & 1;
3525 var->dpl = (ar >> 5) & 3;
3526 /*
3527 * Some userspaces do not preserve unusable property. Since usable
3528 * segment has to be present according to VMX spec we can use present
3529 * property to amend userspace bug by making unusable segment always
3530 * nonpresent. vmx_segment_access_rights() already marks nonpresent
3531 * segment as unusable.
3532 */
3533 var->present = !var->unusable;
3534 var->avl = (ar >> 12) & 1;
3535 var->l = (ar >> 13) & 1;
3536 var->db = (ar >> 14) & 1;
3537 var->g = (ar >> 15) & 1;
3538 }
3539
vmx_get_segment_base(struct kvm_vcpu * vcpu,int seg)3540 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3541 {
3542 struct kvm_segment s;
3543
3544 if (to_vmx(vcpu)->rmode.vm86_active) {
3545 vmx_get_segment(vcpu, &s, seg);
3546 return s.base;
3547 }
3548 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3549 }
3550
vmx_get_cpl(struct kvm_vcpu * vcpu)3551 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3552 {
3553 struct vcpu_vmx *vmx = to_vmx(vcpu);
3554
3555 if (unlikely(vmx->rmode.vm86_active))
3556 return 0;
3557 else {
3558 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3559 return VMX_AR_DPL(ar);
3560 }
3561 }
3562
vmx_segment_access_rights(struct kvm_segment * var)3563 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3564 {
3565 u32 ar;
3566
3567 ar = var->type & 15;
3568 ar |= (var->s & 1) << 4;
3569 ar |= (var->dpl & 3) << 5;
3570 ar |= (var->present & 1) << 7;
3571 ar |= (var->avl & 1) << 12;
3572 ar |= (var->l & 1) << 13;
3573 ar |= (var->db & 1) << 14;
3574 ar |= (var->g & 1) << 15;
3575 ar |= (var->unusable || !var->present) << 16;
3576
3577 return ar;
3578 }
3579
__vmx_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)3580 void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3581 {
3582 struct vcpu_vmx *vmx = to_vmx(vcpu);
3583 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3584
3585 vmx_segment_cache_clear(vmx);
3586
3587 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3588 vmx->rmode.segs[seg] = *var;
3589 if (seg == VCPU_SREG_TR)
3590 vmcs_write16(sf->selector, var->selector);
3591 else if (var->s)
3592 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3593 return;
3594 }
3595
3596 vmcs_writel(sf->base, var->base);
3597 vmcs_write32(sf->limit, var->limit);
3598 vmcs_write16(sf->selector, var->selector);
3599
3600 /*
3601 * Fix the "Accessed" bit in AR field of segment registers for older
3602 * qemu binaries.
3603 * IA32 arch specifies that at the time of processor reset the
3604 * "Accessed" bit in the AR field of segment registers is 1. And qemu
3605 * is setting it to 0 in the userland code. This causes invalid guest
3606 * state vmexit when "unrestricted guest" mode is turned on.
3607 * Fix for this setup issue in cpu_reset is being pushed in the qemu
3608 * tree. Newer qemu binaries with that qemu fix would not need this
3609 * kvm hack.
3610 */
3611 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3612 var->type |= 0x1; /* Accessed */
3613
3614 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3615 }
3616
vmx_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)3617 static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3618 {
3619 __vmx_set_segment(vcpu, var, seg);
3620
3621 to_vmx(vcpu)->emulation_required = vmx_emulation_required(vcpu);
3622 }
3623
vmx_get_cs_db_l_bits(struct kvm_vcpu * vcpu,int * db,int * l)3624 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3625 {
3626 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3627
3628 *db = (ar >> 14) & 1;
3629 *l = (ar >> 13) & 1;
3630 }
3631
vmx_get_idt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)3632 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3633 {
3634 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3635 dt->address = vmcs_readl(GUEST_IDTR_BASE);
3636 }
3637
vmx_set_idt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)3638 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3639 {
3640 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3641 vmcs_writel(GUEST_IDTR_BASE, dt->address);
3642 }
3643
vmx_get_gdt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)3644 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3645 {
3646 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3647 dt->address = vmcs_readl(GUEST_GDTR_BASE);
3648 }
3649
vmx_set_gdt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)3650 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3651 {
3652 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3653 vmcs_writel(GUEST_GDTR_BASE, dt->address);
3654 }
3655
rmode_segment_valid(struct kvm_vcpu * vcpu,int seg)3656 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3657 {
3658 struct kvm_segment var;
3659 u32 ar;
3660
3661 vmx_get_segment(vcpu, &var, seg);
3662 var.dpl = 0x3;
3663 if (seg == VCPU_SREG_CS)
3664 var.type = 0x3;
3665 ar = vmx_segment_access_rights(&var);
3666
3667 if (var.base != (var.selector << 4))
3668 return false;
3669 if (var.limit != 0xffff)
3670 return false;
3671 if (ar != 0xf3)
3672 return false;
3673
3674 return true;
3675 }
3676
code_segment_valid(struct kvm_vcpu * vcpu)3677 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3678 {
3679 struct kvm_segment cs;
3680 unsigned int cs_rpl;
3681
3682 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3683 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3684
3685 if (cs.unusable)
3686 return false;
3687 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3688 return false;
3689 if (!cs.s)
3690 return false;
3691 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3692 if (cs.dpl > cs_rpl)
3693 return false;
3694 } else {
3695 if (cs.dpl != cs_rpl)
3696 return false;
3697 }
3698 if (!cs.present)
3699 return false;
3700
3701 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3702 return true;
3703 }
3704
stack_segment_valid(struct kvm_vcpu * vcpu)3705 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3706 {
3707 struct kvm_segment ss;
3708 unsigned int ss_rpl;
3709
3710 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3711 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3712
3713 if (ss.unusable)
3714 return true;
3715 if (ss.type != 3 && ss.type != 7)
3716 return false;
3717 if (!ss.s)
3718 return false;
3719 if (ss.dpl != ss_rpl) /* DPL != RPL */
3720 return false;
3721 if (!ss.present)
3722 return false;
3723
3724 return true;
3725 }
3726
data_segment_valid(struct kvm_vcpu * vcpu,int seg)3727 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3728 {
3729 struct kvm_segment var;
3730 unsigned int rpl;
3731
3732 vmx_get_segment(vcpu, &var, seg);
3733 rpl = var.selector & SEGMENT_RPL_MASK;
3734
3735 if (var.unusable)
3736 return true;
3737 if (!var.s)
3738 return false;
3739 if (!var.present)
3740 return false;
3741 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3742 if (var.dpl < rpl) /* DPL < RPL */
3743 return false;
3744 }
3745
3746 /* TODO: Add other members to kvm_segment_field to allow checking for other access
3747 * rights flags
3748 */
3749 return true;
3750 }
3751
tr_valid(struct kvm_vcpu * vcpu)3752 static bool tr_valid(struct kvm_vcpu *vcpu)
3753 {
3754 struct kvm_segment tr;
3755
3756 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3757
3758 if (tr.unusable)
3759 return false;
3760 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3761 return false;
3762 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3763 return false;
3764 if (!tr.present)
3765 return false;
3766
3767 return true;
3768 }
3769
ldtr_valid(struct kvm_vcpu * vcpu)3770 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3771 {
3772 struct kvm_segment ldtr;
3773
3774 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3775
3776 if (ldtr.unusable)
3777 return true;
3778 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
3779 return false;
3780 if (ldtr.type != 2)
3781 return false;
3782 if (!ldtr.present)
3783 return false;
3784
3785 return true;
3786 }
3787
cs_ss_rpl_check(struct kvm_vcpu * vcpu)3788 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3789 {
3790 struct kvm_segment cs, ss;
3791
3792 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3793 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3794
3795 return ((cs.selector & SEGMENT_RPL_MASK) ==
3796 (ss.selector & SEGMENT_RPL_MASK));
3797 }
3798
3799 /*
3800 * Check if guest state is valid. Returns true if valid, false if
3801 * not.
3802 * We assume that registers are always usable
3803 */
__vmx_guest_state_valid(struct kvm_vcpu * vcpu)3804 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3805 {
3806 /* real mode guest state checks */
3807 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3808 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3809 return false;
3810 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3811 return false;
3812 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3813 return false;
3814 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3815 return false;
3816 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3817 return false;
3818 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3819 return false;
3820 } else {
3821 /* protected mode guest state checks */
3822 if (!cs_ss_rpl_check(vcpu))
3823 return false;
3824 if (!code_segment_valid(vcpu))
3825 return false;
3826 if (!stack_segment_valid(vcpu))
3827 return false;
3828 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3829 return false;
3830 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3831 return false;
3832 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3833 return false;
3834 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3835 return false;
3836 if (!tr_valid(vcpu))
3837 return false;
3838 if (!ldtr_valid(vcpu))
3839 return false;
3840 }
3841 /* TODO:
3842 * - Add checks on RIP
3843 * - Add checks on RFLAGS
3844 */
3845
3846 return true;
3847 }
3848
init_rmode_tss(struct kvm * kvm,void __user * ua)3849 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3850 {
3851 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3852 u16 data;
3853 int i;
3854
3855 for (i = 0; i < 3; i++) {
3856 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3857 return -EFAULT;
3858 }
3859
3860 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3861 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3862 return -EFAULT;
3863
3864 data = ~0;
3865 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3866 return -EFAULT;
3867
3868 return 0;
3869 }
3870
init_rmode_identity_map(struct kvm * kvm)3871 static int init_rmode_identity_map(struct kvm *kvm)
3872 {
3873 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3874 int i, r = 0;
3875 void __user *uaddr;
3876 u32 tmp;
3877
3878 /* Protect kvm_vmx->ept_identity_pagetable_done. */
3879 mutex_lock(&kvm->slots_lock);
3880
3881 if (likely(kvm_vmx->ept_identity_pagetable_done))
3882 goto out;
3883
3884 if (!kvm_vmx->ept_identity_map_addr)
3885 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3886
3887 uaddr = __x86_set_memory_region(kvm,
3888 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3889 kvm_vmx->ept_identity_map_addr,
3890 PAGE_SIZE);
3891 if (IS_ERR(uaddr)) {
3892 r = PTR_ERR(uaddr);
3893 goto out;
3894 }
3895
3896 /* Set up identity-mapping pagetable for EPT in real mode */
3897 for (i = 0; i < (PAGE_SIZE / sizeof(tmp)); i++) {
3898 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3899 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3900 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3901 r = -EFAULT;
3902 goto out;
3903 }
3904 }
3905 kvm_vmx->ept_identity_pagetable_done = true;
3906
3907 out:
3908 mutex_unlock(&kvm->slots_lock);
3909 return r;
3910 }
3911
seg_setup(int seg)3912 static void seg_setup(int seg)
3913 {
3914 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3915 unsigned int ar;
3916
3917 vmcs_write16(sf->selector, 0);
3918 vmcs_writel(sf->base, 0);
3919 vmcs_write32(sf->limit, 0xffff);
3920 ar = 0x93;
3921 if (seg == VCPU_SREG_CS)
3922 ar |= 0x08; /* code segment */
3923
3924 vmcs_write32(sf->ar_bytes, ar);
3925 }
3926
allocate_vpid(void)3927 int allocate_vpid(void)
3928 {
3929 int vpid;
3930
3931 if (!enable_vpid)
3932 return 0;
3933 spin_lock(&vmx_vpid_lock);
3934 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3935 if (vpid < VMX_NR_VPIDS)
3936 __set_bit(vpid, vmx_vpid_bitmap);
3937 else
3938 vpid = 0;
3939 spin_unlock(&vmx_vpid_lock);
3940 return vpid;
3941 }
3942
free_vpid(int vpid)3943 void free_vpid(int vpid)
3944 {
3945 if (!enable_vpid || vpid == 0)
3946 return;
3947 spin_lock(&vmx_vpid_lock);
3948 __clear_bit(vpid, vmx_vpid_bitmap);
3949 spin_unlock(&vmx_vpid_lock);
3950 }
3951
vmx_msr_bitmap_l01_changed(struct vcpu_vmx * vmx)3952 static void vmx_msr_bitmap_l01_changed(struct vcpu_vmx *vmx)
3953 {
3954 /*
3955 * When KVM is a nested hypervisor on top of Hyper-V and uses
3956 * 'Enlightened MSR Bitmap' feature L0 needs to know that MSR
3957 * bitmap has changed.
3958 */
3959 if (kvm_is_using_evmcs()) {
3960 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
3961
3962 if (evmcs->hv_enlightenments_control.msr_bitmap)
3963 evmcs->hv_clean_fields &=
3964 ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
3965 }
3966
3967 vmx->nested.force_msr_bitmap_recalc = true;
3968 }
3969
vmx_disable_intercept_for_msr(struct kvm_vcpu * vcpu,u32 msr,int type)3970 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3971 {
3972 struct vcpu_vmx *vmx = to_vmx(vcpu);
3973 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3974
3975 if (!cpu_has_vmx_msr_bitmap())
3976 return;
3977
3978 vmx_msr_bitmap_l01_changed(vmx);
3979
3980 /*
3981 * Mark the desired intercept state in shadow bitmap, this is needed
3982 * for resync when the MSR filters change.
3983 */
3984 if (is_valid_passthrough_msr(msr)) {
3985 int idx = possible_passthrough_msr_slot(msr);
3986
3987 if (idx != -ENOENT) {
3988 if (type & MSR_TYPE_R)
3989 clear_bit(idx, vmx->shadow_msr_intercept.read);
3990 if (type & MSR_TYPE_W)
3991 clear_bit(idx, vmx->shadow_msr_intercept.write);
3992 }
3993 }
3994
3995 if ((type & MSR_TYPE_R) &&
3996 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3997 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3998 type &= ~MSR_TYPE_R;
3999 }
4000
4001 if ((type & MSR_TYPE_W) &&
4002 !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
4003 vmx_set_msr_bitmap_write(msr_bitmap, msr);
4004 type &= ~MSR_TYPE_W;
4005 }
4006
4007 if (type & MSR_TYPE_R)
4008 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
4009
4010 if (type & MSR_TYPE_W)
4011 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
4012 }
4013
vmx_enable_intercept_for_msr(struct kvm_vcpu * vcpu,u32 msr,int type)4014 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
4015 {
4016 struct vcpu_vmx *vmx = to_vmx(vcpu);
4017 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
4018
4019 if (!cpu_has_vmx_msr_bitmap())
4020 return;
4021
4022 vmx_msr_bitmap_l01_changed(vmx);
4023
4024 /*
4025 * Mark the desired intercept state in shadow bitmap, this is needed
4026 * for resync when the MSR filter changes.
4027 */
4028 if (is_valid_passthrough_msr(msr)) {
4029 int idx = possible_passthrough_msr_slot(msr);
4030
4031 if (idx != -ENOENT) {
4032 if (type & MSR_TYPE_R)
4033 set_bit(idx, vmx->shadow_msr_intercept.read);
4034 if (type & MSR_TYPE_W)
4035 set_bit(idx, vmx->shadow_msr_intercept.write);
4036 }
4037 }
4038
4039 if (type & MSR_TYPE_R)
4040 vmx_set_msr_bitmap_read(msr_bitmap, msr);
4041
4042 if (type & MSR_TYPE_W)
4043 vmx_set_msr_bitmap_write(msr_bitmap, msr);
4044 }
4045
vmx_update_msr_bitmap_x2apic(struct kvm_vcpu * vcpu)4046 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu)
4047 {
4048 /*
4049 * x2APIC indices for 64-bit accesses into the RDMSR and WRMSR halves
4050 * of the MSR bitmap. KVM emulates APIC registers up through 0x3f0,
4051 * i.e. MSR 0x83f, and so only needs to dynamically manipulate 64 bits.
4052 */
4053 const int read_idx = APIC_BASE_MSR / BITS_PER_LONG_LONG;
4054 const int write_idx = read_idx + (0x800 / sizeof(u64));
4055 struct vcpu_vmx *vmx = to_vmx(vcpu);
4056 u64 *msr_bitmap = (u64 *)vmx->vmcs01.msr_bitmap;
4057 u8 mode;
4058
4059 if (!cpu_has_vmx_msr_bitmap() || WARN_ON_ONCE(!lapic_in_kernel(vcpu)))
4060 return;
4061
4062 if (cpu_has_secondary_exec_ctrls() &&
4063 (secondary_exec_controls_get(vmx) &
4064 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
4065 mode = MSR_BITMAP_MODE_X2APIC;
4066 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
4067 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
4068 } else {
4069 mode = 0;
4070 }
4071
4072 if (mode == vmx->x2apic_msr_bitmap_mode)
4073 return;
4074
4075 vmx->x2apic_msr_bitmap_mode = mode;
4076
4077 /*
4078 * Reset the bitmap for MSRs 0x800 - 0x83f. Leave AMD's uber-extended
4079 * registers (0x840 and above) intercepted, KVM doesn't support them.
4080 * Intercept all writes by default and poke holes as needed. Pass
4081 * through reads for all valid registers by default in x2APIC+APICv
4082 * mode, only the current timer count needs on-demand emulation by KVM.
4083 */
4084 if (mode & MSR_BITMAP_MODE_X2APIC_APICV)
4085 msr_bitmap[read_idx] = ~kvm_lapic_readable_reg_mask(vcpu->arch.apic);
4086 else
4087 msr_bitmap[read_idx] = ~0ull;
4088 msr_bitmap[write_idx] = ~0ull;
4089
4090 /*
4091 * TPR reads and writes can be virtualized even if virtual interrupt
4092 * delivery is not in use.
4093 */
4094 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
4095 !(mode & MSR_BITMAP_MODE_X2APIC));
4096
4097 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
4098 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
4099 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
4100 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
4101 if (enable_ipiv)
4102 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_ICR), MSR_TYPE_RW);
4103 }
4104 }
4105
pt_update_intercept_for_msr(struct kvm_vcpu * vcpu)4106 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
4107 {
4108 struct vcpu_vmx *vmx = to_vmx(vcpu);
4109 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
4110 u32 i;
4111
4112 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
4113 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
4114 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
4115 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
4116 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++) {
4117 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
4118 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
4119 }
4120 }
4121
vmx_guest_apic_has_interrupt(struct kvm_vcpu * vcpu)4122 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
4123 {
4124 struct vcpu_vmx *vmx = to_vmx(vcpu);
4125 void *vapic_page;
4126 u32 vppr;
4127 int rvi;
4128
4129 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
4130 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
4131 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
4132 return false;
4133
4134 rvi = vmx_get_rvi();
4135
4136 vapic_page = vmx->nested.virtual_apic_map.hva;
4137 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
4138
4139 return ((rvi & 0xf0) > (vppr & 0xf0));
4140 }
4141
vmx_msr_filter_changed(struct kvm_vcpu * vcpu)4142 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
4143 {
4144 struct vcpu_vmx *vmx = to_vmx(vcpu);
4145 u32 i;
4146
4147 /*
4148 * Redo intercept permissions for MSRs that KVM is passing through to
4149 * the guest. Disabling interception will check the new MSR filter and
4150 * ensure that KVM enables interception if usersepace wants to filter
4151 * the MSR. MSRs that KVM is already intercepting don't need to be
4152 * refreshed since KVM is going to intercept them regardless of what
4153 * userspace wants.
4154 */
4155 for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
4156 u32 msr = vmx_possible_passthrough_msrs[i];
4157
4158 if (!test_bit(i, vmx->shadow_msr_intercept.read))
4159 vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_R);
4160
4161 if (!test_bit(i, vmx->shadow_msr_intercept.write))
4162 vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_W);
4163 }
4164
4165 /* PT MSRs can be passed through iff PT is exposed to the guest. */
4166 if (vmx_pt_mode_is_host_guest())
4167 pt_update_intercept_for_msr(vcpu);
4168 }
4169
kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu * vcpu,int pi_vec)4170 static inline void kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
4171 int pi_vec)
4172 {
4173 #ifdef CONFIG_SMP
4174 if (vcpu->mode == IN_GUEST_MODE) {
4175 /*
4176 * The vector of the virtual has already been set in the PIR.
4177 * Send a notification event to deliver the virtual interrupt
4178 * unless the vCPU is the currently running vCPU, i.e. the
4179 * event is being sent from a fastpath VM-Exit handler, in
4180 * which case the PIR will be synced to the vIRR before
4181 * re-entering the guest.
4182 *
4183 * When the target is not the running vCPU, the following
4184 * possibilities emerge:
4185 *
4186 * Case 1: vCPU stays in non-root mode. Sending a notification
4187 * event posts the interrupt to the vCPU.
4188 *
4189 * Case 2: vCPU exits to root mode and is still runnable. The
4190 * PIR will be synced to the vIRR before re-entering the guest.
4191 * Sending a notification event is ok as the host IRQ handler
4192 * will ignore the spurious event.
4193 *
4194 * Case 3: vCPU exits to root mode and is blocked. vcpu_block()
4195 * has already synced PIR to vIRR and never blocks the vCPU if
4196 * the vIRR is not empty. Therefore, a blocked vCPU here does
4197 * not wait for any requested interrupts in PIR, and sending a
4198 * notification event also results in a benign, spurious event.
4199 */
4200
4201 if (vcpu != kvm_get_running_vcpu())
4202 __apic_send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
4203 return;
4204 }
4205 #endif
4206 /*
4207 * The vCPU isn't in the guest; wake the vCPU in case it is blocking,
4208 * otherwise do nothing as KVM will grab the highest priority pending
4209 * IRQ via ->sync_pir_to_irr() in vcpu_enter_guest().
4210 */
4211 kvm_vcpu_wake_up(vcpu);
4212 }
4213
vmx_deliver_nested_posted_interrupt(struct kvm_vcpu * vcpu,int vector)4214 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4215 int vector)
4216 {
4217 struct vcpu_vmx *vmx = to_vmx(vcpu);
4218
4219 if (is_guest_mode(vcpu) &&
4220 vector == vmx->nested.posted_intr_nv) {
4221 /*
4222 * If a posted intr is not recognized by hardware,
4223 * we will accomplish it in the next vmentry.
4224 */
4225 vmx->nested.pi_pending = true;
4226 kvm_make_request(KVM_REQ_EVENT, vcpu);
4227
4228 /*
4229 * This pairs with the smp_mb_*() after setting vcpu->mode in
4230 * vcpu_enter_guest() to guarantee the vCPU sees the event
4231 * request if triggering a posted interrupt "fails" because
4232 * vcpu->mode != IN_GUEST_MODE. The extra barrier is needed as
4233 * the smb_wmb() in kvm_make_request() only ensures everything
4234 * done before making the request is visible when the request
4235 * is visible, it doesn't ensure ordering between the store to
4236 * vcpu->requests and the load from vcpu->mode.
4237 */
4238 smp_mb__after_atomic();
4239
4240 /* the PIR and ON have been set by L1. */
4241 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_NESTED_VECTOR);
4242 return 0;
4243 }
4244 return -1;
4245 }
4246 /*
4247 * Send interrupt to vcpu via posted interrupt way.
4248 * 1. If target vcpu is running(non-root mode), send posted interrupt
4249 * notification to vcpu and hardware will sync PIR to vIRR atomically.
4250 * 2. If target vcpu isn't running(root mode), kick it to pick up the
4251 * interrupt from PIR in next vmentry.
4252 */
vmx_deliver_posted_interrupt(struct kvm_vcpu * vcpu,int vector)4253 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4254 {
4255 struct vcpu_vmx *vmx = to_vmx(vcpu);
4256 int r;
4257
4258 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4259 if (!r)
4260 return 0;
4261
4262 /* Note, this is called iff the local APIC is in-kernel. */
4263 if (!vcpu->arch.apic->apicv_active)
4264 return -1;
4265
4266 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4267 return 0;
4268
4269 /* If a previous notification has sent the IPI, nothing to do. */
4270 if (pi_test_and_set_on(&vmx->pi_desc))
4271 return 0;
4272
4273 /*
4274 * The implied barrier in pi_test_and_set_on() pairs with the smp_mb_*()
4275 * after setting vcpu->mode in vcpu_enter_guest(), thus the vCPU is
4276 * guaranteed to see PID.ON=1 and sync the PIR to IRR if triggering a
4277 * posted interrupt "fails" because vcpu->mode != IN_GUEST_MODE.
4278 */
4279 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_VECTOR);
4280 return 0;
4281 }
4282
vmx_deliver_interrupt(struct kvm_lapic * apic,int delivery_mode,int trig_mode,int vector)4283 static void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
4284 int trig_mode, int vector)
4285 {
4286 struct kvm_vcpu *vcpu = apic->vcpu;
4287
4288 if (vmx_deliver_posted_interrupt(vcpu, vector)) {
4289 kvm_lapic_set_irr(vector, apic);
4290 kvm_make_request(KVM_REQ_EVENT, vcpu);
4291 kvm_vcpu_kick(vcpu);
4292 } else {
4293 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode,
4294 trig_mode, vector);
4295 }
4296 }
4297
4298 /*
4299 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4300 * will not change in the lifetime of the guest.
4301 * Note that host-state that does change is set elsewhere. E.g., host-state
4302 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4303 */
vmx_set_constant_host_state(struct vcpu_vmx * vmx)4304 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4305 {
4306 u32 low32, high32;
4307 unsigned long tmpl;
4308 unsigned long cr0, cr3, cr4;
4309
4310 cr0 = read_cr0();
4311 WARN_ON(cr0 & X86_CR0_TS);
4312 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
4313
4314 /*
4315 * Save the most likely value for this task's CR3 in the VMCS.
4316 * We can't use __get_current_cr3_fast() because we're not atomic.
4317 */
4318 cr3 = __read_cr3();
4319 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
4320 vmx->loaded_vmcs->host_state.cr3 = cr3;
4321
4322 /* Save the most likely value for this task's CR4 in the VMCS. */
4323 cr4 = cr4_read_shadow();
4324 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
4325 vmx->loaded_vmcs->host_state.cr4 = cr4;
4326
4327 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
4328 #ifdef CONFIG_X86_64
4329 /*
4330 * Load null selectors, so we can avoid reloading them in
4331 * vmx_prepare_switch_to_host(), in case userspace uses
4332 * the null selectors too (the expected case).
4333 */
4334 vmcs_write16(HOST_DS_SELECTOR, 0);
4335 vmcs_write16(HOST_ES_SELECTOR, 0);
4336 #else
4337 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4338 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4339 #endif
4340 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
4341 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
4342
4343 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */
4344
4345 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4346
4347 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4348 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4349
4350 /*
4351 * SYSENTER is used for 32-bit system calls on either 32-bit or
4352 * 64-bit kernels. It is always zero If neither is allowed, otherwise
4353 * vmx_vcpu_load_vmcs loads it with the per-CPU entry stack (and may
4354 * have already done so!).
4355 */
4356 if (!IS_ENABLED(CONFIG_IA32_EMULATION) && !IS_ENABLED(CONFIG_X86_32))
4357 vmcs_writel(HOST_IA32_SYSENTER_ESP, 0);
4358
4359 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4360 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
4361
4362 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4363 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4364 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4365 }
4366
4367 if (cpu_has_load_ia32_efer())
4368 vmcs_write64(HOST_IA32_EFER, host_efer);
4369 }
4370
set_cr4_guest_host_mask(struct vcpu_vmx * vmx)4371 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4372 {
4373 struct kvm_vcpu *vcpu = &vmx->vcpu;
4374
4375 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4376 ~vcpu->arch.cr4_guest_rsvd_bits;
4377 if (!enable_ept) {
4378 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_TLBFLUSH_BITS;
4379 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PDPTR_BITS;
4380 }
4381 if (is_guest_mode(&vmx->vcpu))
4382 vcpu->arch.cr4_guest_owned_bits &=
4383 ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4384 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4385 }
4386
vmx_pin_based_exec_ctrl(struct vcpu_vmx * vmx)4387 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4388 {
4389 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4390
4391 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4392 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4393
4394 if (!enable_vnmi)
4395 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4396
4397 if (!enable_preemption_timer)
4398 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4399
4400 return pin_based_exec_ctrl;
4401 }
4402
vmx_vmentry_ctrl(void)4403 static u32 vmx_vmentry_ctrl(void)
4404 {
4405 u32 vmentry_ctrl = vmcs_config.vmentry_ctrl;
4406
4407 if (vmx_pt_mode_is_system())
4408 vmentry_ctrl &= ~(VM_ENTRY_PT_CONCEAL_PIP |
4409 VM_ENTRY_LOAD_IA32_RTIT_CTL);
4410 /*
4411 * IA32e mode, and loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically.
4412 */
4413 vmentry_ctrl &= ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
4414 VM_ENTRY_LOAD_IA32_EFER |
4415 VM_ENTRY_IA32E_MODE);
4416
4417 if (cpu_has_perf_global_ctrl_bug())
4418 vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4419
4420 return vmentry_ctrl;
4421 }
4422
vmx_vmexit_ctrl(void)4423 static u32 vmx_vmexit_ctrl(void)
4424 {
4425 u32 vmexit_ctrl = vmcs_config.vmexit_ctrl;
4426
4427 /*
4428 * Not used by KVM and never set in vmcs01 or vmcs02, but emulated for
4429 * nested virtualization and thus allowed to be set in vmcs12.
4430 */
4431 vmexit_ctrl &= ~(VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER |
4432 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER);
4433
4434 if (vmx_pt_mode_is_system())
4435 vmexit_ctrl &= ~(VM_EXIT_PT_CONCEAL_PIP |
4436 VM_EXIT_CLEAR_IA32_RTIT_CTL);
4437
4438 if (cpu_has_perf_global_ctrl_bug())
4439 vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
4440
4441 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
4442 return vmexit_ctrl &
4443 ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
4444 }
4445
vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu * vcpu)4446 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4447 {
4448 struct vcpu_vmx *vmx = to_vmx(vcpu);
4449
4450 if (is_guest_mode(vcpu)) {
4451 vmx->nested.update_vmcs01_apicv_status = true;
4452 return;
4453 }
4454
4455 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4456
4457 if (kvm_vcpu_apicv_active(vcpu)) {
4458 secondary_exec_controls_setbit(vmx,
4459 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4460 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4461 if (enable_ipiv)
4462 tertiary_exec_controls_setbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4463 } else {
4464 secondary_exec_controls_clearbit(vmx,
4465 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4466 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4467 if (enable_ipiv)
4468 tertiary_exec_controls_clearbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4469 }
4470
4471 vmx_update_msr_bitmap_x2apic(vcpu);
4472 }
4473
vmx_exec_control(struct vcpu_vmx * vmx)4474 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4475 {
4476 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4477
4478 /*
4479 * Not used by KVM, but fully supported for nesting, i.e. are allowed in
4480 * vmcs12 and propagated to vmcs02 when set in vmcs12.
4481 */
4482 exec_control &= ~(CPU_BASED_RDTSC_EXITING |
4483 CPU_BASED_USE_IO_BITMAPS |
4484 CPU_BASED_MONITOR_TRAP_FLAG |
4485 CPU_BASED_PAUSE_EXITING);
4486
4487 /* INTR_WINDOW_EXITING and NMI_WINDOW_EXITING are toggled dynamically */
4488 exec_control &= ~(CPU_BASED_INTR_WINDOW_EXITING |
4489 CPU_BASED_NMI_WINDOW_EXITING);
4490
4491 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4492 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4493
4494 if (!cpu_need_tpr_shadow(&vmx->vcpu))
4495 exec_control &= ~CPU_BASED_TPR_SHADOW;
4496
4497 #ifdef CONFIG_X86_64
4498 if (exec_control & CPU_BASED_TPR_SHADOW)
4499 exec_control &= ~(CPU_BASED_CR8_LOAD_EXITING |
4500 CPU_BASED_CR8_STORE_EXITING);
4501 else
4502 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4503 CPU_BASED_CR8_LOAD_EXITING;
4504 #endif
4505 /* No need to intercept CR3 access or INVPLG when using EPT. */
4506 if (enable_ept)
4507 exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4508 CPU_BASED_CR3_STORE_EXITING |
4509 CPU_BASED_INVLPG_EXITING);
4510 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4511 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4512 CPU_BASED_MONITOR_EXITING);
4513 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4514 exec_control &= ~CPU_BASED_HLT_EXITING;
4515 return exec_control;
4516 }
4517
vmx_tertiary_exec_control(struct vcpu_vmx * vmx)4518 static u64 vmx_tertiary_exec_control(struct vcpu_vmx *vmx)
4519 {
4520 u64 exec_control = vmcs_config.cpu_based_3rd_exec_ctrl;
4521
4522 /*
4523 * IPI virtualization relies on APICv. Disable IPI virtualization if
4524 * APICv is inhibited.
4525 */
4526 if (!enable_ipiv || !kvm_vcpu_apicv_active(&vmx->vcpu))
4527 exec_control &= ~TERTIARY_EXEC_IPI_VIRT;
4528
4529 return exec_control;
4530 }
4531
4532 /*
4533 * Adjust a single secondary execution control bit to intercept/allow an
4534 * instruction in the guest. This is usually done based on whether or not a
4535 * feature has been exposed to the guest in order to correctly emulate faults.
4536 */
4537 static inline void
vmx_adjust_secondary_exec_control(struct vcpu_vmx * vmx,u32 * exec_control,u32 control,bool enabled,bool exiting)4538 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4539 u32 control, bool enabled, bool exiting)
4540 {
4541 /*
4542 * If the control is for an opt-in feature, clear the control if the
4543 * feature is not exposed to the guest, i.e. not enabled. If the
4544 * control is opt-out, i.e. an exiting control, clear the control if
4545 * the feature _is_ exposed to the guest, i.e. exiting/interception is
4546 * disabled for the associated instruction. Note, the caller is
4547 * responsible presetting exec_control to set all supported bits.
4548 */
4549 if (enabled == exiting)
4550 *exec_control &= ~control;
4551
4552 /*
4553 * Update the nested MSR settings so that a nested VMM can/can't set
4554 * controls for features that are/aren't exposed to the guest.
4555 */
4556 if (nested) {
4557 /*
4558 * All features that can be added or removed to VMX MSRs must
4559 * be supported in the first place for nested virtualization.
4560 */
4561 if (WARN_ON_ONCE(!(vmcs_config.nested.secondary_ctls_high & control)))
4562 enabled = false;
4563
4564 if (enabled)
4565 vmx->nested.msrs.secondary_ctls_high |= control;
4566 else
4567 vmx->nested.msrs.secondary_ctls_high &= ~control;
4568 }
4569 }
4570
4571 /*
4572 * Wrapper macro for the common case of adjusting a secondary execution control
4573 * based on a single guest CPUID bit, with a dedicated feature bit. This also
4574 * verifies that the control is actually supported by KVM and hardware.
4575 */
4576 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4577 ({ \
4578 struct kvm_vcpu *__vcpu = &(vmx)->vcpu; \
4579 bool __enabled; \
4580 \
4581 if (cpu_has_vmx_##name()) { \
4582 if (kvm_is_governed_feature(X86_FEATURE_##feat_name)) \
4583 __enabled = guest_can_use(__vcpu, X86_FEATURE_##feat_name); \
4584 else \
4585 __enabled = guest_cpuid_has(__vcpu, X86_FEATURE_##feat_name); \
4586 vmx_adjust_secondary_exec_control(vmx, exec_control, SECONDARY_EXEC_##ctrl_name,\
4587 __enabled, exiting); \
4588 } \
4589 })
4590
4591 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4592 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4593 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4594
4595 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4596 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4597
vmx_secondary_exec_control(struct vcpu_vmx * vmx)4598 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4599 {
4600 struct kvm_vcpu *vcpu = &vmx->vcpu;
4601
4602 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4603
4604 if (vmx_pt_mode_is_system())
4605 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4606 if (!cpu_need_virtualize_apic_accesses(vcpu))
4607 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4608 if (vmx->vpid == 0)
4609 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4610 if (!enable_ept) {
4611 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4612 enable_unrestricted_guest = 0;
4613 }
4614 if (!enable_unrestricted_guest)
4615 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4616 if (kvm_pause_in_guest(vmx->vcpu.kvm))
4617 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4618 if (!kvm_vcpu_apicv_active(vcpu))
4619 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4620 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4621 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4622
4623 /*
4624 * KVM doesn't support VMFUNC for L1, but the control is set in KVM's
4625 * base configuration as KVM emulates VMFUNC[EPTP_SWITCHING] for L2.
4626 */
4627 exec_control &= ~SECONDARY_EXEC_ENABLE_VMFUNC;
4628
4629 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4630 * in vmx_set_cr4. */
4631 exec_control &= ~SECONDARY_EXEC_DESC;
4632
4633 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4634 (handle_vmptrld).
4635 We can NOT enable shadow_vmcs here because we don't have yet
4636 a current VMCS12
4637 */
4638 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4639
4640 /*
4641 * PML is enabled/disabled when dirty logging of memsmlots changes, but
4642 * it needs to be set here when dirty logging is already active, e.g.
4643 * if this vCPU was created after dirty logging was enabled.
4644 */
4645 if (!enable_pml || !atomic_read(&vcpu->kvm->nr_memslots_dirty_logging))
4646 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4647
4648 vmx_adjust_sec_exec_feature(vmx, &exec_control, xsaves, XSAVES);
4649
4650 /*
4651 * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
4652 * feature is exposed to the guest. This creates a virtualization hole
4653 * if both are supported in hardware but only one is exposed to the
4654 * guest, but letting the guest execute RDTSCP or RDPID when either one
4655 * is advertised is preferable to emulating the advertised instruction
4656 * in KVM on #UD, and obviously better than incorrectly injecting #UD.
4657 */
4658 if (cpu_has_vmx_rdtscp()) {
4659 bool rdpid_or_rdtscp_enabled =
4660 guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
4661 guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
4662
4663 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4664 SECONDARY_EXEC_ENABLE_RDTSCP,
4665 rdpid_or_rdtscp_enabled, false);
4666 }
4667
4668 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4669
4670 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4671 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4672
4673 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4674 ENABLE_USR_WAIT_PAUSE, false);
4675
4676 if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4677 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4678
4679 if (!kvm_notify_vmexit_enabled(vcpu->kvm))
4680 exec_control &= ~SECONDARY_EXEC_NOTIFY_VM_EXITING;
4681
4682 return exec_control;
4683 }
4684
vmx_get_pid_table_order(struct kvm * kvm)4685 static inline int vmx_get_pid_table_order(struct kvm *kvm)
4686 {
4687 return get_order(kvm->arch.max_vcpu_ids * sizeof(*to_kvm_vmx(kvm)->pid_table));
4688 }
4689
vmx_alloc_ipiv_pid_table(struct kvm * kvm)4690 static int vmx_alloc_ipiv_pid_table(struct kvm *kvm)
4691 {
4692 struct page *pages;
4693 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4694
4695 if (!irqchip_in_kernel(kvm) || !enable_ipiv)
4696 return 0;
4697
4698 if (kvm_vmx->pid_table)
4699 return 0;
4700
4701 pages = alloc_pages(GFP_KERNEL_ACCOUNT | __GFP_ZERO,
4702 vmx_get_pid_table_order(kvm));
4703 if (!pages)
4704 return -ENOMEM;
4705
4706 kvm_vmx->pid_table = (void *)page_address(pages);
4707 return 0;
4708 }
4709
vmx_vcpu_precreate(struct kvm * kvm)4710 static int vmx_vcpu_precreate(struct kvm *kvm)
4711 {
4712 return vmx_alloc_ipiv_pid_table(kvm);
4713 }
4714
4715 #define VMX_XSS_EXIT_BITMAP 0
4716
init_vmcs(struct vcpu_vmx * vmx)4717 static void init_vmcs(struct vcpu_vmx *vmx)
4718 {
4719 struct kvm *kvm = vmx->vcpu.kvm;
4720 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4721
4722 if (nested)
4723 nested_vmx_set_vmcs_shadowing_bitmap();
4724
4725 if (cpu_has_vmx_msr_bitmap())
4726 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4727
4728 vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA); /* 22.3.1.5 */
4729
4730 /* Control */
4731 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4732
4733 exec_controls_set(vmx, vmx_exec_control(vmx));
4734
4735 if (cpu_has_secondary_exec_ctrls())
4736 secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx));
4737
4738 if (cpu_has_tertiary_exec_ctrls())
4739 tertiary_exec_controls_set(vmx, vmx_tertiary_exec_control(vmx));
4740
4741 if (enable_apicv && lapic_in_kernel(&vmx->vcpu)) {
4742 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4743 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4744 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4745 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4746
4747 vmcs_write16(GUEST_INTR_STATUS, 0);
4748
4749 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4750 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4751 }
4752
4753 if (vmx_can_use_ipiv(&vmx->vcpu)) {
4754 vmcs_write64(PID_POINTER_TABLE, __pa(kvm_vmx->pid_table));
4755 vmcs_write16(LAST_PID_POINTER_INDEX, kvm->arch.max_vcpu_ids - 1);
4756 }
4757
4758 if (!kvm_pause_in_guest(kvm)) {
4759 vmcs_write32(PLE_GAP, ple_gap);
4760 vmx->ple_window = ple_window;
4761 vmx->ple_window_dirty = true;
4762 }
4763
4764 if (kvm_notify_vmexit_enabled(kvm))
4765 vmcs_write32(NOTIFY_WINDOW, kvm->arch.notify_window);
4766
4767 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4768 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4769 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
4770
4771 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
4772 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
4773 vmx_set_constant_host_state(vmx);
4774 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4775 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4776
4777 if (cpu_has_vmx_vmfunc())
4778 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4779
4780 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4781 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4782 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4783 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4784 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4785
4786 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4787 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4788
4789 vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4790
4791 /* 22.2.1, 20.8.1 */
4792 vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4793
4794 vmx->vcpu.arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
4795 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4796
4797 set_cr4_guest_host_mask(vmx);
4798
4799 if (vmx->vpid != 0)
4800 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4801
4802 if (cpu_has_vmx_xsaves())
4803 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4804
4805 if (enable_pml) {
4806 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4807 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4808 }
4809
4810 vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4811
4812 if (vmx_pt_mode_is_host_guest()) {
4813 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4814 /* Bit[6~0] are forced to 1, writes are ignored. */
4815 vmx->pt_desc.guest.output_mask = 0x7F;
4816 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4817 }
4818
4819 vmcs_write32(GUEST_SYSENTER_CS, 0);
4820 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4821 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4822 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4823
4824 if (cpu_has_vmx_tpr_shadow()) {
4825 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4826 if (cpu_need_tpr_shadow(&vmx->vcpu))
4827 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4828 __pa(vmx->vcpu.arch.apic->regs));
4829 vmcs_write32(TPR_THRESHOLD, 0);
4830 }
4831
4832 vmx_setup_uret_msrs(vmx);
4833 }
4834
__vmx_vcpu_reset(struct kvm_vcpu * vcpu)4835 static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4836 {
4837 struct vcpu_vmx *vmx = to_vmx(vcpu);
4838
4839 init_vmcs(vmx);
4840
4841 if (nested)
4842 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
4843
4844 vcpu_setup_sgx_lepubkeyhash(vcpu);
4845
4846 vmx->nested.posted_intr_nv = -1;
4847 vmx->nested.vmxon_ptr = INVALID_GPA;
4848 vmx->nested.current_vmptr = INVALID_GPA;
4849 vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
4850
4851 vcpu->arch.microcode_version = 0x100000000ULL;
4852 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
4853
4854 /*
4855 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
4856 * or POSTED_INTR_WAKEUP_VECTOR.
4857 */
4858 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
4859 vmx->pi_desc.sn = 1;
4860 }
4861
vmx_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)4862 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4863 {
4864 struct vcpu_vmx *vmx = to_vmx(vcpu);
4865
4866 if (!init_event)
4867 __vmx_vcpu_reset(vcpu);
4868
4869 vmx->rmode.vm86_active = 0;
4870 vmx->spec_ctrl = 0;
4871
4872 vmx->msr_ia32_umwait_control = 0;
4873
4874 vmx->hv_deadline_tsc = -1;
4875 kvm_set_cr8(vcpu, 0);
4876
4877 vmx_segment_cache_clear(vmx);
4878 kvm_register_mark_available(vcpu, VCPU_EXREG_SEGMENTS);
4879
4880 seg_setup(VCPU_SREG_CS);
4881 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4882 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4883
4884 seg_setup(VCPU_SREG_DS);
4885 seg_setup(VCPU_SREG_ES);
4886 seg_setup(VCPU_SREG_FS);
4887 seg_setup(VCPU_SREG_GS);
4888 seg_setup(VCPU_SREG_SS);
4889
4890 vmcs_write16(GUEST_TR_SELECTOR, 0);
4891 vmcs_writel(GUEST_TR_BASE, 0);
4892 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4893 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4894
4895 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4896 vmcs_writel(GUEST_LDTR_BASE, 0);
4897 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4898 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4899
4900 vmcs_writel(GUEST_GDTR_BASE, 0);
4901 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4902
4903 vmcs_writel(GUEST_IDTR_BASE, 0);
4904 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4905
4906 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4907 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4908 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4909 if (kvm_mpx_supported())
4910 vmcs_write64(GUEST_BNDCFGS, 0);
4911
4912 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
4913
4914 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4915
4916 vpid_sync_context(vmx->vpid);
4917
4918 vmx_update_fb_clear_dis(vcpu, vmx);
4919 }
4920
vmx_enable_irq_window(struct kvm_vcpu * vcpu)4921 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4922 {
4923 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4924 }
4925
vmx_enable_nmi_window(struct kvm_vcpu * vcpu)4926 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4927 {
4928 if (!enable_vnmi ||
4929 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4930 vmx_enable_irq_window(vcpu);
4931 return;
4932 }
4933
4934 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4935 }
4936
vmx_inject_irq(struct kvm_vcpu * vcpu,bool reinjected)4937 static void vmx_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
4938 {
4939 struct vcpu_vmx *vmx = to_vmx(vcpu);
4940 uint32_t intr;
4941 int irq = vcpu->arch.interrupt.nr;
4942
4943 trace_kvm_inj_virq(irq, vcpu->arch.interrupt.soft, reinjected);
4944
4945 ++vcpu->stat.irq_injections;
4946 if (vmx->rmode.vm86_active) {
4947 int inc_eip = 0;
4948 if (vcpu->arch.interrupt.soft)
4949 inc_eip = vcpu->arch.event_exit_inst_len;
4950 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4951 return;
4952 }
4953 intr = irq | INTR_INFO_VALID_MASK;
4954 if (vcpu->arch.interrupt.soft) {
4955 intr |= INTR_TYPE_SOFT_INTR;
4956 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4957 vmx->vcpu.arch.event_exit_inst_len);
4958 } else
4959 intr |= INTR_TYPE_EXT_INTR;
4960 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4961
4962 vmx_clear_hlt(vcpu);
4963 }
4964
vmx_inject_nmi(struct kvm_vcpu * vcpu)4965 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4966 {
4967 struct vcpu_vmx *vmx = to_vmx(vcpu);
4968
4969 if (!enable_vnmi) {
4970 /*
4971 * Tracking the NMI-blocked state in software is built upon
4972 * finding the next open IRQ window. This, in turn, depends on
4973 * well-behaving guests: They have to keep IRQs disabled at
4974 * least as long as the NMI handler runs. Otherwise we may
4975 * cause NMI nesting, maybe breaking the guest. But as this is
4976 * highly unlikely, we can live with the residual risk.
4977 */
4978 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4979 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4980 }
4981
4982 ++vcpu->stat.nmi_injections;
4983 vmx->loaded_vmcs->nmi_known_unmasked = false;
4984
4985 if (vmx->rmode.vm86_active) {
4986 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4987 return;
4988 }
4989
4990 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4991 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4992
4993 vmx_clear_hlt(vcpu);
4994 }
4995
vmx_get_nmi_mask(struct kvm_vcpu * vcpu)4996 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4997 {
4998 struct vcpu_vmx *vmx = to_vmx(vcpu);
4999 bool masked;
5000
5001 if (!enable_vnmi)
5002 return vmx->loaded_vmcs->soft_vnmi_blocked;
5003 if (vmx->loaded_vmcs->nmi_known_unmasked)
5004 return false;
5005 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
5006 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5007 return masked;
5008 }
5009
vmx_set_nmi_mask(struct kvm_vcpu * vcpu,bool masked)5010 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5011 {
5012 struct vcpu_vmx *vmx = to_vmx(vcpu);
5013
5014 if (!enable_vnmi) {
5015 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
5016 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
5017 vmx->loaded_vmcs->vnmi_blocked_time = 0;
5018 }
5019 } else {
5020 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
5021 if (masked)
5022 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5023 GUEST_INTR_STATE_NMI);
5024 else
5025 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
5026 GUEST_INTR_STATE_NMI);
5027 }
5028 }
5029
vmx_nmi_blocked(struct kvm_vcpu * vcpu)5030 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
5031 {
5032 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
5033 return false;
5034
5035 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
5036 return true;
5037
5038 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5039 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
5040 GUEST_INTR_STATE_NMI));
5041 }
5042
vmx_nmi_allowed(struct kvm_vcpu * vcpu,bool for_injection)5043 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
5044 {
5045 if (to_vmx(vcpu)->nested.nested_run_pending)
5046 return -EBUSY;
5047
5048 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
5049 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
5050 return -EBUSY;
5051
5052 return !vmx_nmi_blocked(vcpu);
5053 }
5054
__vmx_interrupt_blocked(struct kvm_vcpu * vcpu)5055 bool __vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
5056 {
5057 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
5058 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5059 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
5060 }
5061
vmx_interrupt_blocked(struct kvm_vcpu * vcpu)5062 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
5063 {
5064 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
5065 return false;
5066
5067 return __vmx_interrupt_blocked(vcpu);
5068 }
5069
vmx_interrupt_allowed(struct kvm_vcpu * vcpu,bool for_injection)5070 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
5071 {
5072 if (to_vmx(vcpu)->nested.nested_run_pending)
5073 return -EBUSY;
5074
5075 /*
5076 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
5077 * e.g. if the IRQ arrived asynchronously after checking nested events.
5078 */
5079 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
5080 return -EBUSY;
5081
5082 return !vmx_interrupt_blocked(vcpu);
5083 }
5084
vmx_set_tss_addr(struct kvm * kvm,unsigned int addr)5085 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
5086 {
5087 void __user *ret;
5088
5089 if (enable_unrestricted_guest)
5090 return 0;
5091
5092 mutex_lock(&kvm->slots_lock);
5093 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
5094 PAGE_SIZE * 3);
5095 mutex_unlock(&kvm->slots_lock);
5096
5097 if (IS_ERR(ret))
5098 return PTR_ERR(ret);
5099
5100 to_kvm_vmx(kvm)->tss_addr = addr;
5101
5102 return init_rmode_tss(kvm, ret);
5103 }
5104
vmx_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)5105 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5106 {
5107 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
5108 return 0;
5109 }
5110
rmode_exception(struct kvm_vcpu * vcpu,int vec)5111 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
5112 {
5113 switch (vec) {
5114 case BP_VECTOR:
5115 /*
5116 * Update instruction length as we may reinject the exception
5117 * from user space while in guest debugging mode.
5118 */
5119 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
5120 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5121 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5122 return false;
5123 fallthrough;
5124 case DB_VECTOR:
5125 return !(vcpu->guest_debug &
5126 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
5127 case DE_VECTOR:
5128 case OF_VECTOR:
5129 case BR_VECTOR:
5130 case UD_VECTOR:
5131 case DF_VECTOR:
5132 case SS_VECTOR:
5133 case GP_VECTOR:
5134 case MF_VECTOR:
5135 return true;
5136 }
5137 return false;
5138 }
5139
handle_rmode_exception(struct kvm_vcpu * vcpu,int vec,u32 err_code)5140 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
5141 int vec, u32 err_code)
5142 {
5143 /*
5144 * Instruction with address size override prefix opcode 0x67
5145 * Cause the #SS fault with 0 error code in VM86 mode.
5146 */
5147 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5148 if (kvm_emulate_instruction(vcpu, 0)) {
5149 if (vcpu->arch.halt_request) {
5150 vcpu->arch.halt_request = 0;
5151 return kvm_emulate_halt_noskip(vcpu);
5152 }
5153 return 1;
5154 }
5155 return 0;
5156 }
5157
5158 /*
5159 * Forward all other exceptions that are valid in real mode.
5160 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5161 * the required debugging infrastructure rework.
5162 */
5163 kvm_queue_exception(vcpu, vec);
5164 return 1;
5165 }
5166
handle_machine_check(struct kvm_vcpu * vcpu)5167 static int handle_machine_check(struct kvm_vcpu *vcpu)
5168 {
5169 /* handled by vmx_vcpu_run() */
5170 return 1;
5171 }
5172
5173 /*
5174 * If the host has split lock detection disabled, then #AC is
5175 * unconditionally injected into the guest, which is the pre split lock
5176 * detection behaviour.
5177 *
5178 * If the host has split lock detection enabled then #AC is
5179 * only injected into the guest when:
5180 * - Guest CPL == 3 (user mode)
5181 * - Guest has #AC detection enabled in CR0
5182 * - Guest EFLAGS has AC bit set
5183 */
vmx_guest_inject_ac(struct kvm_vcpu * vcpu)5184 bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu)
5185 {
5186 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5187 return true;
5188
5189 return vmx_get_cpl(vcpu) == 3 && kvm_is_cr0_bit_set(vcpu, X86_CR0_AM) &&
5190 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
5191 }
5192
handle_exception_nmi(struct kvm_vcpu * vcpu)5193 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
5194 {
5195 struct vcpu_vmx *vmx = to_vmx(vcpu);
5196 struct kvm_run *kvm_run = vcpu->run;
5197 u32 intr_info, ex_no, error_code;
5198 unsigned long cr2, dr6;
5199 u32 vect_info;
5200
5201 vect_info = vmx->idt_vectoring_info;
5202 intr_info = vmx_get_intr_info(vcpu);
5203
5204 /*
5205 * Machine checks are handled by handle_exception_irqoff(), or by
5206 * vmx_vcpu_run() if a #MC occurs on VM-Entry. NMIs are handled by
5207 * vmx_vcpu_enter_exit().
5208 */
5209 if (is_machine_check(intr_info) || is_nmi(intr_info))
5210 return 1;
5211
5212 /*
5213 * Queue the exception here instead of in handle_nm_fault_irqoff().
5214 * This ensures the nested_vmx check is not skipped so vmexit can
5215 * be reflected to L1 (when it intercepts #NM) before reaching this
5216 * point.
5217 */
5218 if (is_nm_fault(intr_info)) {
5219 kvm_queue_exception(vcpu, NM_VECTOR);
5220 return 1;
5221 }
5222
5223 if (is_invalid_opcode(intr_info))
5224 return handle_ud(vcpu);
5225
5226 error_code = 0;
5227 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5228 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5229
5230 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
5231 WARN_ON_ONCE(!enable_vmware_backdoor);
5232
5233 /*
5234 * VMware backdoor emulation on #GP interception only handles
5235 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
5236 * error code on #GP.
5237 */
5238 if (error_code) {
5239 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
5240 return 1;
5241 }
5242 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
5243 }
5244
5245 /*
5246 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5247 * MMIO, it is better to report an internal error.
5248 * See the comments in vmx_handle_exit.
5249 */
5250 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5251 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5252 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5253 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5254 vcpu->run->internal.ndata = 4;
5255 vcpu->run->internal.data[0] = vect_info;
5256 vcpu->run->internal.data[1] = intr_info;
5257 vcpu->run->internal.data[2] = error_code;
5258 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
5259 return 0;
5260 }
5261
5262 if (is_page_fault(intr_info)) {
5263 cr2 = vmx_get_exit_qual(vcpu);
5264 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
5265 /*
5266 * EPT will cause page fault only if we need to
5267 * detect illegal GPAs.
5268 */
5269 WARN_ON_ONCE(!allow_smaller_maxphyaddr);
5270 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
5271 return 1;
5272 } else
5273 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
5274 }
5275
5276 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5277
5278 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5279 return handle_rmode_exception(vcpu, ex_no, error_code);
5280
5281 switch (ex_no) {
5282 case DB_VECTOR:
5283 dr6 = vmx_get_exit_qual(vcpu);
5284 if (!(vcpu->guest_debug &
5285 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5286 /*
5287 * If the #DB was due to ICEBP, a.k.a. INT1, skip the
5288 * instruction. ICEBP generates a trap-like #DB, but
5289 * despite its interception control being tied to #DB,
5290 * is an instruction intercept, i.e. the VM-Exit occurs
5291 * on the ICEBP itself. Use the inner "skip" helper to
5292 * avoid single-step #DB and MTF updates, as ICEBP is
5293 * higher priority. Note, skipping ICEBP still clears
5294 * STI and MOVSS blocking.
5295 *
5296 * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
5297 * if single-step is enabled in RFLAGS and STI or MOVSS
5298 * blocking is active, as the CPU doesn't set the bit
5299 * on VM-Exit due to #DB interception. VM-Entry has a
5300 * consistency check that a single-step #DB is pending
5301 * in this scenario as the previous instruction cannot
5302 * have toggled RFLAGS.TF 0=>1 (because STI and POP/MOV
5303 * don't modify RFLAGS), therefore the one instruction
5304 * delay when activating single-step breakpoints must
5305 * have already expired. Note, the CPU sets/clears BS
5306 * as appropriate for all other VM-Exits types.
5307 */
5308 if (is_icebp(intr_info))
5309 WARN_ON(!skip_emulated_instruction(vcpu));
5310 else if ((vmx_get_rflags(vcpu) & X86_EFLAGS_TF) &&
5311 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5312 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)))
5313 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
5314 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS) | DR6_BS);
5315
5316 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
5317 return 1;
5318 }
5319 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
5320 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5321 fallthrough;
5322 case BP_VECTOR:
5323 /*
5324 * Update instruction length as we may reinject #BP from
5325 * user space while in guest debugging mode. Reading it for
5326 * #DB as well causes no harm, it is not used in that case.
5327 */
5328 vmx->vcpu.arch.event_exit_inst_len =
5329 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5330 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5331 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5332 kvm_run->debug.arch.exception = ex_no;
5333 break;
5334 case AC_VECTOR:
5335 if (vmx_guest_inject_ac(vcpu)) {
5336 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5337 return 1;
5338 }
5339
5340 /*
5341 * Handle split lock. Depending on detection mode this will
5342 * either warn and disable split lock detection for this
5343 * task or force SIGBUS on it.
5344 */
5345 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
5346 return 1;
5347 fallthrough;
5348 default:
5349 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5350 kvm_run->ex.exception = ex_no;
5351 kvm_run->ex.error_code = error_code;
5352 break;
5353 }
5354 return 0;
5355 }
5356
handle_external_interrupt(struct kvm_vcpu * vcpu)5357 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
5358 {
5359 ++vcpu->stat.irq_exits;
5360 return 1;
5361 }
5362
handle_triple_fault(struct kvm_vcpu * vcpu)5363 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5364 {
5365 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5366 vcpu->mmio_needed = 0;
5367 return 0;
5368 }
5369
handle_io(struct kvm_vcpu * vcpu)5370 static int handle_io(struct kvm_vcpu *vcpu)
5371 {
5372 unsigned long exit_qualification;
5373 int size, in, string;
5374 unsigned port;
5375
5376 exit_qualification = vmx_get_exit_qual(vcpu);
5377 string = (exit_qualification & 16) != 0;
5378
5379 ++vcpu->stat.io_exits;
5380
5381 if (string)
5382 return kvm_emulate_instruction(vcpu, 0);
5383
5384 port = exit_qualification >> 16;
5385 size = (exit_qualification & 7) + 1;
5386 in = (exit_qualification & 8) != 0;
5387
5388 return kvm_fast_pio(vcpu, size, port, in);
5389 }
5390
5391 static void
vmx_patch_hypercall(struct kvm_vcpu * vcpu,unsigned char * hypercall)5392 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5393 {
5394 /*
5395 * Patch in the VMCALL instruction:
5396 */
5397 hypercall[0] = 0x0f;
5398 hypercall[1] = 0x01;
5399 hypercall[2] = 0xc1;
5400 }
5401
5402 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
handle_set_cr0(struct kvm_vcpu * vcpu,unsigned long val)5403 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5404 {
5405 if (is_guest_mode(vcpu)) {
5406 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5407 unsigned long orig_val = val;
5408
5409 /*
5410 * We get here when L2 changed cr0 in a way that did not change
5411 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5412 * but did change L0 shadowed bits. So we first calculate the
5413 * effective cr0 value that L1 would like to write into the
5414 * hardware. It consists of the L2-owned bits from the new
5415 * value combined with the L1-owned bits from L1's guest_cr0.
5416 */
5417 val = (val & ~vmcs12->cr0_guest_host_mask) |
5418 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5419
5420 if (kvm_set_cr0(vcpu, val))
5421 return 1;
5422 vmcs_writel(CR0_READ_SHADOW, orig_val);
5423 return 0;
5424 } else {
5425 return kvm_set_cr0(vcpu, val);
5426 }
5427 }
5428
handle_set_cr4(struct kvm_vcpu * vcpu,unsigned long val)5429 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5430 {
5431 if (is_guest_mode(vcpu)) {
5432 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5433 unsigned long orig_val = val;
5434
5435 /* analogously to handle_set_cr0 */
5436 val = (val & ~vmcs12->cr4_guest_host_mask) |
5437 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5438 if (kvm_set_cr4(vcpu, val))
5439 return 1;
5440 vmcs_writel(CR4_READ_SHADOW, orig_val);
5441 return 0;
5442 } else
5443 return kvm_set_cr4(vcpu, val);
5444 }
5445
handle_desc(struct kvm_vcpu * vcpu)5446 static int handle_desc(struct kvm_vcpu *vcpu)
5447 {
5448 /*
5449 * UMIP emulation relies on intercepting writes to CR4.UMIP, i.e. this
5450 * and other code needs to be updated if UMIP can be guest owned.
5451 */
5452 BUILD_BUG_ON(KVM_POSSIBLE_CR4_GUEST_BITS & X86_CR4_UMIP);
5453
5454 WARN_ON_ONCE(!kvm_is_cr4_bit_set(vcpu, X86_CR4_UMIP));
5455 return kvm_emulate_instruction(vcpu, 0);
5456 }
5457
handle_cr(struct kvm_vcpu * vcpu)5458 static int handle_cr(struct kvm_vcpu *vcpu)
5459 {
5460 unsigned long exit_qualification, val;
5461 int cr;
5462 int reg;
5463 int err;
5464 int ret;
5465
5466 exit_qualification = vmx_get_exit_qual(vcpu);
5467 cr = exit_qualification & 15;
5468 reg = (exit_qualification >> 8) & 15;
5469 switch ((exit_qualification >> 4) & 3) {
5470 case 0: /* mov to cr */
5471 val = kvm_register_read(vcpu, reg);
5472 trace_kvm_cr_write(cr, val);
5473 switch (cr) {
5474 case 0:
5475 err = handle_set_cr0(vcpu, val);
5476 return kvm_complete_insn_gp(vcpu, err);
5477 case 3:
5478 WARN_ON_ONCE(enable_unrestricted_guest);
5479
5480 err = kvm_set_cr3(vcpu, val);
5481 return kvm_complete_insn_gp(vcpu, err);
5482 case 4:
5483 err = handle_set_cr4(vcpu, val);
5484 return kvm_complete_insn_gp(vcpu, err);
5485 case 8: {
5486 u8 cr8_prev = kvm_get_cr8(vcpu);
5487 u8 cr8 = (u8)val;
5488 err = kvm_set_cr8(vcpu, cr8);
5489 ret = kvm_complete_insn_gp(vcpu, err);
5490 if (lapic_in_kernel(vcpu))
5491 return ret;
5492 if (cr8_prev <= cr8)
5493 return ret;
5494 /*
5495 * TODO: we might be squashing a
5496 * KVM_GUESTDBG_SINGLESTEP-triggered
5497 * KVM_EXIT_DEBUG here.
5498 */
5499 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5500 return 0;
5501 }
5502 }
5503 break;
5504 case 2: /* clts */
5505 KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS");
5506 return -EIO;
5507 case 1: /*mov from cr*/
5508 switch (cr) {
5509 case 3:
5510 WARN_ON_ONCE(enable_unrestricted_guest);
5511
5512 val = kvm_read_cr3(vcpu);
5513 kvm_register_write(vcpu, reg, val);
5514 trace_kvm_cr_read(cr, val);
5515 return kvm_skip_emulated_instruction(vcpu);
5516 case 8:
5517 val = kvm_get_cr8(vcpu);
5518 kvm_register_write(vcpu, reg, val);
5519 trace_kvm_cr_read(cr, val);
5520 return kvm_skip_emulated_instruction(vcpu);
5521 }
5522 break;
5523 case 3: /* lmsw */
5524 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5525 trace_kvm_cr_write(0, (kvm_read_cr0_bits(vcpu, ~0xful) | val));
5526 kvm_lmsw(vcpu, val);
5527
5528 return kvm_skip_emulated_instruction(vcpu);
5529 default:
5530 break;
5531 }
5532 vcpu->run->exit_reason = 0;
5533 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5534 (int)(exit_qualification >> 4) & 3, cr);
5535 return 0;
5536 }
5537
handle_dr(struct kvm_vcpu * vcpu)5538 static int handle_dr(struct kvm_vcpu *vcpu)
5539 {
5540 unsigned long exit_qualification;
5541 int dr, dr7, reg;
5542 int err = 1;
5543
5544 exit_qualification = vmx_get_exit_qual(vcpu);
5545 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5546
5547 /* First, if DR does not exist, trigger UD */
5548 if (!kvm_require_dr(vcpu, dr))
5549 return 1;
5550
5551 if (vmx_get_cpl(vcpu) > 0)
5552 goto out;
5553
5554 dr7 = vmcs_readl(GUEST_DR7);
5555 if (dr7 & DR7_GD) {
5556 /*
5557 * As the vm-exit takes precedence over the debug trap, we
5558 * need to emulate the latter, either for the host or the
5559 * guest debugging itself.
5560 */
5561 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5562 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5563 vcpu->run->debug.arch.dr7 = dr7;
5564 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5565 vcpu->run->debug.arch.exception = DB_VECTOR;
5566 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5567 return 0;
5568 } else {
5569 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5570 return 1;
5571 }
5572 }
5573
5574 if (vcpu->guest_debug == 0) {
5575 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5576
5577 /*
5578 * No more DR vmexits; force a reload of the debug registers
5579 * and reenter on this instruction. The next vmexit will
5580 * retrieve the full state of the debug registers.
5581 */
5582 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5583 return 1;
5584 }
5585
5586 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5587 if (exit_qualification & TYPE_MOV_FROM_DR) {
5588 unsigned long val;
5589
5590 kvm_get_dr(vcpu, dr, &val);
5591 kvm_register_write(vcpu, reg, val);
5592 err = 0;
5593 } else {
5594 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5595 }
5596
5597 out:
5598 return kvm_complete_insn_gp(vcpu, err);
5599 }
5600
vmx_sync_dirty_debug_regs(struct kvm_vcpu * vcpu)5601 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5602 {
5603 get_debugreg(vcpu->arch.db[0], 0);
5604 get_debugreg(vcpu->arch.db[1], 1);
5605 get_debugreg(vcpu->arch.db[2], 2);
5606 get_debugreg(vcpu->arch.db[3], 3);
5607 get_debugreg(vcpu->arch.dr6, 6);
5608 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5609
5610 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5611 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5612
5613 /*
5614 * exc_debug expects dr6 to be cleared after it runs, avoid that it sees
5615 * a stale dr6 from the guest.
5616 */
5617 set_debugreg(DR6_RESERVED, 6);
5618 }
5619
vmx_set_dr6(struct kvm_vcpu * vcpu,unsigned long val)5620 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
5621 {
5622 lockdep_assert_irqs_disabled();
5623 set_debugreg(vcpu->arch.dr6, 6);
5624 }
5625
vmx_set_dr7(struct kvm_vcpu * vcpu,unsigned long val)5626 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5627 {
5628 vmcs_writel(GUEST_DR7, val);
5629 }
5630
handle_tpr_below_threshold(struct kvm_vcpu * vcpu)5631 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5632 {
5633 kvm_apic_update_ppr(vcpu);
5634 return 1;
5635 }
5636
handle_interrupt_window(struct kvm_vcpu * vcpu)5637 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5638 {
5639 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5640
5641 kvm_make_request(KVM_REQ_EVENT, vcpu);
5642
5643 ++vcpu->stat.irq_window_exits;
5644 return 1;
5645 }
5646
handle_invlpg(struct kvm_vcpu * vcpu)5647 static int handle_invlpg(struct kvm_vcpu *vcpu)
5648 {
5649 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5650
5651 kvm_mmu_invlpg(vcpu, exit_qualification);
5652 return kvm_skip_emulated_instruction(vcpu);
5653 }
5654
handle_apic_access(struct kvm_vcpu * vcpu)5655 static int handle_apic_access(struct kvm_vcpu *vcpu)
5656 {
5657 if (likely(fasteoi)) {
5658 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5659 int access_type, offset;
5660
5661 access_type = exit_qualification & APIC_ACCESS_TYPE;
5662 offset = exit_qualification & APIC_ACCESS_OFFSET;
5663 /*
5664 * Sane guest uses MOV to write EOI, with written value
5665 * not cared. So make a short-circuit here by avoiding
5666 * heavy instruction emulation.
5667 */
5668 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5669 (offset == APIC_EOI)) {
5670 kvm_lapic_set_eoi(vcpu);
5671 return kvm_skip_emulated_instruction(vcpu);
5672 }
5673 }
5674 return kvm_emulate_instruction(vcpu, 0);
5675 }
5676
handle_apic_eoi_induced(struct kvm_vcpu * vcpu)5677 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5678 {
5679 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5680 int vector = exit_qualification & 0xff;
5681
5682 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5683 kvm_apic_set_eoi_accelerated(vcpu, vector);
5684 return 1;
5685 }
5686
handle_apic_write(struct kvm_vcpu * vcpu)5687 static int handle_apic_write(struct kvm_vcpu *vcpu)
5688 {
5689 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5690
5691 /*
5692 * APIC-write VM-Exit is trap-like, KVM doesn't need to advance RIP and
5693 * hardware has done any necessary aliasing, offset adjustments, etc...
5694 * for the access. I.e. the correct value has already been written to
5695 * the vAPIC page for the correct 16-byte chunk. KVM needs only to
5696 * retrieve the register value and emulate the access.
5697 */
5698 u32 offset = exit_qualification & 0xff0;
5699
5700 kvm_apic_write_nodecode(vcpu, offset);
5701 return 1;
5702 }
5703
handle_task_switch(struct kvm_vcpu * vcpu)5704 static int handle_task_switch(struct kvm_vcpu *vcpu)
5705 {
5706 struct vcpu_vmx *vmx = to_vmx(vcpu);
5707 unsigned long exit_qualification;
5708 bool has_error_code = false;
5709 u32 error_code = 0;
5710 u16 tss_selector;
5711 int reason, type, idt_v, idt_index;
5712
5713 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5714 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5715 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5716
5717 exit_qualification = vmx_get_exit_qual(vcpu);
5718
5719 reason = (u32)exit_qualification >> 30;
5720 if (reason == TASK_SWITCH_GATE && idt_v) {
5721 switch (type) {
5722 case INTR_TYPE_NMI_INTR:
5723 vcpu->arch.nmi_injected = false;
5724 vmx_set_nmi_mask(vcpu, true);
5725 break;
5726 case INTR_TYPE_EXT_INTR:
5727 case INTR_TYPE_SOFT_INTR:
5728 kvm_clear_interrupt_queue(vcpu);
5729 break;
5730 case INTR_TYPE_HARD_EXCEPTION:
5731 if (vmx->idt_vectoring_info &
5732 VECTORING_INFO_DELIVER_CODE_MASK) {
5733 has_error_code = true;
5734 error_code =
5735 vmcs_read32(IDT_VECTORING_ERROR_CODE);
5736 }
5737 fallthrough;
5738 case INTR_TYPE_SOFT_EXCEPTION:
5739 kvm_clear_exception_queue(vcpu);
5740 break;
5741 default:
5742 break;
5743 }
5744 }
5745 tss_selector = exit_qualification;
5746
5747 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5748 type != INTR_TYPE_EXT_INTR &&
5749 type != INTR_TYPE_NMI_INTR))
5750 WARN_ON(!skip_emulated_instruction(vcpu));
5751
5752 /*
5753 * TODO: What about debug traps on tss switch?
5754 * Are we supposed to inject them and update dr6?
5755 */
5756 return kvm_task_switch(vcpu, tss_selector,
5757 type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5758 reason, has_error_code, error_code);
5759 }
5760
handle_ept_violation(struct kvm_vcpu * vcpu)5761 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5762 {
5763 unsigned long exit_qualification;
5764 gpa_t gpa;
5765 u64 error_code;
5766
5767 exit_qualification = vmx_get_exit_qual(vcpu);
5768
5769 /*
5770 * EPT violation happened while executing iret from NMI,
5771 * "blocked by NMI" bit has to be set before next VM entry.
5772 * There are errata that may cause this bit to not be set:
5773 * AAK134, BY25.
5774 */
5775 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5776 enable_vnmi &&
5777 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5778 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5779
5780 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5781 trace_kvm_page_fault(vcpu, gpa, exit_qualification);
5782
5783 /* Is it a read fault? */
5784 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5785 ? PFERR_USER_MASK : 0;
5786 /* Is it a write fault? */
5787 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5788 ? PFERR_WRITE_MASK : 0;
5789 /* Is it a fetch fault? */
5790 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5791 ? PFERR_FETCH_MASK : 0;
5792 /* ept page table entry is present? */
5793 error_code |= (exit_qualification & EPT_VIOLATION_RWX_MASK)
5794 ? PFERR_PRESENT_MASK : 0;
5795
5796 error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
5797 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5798
5799 vcpu->arch.exit_qualification = exit_qualification;
5800
5801 /*
5802 * Check that the GPA doesn't exceed physical memory limits, as that is
5803 * a guest page fault. We have to emulate the instruction here, because
5804 * if the illegal address is that of a paging structure, then
5805 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we
5806 * would also use advanced VM-exit information for EPT violations to
5807 * reconstruct the page fault error code.
5808 */
5809 if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5810 return kvm_emulate_instruction(vcpu, 0);
5811
5812 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5813 }
5814
handle_ept_misconfig(struct kvm_vcpu * vcpu)5815 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5816 {
5817 gpa_t gpa;
5818
5819 if (!vmx_can_emulate_instruction(vcpu, EMULTYPE_PF, NULL, 0))
5820 return 1;
5821
5822 /*
5823 * A nested guest cannot optimize MMIO vmexits, because we have an
5824 * nGPA here instead of the required GPA.
5825 */
5826 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5827 if (!is_guest_mode(vcpu) &&
5828 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5829 trace_kvm_fast_mmio(gpa);
5830 return kvm_skip_emulated_instruction(vcpu);
5831 }
5832
5833 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5834 }
5835
handle_nmi_window(struct kvm_vcpu * vcpu)5836 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5837 {
5838 if (KVM_BUG_ON(!enable_vnmi, vcpu->kvm))
5839 return -EIO;
5840
5841 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5842 ++vcpu->stat.nmi_window_exits;
5843 kvm_make_request(KVM_REQ_EVENT, vcpu);
5844
5845 return 1;
5846 }
5847
vmx_emulation_required_with_pending_exception(struct kvm_vcpu * vcpu)5848 static bool vmx_emulation_required_with_pending_exception(struct kvm_vcpu *vcpu)
5849 {
5850 struct vcpu_vmx *vmx = to_vmx(vcpu);
5851
5852 return vmx->emulation_required && !vmx->rmode.vm86_active &&
5853 (kvm_is_exception_pending(vcpu) || vcpu->arch.exception.injected);
5854 }
5855
handle_invalid_guest_state(struct kvm_vcpu * vcpu)5856 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5857 {
5858 struct vcpu_vmx *vmx = to_vmx(vcpu);
5859 bool intr_window_requested;
5860 unsigned count = 130;
5861
5862 intr_window_requested = exec_controls_get(vmx) &
5863 CPU_BASED_INTR_WINDOW_EXITING;
5864
5865 while (vmx->emulation_required && count-- != 0) {
5866 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5867 return handle_interrupt_window(&vmx->vcpu);
5868
5869 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5870 return 1;
5871
5872 if (!kvm_emulate_instruction(vcpu, 0))
5873 return 0;
5874
5875 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5876 kvm_prepare_emulation_failure_exit(vcpu);
5877 return 0;
5878 }
5879
5880 if (vcpu->arch.halt_request) {
5881 vcpu->arch.halt_request = 0;
5882 return kvm_emulate_halt_noskip(vcpu);
5883 }
5884
5885 /*
5886 * Note, return 1 and not 0, vcpu_run() will invoke
5887 * xfer_to_guest_mode() which will create a proper return
5888 * code.
5889 */
5890 if (__xfer_to_guest_mode_work_pending())
5891 return 1;
5892 }
5893
5894 return 1;
5895 }
5896
vmx_vcpu_pre_run(struct kvm_vcpu * vcpu)5897 static int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu)
5898 {
5899 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5900 kvm_prepare_emulation_failure_exit(vcpu);
5901 return 0;
5902 }
5903
5904 return 1;
5905 }
5906
grow_ple_window(struct kvm_vcpu * vcpu)5907 static void grow_ple_window(struct kvm_vcpu *vcpu)
5908 {
5909 struct vcpu_vmx *vmx = to_vmx(vcpu);
5910 unsigned int old = vmx->ple_window;
5911
5912 vmx->ple_window = __grow_ple_window(old, ple_window,
5913 ple_window_grow,
5914 ple_window_max);
5915
5916 if (vmx->ple_window != old) {
5917 vmx->ple_window_dirty = true;
5918 trace_kvm_ple_window_update(vcpu->vcpu_id,
5919 vmx->ple_window, old);
5920 }
5921 }
5922
shrink_ple_window(struct kvm_vcpu * vcpu)5923 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5924 {
5925 struct vcpu_vmx *vmx = to_vmx(vcpu);
5926 unsigned int old = vmx->ple_window;
5927
5928 vmx->ple_window = __shrink_ple_window(old, ple_window,
5929 ple_window_shrink,
5930 ple_window);
5931
5932 if (vmx->ple_window != old) {
5933 vmx->ple_window_dirty = true;
5934 trace_kvm_ple_window_update(vcpu->vcpu_id,
5935 vmx->ple_window, old);
5936 }
5937 }
5938
5939 /*
5940 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5941 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5942 */
handle_pause(struct kvm_vcpu * vcpu)5943 static int handle_pause(struct kvm_vcpu *vcpu)
5944 {
5945 if (!kvm_pause_in_guest(vcpu->kvm))
5946 grow_ple_window(vcpu);
5947
5948 /*
5949 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5950 * VM-execution control is ignored if CPL > 0. OTOH, KVM
5951 * never set PAUSE_EXITING and just set PLE if supported,
5952 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5953 */
5954 kvm_vcpu_on_spin(vcpu, true);
5955 return kvm_skip_emulated_instruction(vcpu);
5956 }
5957
handle_monitor_trap(struct kvm_vcpu * vcpu)5958 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5959 {
5960 return 1;
5961 }
5962
handle_invpcid(struct kvm_vcpu * vcpu)5963 static int handle_invpcid(struct kvm_vcpu *vcpu)
5964 {
5965 u32 vmx_instruction_info;
5966 unsigned long type;
5967 gva_t gva;
5968 struct {
5969 u64 pcid;
5970 u64 gla;
5971 } operand;
5972 int gpr_index;
5973
5974 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5975 kvm_queue_exception(vcpu, UD_VECTOR);
5976 return 1;
5977 }
5978
5979 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5980 gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
5981 type = kvm_register_read(vcpu, gpr_index);
5982
5983 /* According to the Intel instruction reference, the memory operand
5984 * is read even if it isn't needed (e.g., for type==all)
5985 */
5986 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5987 vmx_instruction_info, false,
5988 sizeof(operand), &gva))
5989 return 1;
5990
5991 return kvm_handle_invpcid(vcpu, type, gva);
5992 }
5993
handle_pml_full(struct kvm_vcpu * vcpu)5994 static int handle_pml_full(struct kvm_vcpu *vcpu)
5995 {
5996 unsigned long exit_qualification;
5997
5998 trace_kvm_pml_full(vcpu->vcpu_id);
5999
6000 exit_qualification = vmx_get_exit_qual(vcpu);
6001
6002 /*
6003 * PML buffer FULL happened while executing iret from NMI,
6004 * "blocked by NMI" bit has to be set before next VM entry.
6005 */
6006 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
6007 enable_vnmi &&
6008 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
6009 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6010 GUEST_INTR_STATE_NMI);
6011
6012 /*
6013 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
6014 * here.., and there's no userspace involvement needed for PML.
6015 */
6016 return 1;
6017 }
6018
handle_fastpath_preemption_timer(struct kvm_vcpu * vcpu)6019 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
6020 {
6021 struct vcpu_vmx *vmx = to_vmx(vcpu);
6022
6023 if (!vmx->req_immediate_exit &&
6024 !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
6025 kvm_lapic_expired_hv_timer(vcpu);
6026 return EXIT_FASTPATH_REENTER_GUEST;
6027 }
6028
6029 return EXIT_FASTPATH_NONE;
6030 }
6031
handle_preemption_timer(struct kvm_vcpu * vcpu)6032 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
6033 {
6034 handle_fastpath_preemption_timer(vcpu);
6035 return 1;
6036 }
6037
6038 /*
6039 * When nested=0, all VMX instruction VM Exits filter here. The handlers
6040 * are overwritten by nested_vmx_setup() when nested=1.
6041 */
handle_vmx_instruction(struct kvm_vcpu * vcpu)6042 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
6043 {
6044 kvm_queue_exception(vcpu, UD_VECTOR);
6045 return 1;
6046 }
6047
6048 #ifndef CONFIG_X86_SGX_KVM
handle_encls(struct kvm_vcpu * vcpu)6049 static int handle_encls(struct kvm_vcpu *vcpu)
6050 {
6051 /*
6052 * SGX virtualization is disabled. There is no software enable bit for
6053 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
6054 * the guest from executing ENCLS (when SGX is supported by hardware).
6055 */
6056 kvm_queue_exception(vcpu, UD_VECTOR);
6057 return 1;
6058 }
6059 #endif /* CONFIG_X86_SGX_KVM */
6060
handle_bus_lock_vmexit(struct kvm_vcpu * vcpu)6061 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
6062 {
6063 /*
6064 * Hardware may or may not set the BUS_LOCK_DETECTED flag on BUS_LOCK
6065 * VM-Exits. Unconditionally set the flag here and leave the handling to
6066 * vmx_handle_exit().
6067 */
6068 to_vmx(vcpu)->exit_reason.bus_lock_detected = true;
6069 return 1;
6070 }
6071
handle_notify(struct kvm_vcpu * vcpu)6072 static int handle_notify(struct kvm_vcpu *vcpu)
6073 {
6074 unsigned long exit_qual = vmx_get_exit_qual(vcpu);
6075 bool context_invalid = exit_qual & NOTIFY_VM_CONTEXT_INVALID;
6076
6077 ++vcpu->stat.notify_window_exits;
6078
6079 /*
6080 * Notify VM exit happened while executing iret from NMI,
6081 * "blocked by NMI" bit has to be set before next VM entry.
6082 */
6083 if (enable_vnmi && (exit_qual & INTR_INFO_UNBLOCK_NMI))
6084 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6085 GUEST_INTR_STATE_NMI);
6086
6087 if (vcpu->kvm->arch.notify_vmexit_flags & KVM_X86_NOTIFY_VMEXIT_USER ||
6088 context_invalid) {
6089 vcpu->run->exit_reason = KVM_EXIT_NOTIFY;
6090 vcpu->run->notify.flags = context_invalid ?
6091 KVM_NOTIFY_CONTEXT_INVALID : 0;
6092 return 0;
6093 }
6094
6095 return 1;
6096 }
6097
6098 /*
6099 * The exit handlers return 1 if the exit was handled fully and guest execution
6100 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
6101 * to be done to userspace and return 0.
6102 */
6103 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
6104 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi,
6105 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
6106 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
6107 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
6108 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
6109 [EXIT_REASON_CR_ACCESS] = handle_cr,
6110 [EXIT_REASON_DR_ACCESS] = handle_dr,
6111 [EXIT_REASON_CPUID] = kvm_emulate_cpuid,
6112 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr,
6113 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr,
6114 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window,
6115 [EXIT_REASON_HLT] = kvm_emulate_halt,
6116 [EXIT_REASON_INVD] = kvm_emulate_invd,
6117 [EXIT_REASON_INVLPG] = handle_invlpg,
6118 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc,
6119 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall,
6120 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction,
6121 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction,
6122 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction,
6123 [EXIT_REASON_VMPTRST] = handle_vmx_instruction,
6124 [EXIT_REASON_VMREAD] = handle_vmx_instruction,
6125 [EXIT_REASON_VMRESUME] = handle_vmx_instruction,
6126 [EXIT_REASON_VMWRITE] = handle_vmx_instruction,
6127 [EXIT_REASON_VMOFF] = handle_vmx_instruction,
6128 [EXIT_REASON_VMON] = handle_vmx_instruction,
6129 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
6130 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
6131 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
6132 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
6133 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
6134 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
6135 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
6136 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
6137 [EXIT_REASON_GDTR_IDTR] = handle_desc,
6138 [EXIT_REASON_LDTR_TR] = handle_desc,
6139 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
6140 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
6141 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
6142 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait,
6143 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
6144 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor,
6145 [EXIT_REASON_INVEPT] = handle_vmx_instruction,
6146 [EXIT_REASON_INVVPID] = handle_vmx_instruction,
6147 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op,
6148 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op,
6149 [EXIT_REASON_PML_FULL] = handle_pml_full,
6150 [EXIT_REASON_INVPCID] = handle_invpcid,
6151 [EXIT_REASON_VMFUNC] = handle_vmx_instruction,
6152 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
6153 [EXIT_REASON_ENCLS] = handle_encls,
6154 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit,
6155 [EXIT_REASON_NOTIFY] = handle_notify,
6156 };
6157
6158 static const int kvm_vmx_max_exit_handlers =
6159 ARRAY_SIZE(kvm_vmx_exit_handlers);
6160
vmx_get_exit_info(struct kvm_vcpu * vcpu,u32 * reason,u64 * info1,u64 * info2,u32 * intr_info,u32 * error_code)6161 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
6162 u64 *info1, u64 *info2,
6163 u32 *intr_info, u32 *error_code)
6164 {
6165 struct vcpu_vmx *vmx = to_vmx(vcpu);
6166
6167 *reason = vmx->exit_reason.full;
6168 *info1 = vmx_get_exit_qual(vcpu);
6169 if (!(vmx->exit_reason.failed_vmentry)) {
6170 *info2 = vmx->idt_vectoring_info;
6171 *intr_info = vmx_get_intr_info(vcpu);
6172 if (is_exception_with_error_code(*intr_info))
6173 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6174 else
6175 *error_code = 0;
6176 } else {
6177 *info2 = 0;
6178 *intr_info = 0;
6179 *error_code = 0;
6180 }
6181 }
6182
vmx_destroy_pml_buffer(struct vcpu_vmx * vmx)6183 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
6184 {
6185 if (vmx->pml_pg) {
6186 __free_page(vmx->pml_pg);
6187 vmx->pml_pg = NULL;
6188 }
6189 }
6190
vmx_flush_pml_buffer(struct kvm_vcpu * vcpu)6191 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
6192 {
6193 struct vcpu_vmx *vmx = to_vmx(vcpu);
6194 u64 *pml_buf;
6195 u16 pml_idx;
6196
6197 pml_idx = vmcs_read16(GUEST_PML_INDEX);
6198
6199 /* Do nothing if PML buffer is empty */
6200 if (pml_idx == (PML_ENTITY_NUM - 1))
6201 return;
6202
6203 /* PML index always points to next available PML buffer entity */
6204 if (pml_idx >= PML_ENTITY_NUM)
6205 pml_idx = 0;
6206 else
6207 pml_idx++;
6208
6209 pml_buf = page_address(vmx->pml_pg);
6210 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
6211 u64 gpa;
6212
6213 gpa = pml_buf[pml_idx];
6214 WARN_ON(gpa & (PAGE_SIZE - 1));
6215 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
6216 }
6217
6218 /* reset PML index */
6219 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6220 }
6221
vmx_dump_sel(char * name,uint32_t sel)6222 static void vmx_dump_sel(char *name, uint32_t sel)
6223 {
6224 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
6225 name, vmcs_read16(sel),
6226 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
6227 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
6228 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
6229 }
6230
vmx_dump_dtsel(char * name,uint32_t limit)6231 static void vmx_dump_dtsel(char *name, uint32_t limit)
6232 {
6233 pr_err("%s limit=0x%08x, base=0x%016lx\n",
6234 name, vmcs_read32(limit),
6235 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
6236 }
6237
vmx_dump_msrs(char * name,struct vmx_msrs * m)6238 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
6239 {
6240 unsigned int i;
6241 struct vmx_msr_entry *e;
6242
6243 pr_err("MSR %s:\n", name);
6244 for (i = 0, e = m->val; i < m->nr; ++i, ++e)
6245 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
6246 }
6247
dump_vmcs(struct kvm_vcpu * vcpu)6248 void dump_vmcs(struct kvm_vcpu *vcpu)
6249 {
6250 struct vcpu_vmx *vmx = to_vmx(vcpu);
6251 u32 vmentry_ctl, vmexit_ctl;
6252 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
6253 u64 tertiary_exec_control;
6254 unsigned long cr4;
6255 int efer_slot;
6256
6257 if (!dump_invalid_vmcs) {
6258 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
6259 return;
6260 }
6261
6262 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
6263 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
6264 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6265 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
6266 cr4 = vmcs_readl(GUEST_CR4);
6267
6268 if (cpu_has_secondary_exec_ctrls())
6269 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6270 else
6271 secondary_exec_control = 0;
6272
6273 if (cpu_has_tertiary_exec_ctrls())
6274 tertiary_exec_control = vmcs_read64(TERTIARY_VM_EXEC_CONTROL);
6275 else
6276 tertiary_exec_control = 0;
6277
6278 pr_err("VMCS %p, last attempted VM-entry on CPU %d\n",
6279 vmx->loaded_vmcs->vmcs, vcpu->arch.last_vmentry_cpu);
6280 pr_err("*** Guest State ***\n");
6281 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6282 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
6283 vmcs_readl(CR0_GUEST_HOST_MASK));
6284 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6285 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
6286 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
6287 if (cpu_has_vmx_ept()) {
6288 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
6289 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
6290 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
6291 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
6292 }
6293 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
6294 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
6295 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
6296 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
6297 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6298 vmcs_readl(GUEST_SYSENTER_ESP),
6299 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
6300 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
6301 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
6302 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
6303 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
6304 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
6305 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
6306 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
6307 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
6308 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
6309 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
6310 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
6311 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
6312 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
6313 else if (efer_slot >= 0)
6314 pr_err("EFER= 0x%016llx (autoload)\n",
6315 vmx->msr_autoload.guest.val[efer_slot].value);
6316 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
6317 pr_err("EFER= 0x%016llx (effective)\n",
6318 vcpu->arch.efer | (EFER_LMA | EFER_LME));
6319 else
6320 pr_err("EFER= 0x%016llx (effective)\n",
6321 vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
6322 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
6323 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
6324 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
6325 vmcs_read64(GUEST_IA32_DEBUGCTL),
6326 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
6327 if (cpu_has_load_perf_global_ctrl() &&
6328 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
6329 pr_err("PerfGlobCtl = 0x%016llx\n",
6330 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
6331 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
6332 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
6333 pr_err("Interruptibility = %08x ActivityState = %08x\n",
6334 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
6335 vmcs_read32(GUEST_ACTIVITY_STATE));
6336 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
6337 pr_err("InterruptStatus = %04x\n",
6338 vmcs_read16(GUEST_INTR_STATUS));
6339 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
6340 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
6341 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
6342 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
6343
6344 pr_err("*** Host State ***\n");
6345 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
6346 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
6347 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
6348 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
6349 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
6350 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
6351 vmcs_read16(HOST_TR_SELECTOR));
6352 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
6353 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
6354 vmcs_readl(HOST_TR_BASE));
6355 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
6356 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
6357 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
6358 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
6359 vmcs_readl(HOST_CR4));
6360 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6361 vmcs_readl(HOST_IA32_SYSENTER_ESP),
6362 vmcs_read32(HOST_IA32_SYSENTER_CS),
6363 vmcs_readl(HOST_IA32_SYSENTER_EIP));
6364 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
6365 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
6366 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
6367 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
6368 if (cpu_has_load_perf_global_ctrl() &&
6369 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
6370 pr_err("PerfGlobCtl = 0x%016llx\n",
6371 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
6372 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
6373 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
6374
6375 pr_err("*** Control State ***\n");
6376 pr_err("CPUBased=0x%08x SecondaryExec=0x%08x TertiaryExec=0x%016llx\n",
6377 cpu_based_exec_ctrl, secondary_exec_control, tertiary_exec_control);
6378 pr_err("PinBased=0x%08x EntryControls=%08x ExitControls=%08x\n",
6379 pin_based_exec_ctrl, vmentry_ctl, vmexit_ctl);
6380 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
6381 vmcs_read32(EXCEPTION_BITMAP),
6382 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
6383 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
6384 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
6385 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6386 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
6387 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
6388 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
6389 vmcs_read32(VM_EXIT_INTR_INFO),
6390 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
6391 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
6392 pr_err(" reason=%08x qualification=%016lx\n",
6393 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
6394 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
6395 vmcs_read32(IDT_VECTORING_INFO_FIELD),
6396 vmcs_read32(IDT_VECTORING_ERROR_CODE));
6397 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
6398 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
6399 pr_err("TSC Multiplier = 0x%016llx\n",
6400 vmcs_read64(TSC_MULTIPLIER));
6401 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
6402 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
6403 u16 status = vmcs_read16(GUEST_INTR_STATUS);
6404 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
6405 }
6406 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
6407 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
6408 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
6409 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
6410 }
6411 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
6412 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
6413 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
6414 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
6415 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
6416 pr_err("PLE Gap=%08x Window=%08x\n",
6417 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
6418 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
6419 pr_err("Virtual processor ID = 0x%04x\n",
6420 vmcs_read16(VIRTUAL_PROCESSOR_ID));
6421 }
6422
6423 /*
6424 * The guest has exited. See if we can fix it or if we need userspace
6425 * assistance.
6426 */
__vmx_handle_exit(struct kvm_vcpu * vcpu,fastpath_t exit_fastpath)6427 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6428 {
6429 struct vcpu_vmx *vmx = to_vmx(vcpu);
6430 union vmx_exit_reason exit_reason = vmx->exit_reason;
6431 u32 vectoring_info = vmx->idt_vectoring_info;
6432 u16 exit_handler_index;
6433
6434 /*
6435 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
6436 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
6437 * querying dirty_bitmap, we only need to kick all vcpus out of guest
6438 * mode as if vcpus is in root mode, the PML buffer must has been
6439 * flushed already. Note, PML is never enabled in hardware while
6440 * running L2.
6441 */
6442 if (enable_pml && !is_guest_mode(vcpu))
6443 vmx_flush_pml_buffer(vcpu);
6444
6445 /*
6446 * KVM should never reach this point with a pending nested VM-Enter.
6447 * More specifically, short-circuiting VM-Entry to emulate L2 due to
6448 * invalid guest state should never happen as that means KVM knowingly
6449 * allowed a nested VM-Enter with an invalid vmcs12. More below.
6450 */
6451 if (KVM_BUG_ON(vmx->nested.nested_run_pending, vcpu->kvm))
6452 return -EIO;
6453
6454 if (is_guest_mode(vcpu)) {
6455 /*
6456 * PML is never enabled when running L2, bail immediately if a
6457 * PML full exit occurs as something is horribly wrong.
6458 */
6459 if (exit_reason.basic == EXIT_REASON_PML_FULL)
6460 goto unexpected_vmexit;
6461
6462 /*
6463 * The host physical addresses of some pages of guest memory
6464 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6465 * Page). The CPU may write to these pages via their host
6466 * physical address while L2 is running, bypassing any
6467 * address-translation-based dirty tracking (e.g. EPT write
6468 * protection).
6469 *
6470 * Mark them dirty on every exit from L2 to prevent them from
6471 * getting out of sync with dirty tracking.
6472 */
6473 nested_mark_vmcs12_pages_dirty(vcpu);
6474
6475 /*
6476 * Synthesize a triple fault if L2 state is invalid. In normal
6477 * operation, nested VM-Enter rejects any attempt to enter L2
6478 * with invalid state. However, those checks are skipped if
6479 * state is being stuffed via RSM or KVM_SET_NESTED_STATE. If
6480 * L2 state is invalid, it means either L1 modified SMRAM state
6481 * or userspace provided bad state. Synthesize TRIPLE_FAULT as
6482 * doing so is architecturally allowed in the RSM case, and is
6483 * the least awful solution for the userspace case without
6484 * risking false positives.
6485 */
6486 if (vmx->emulation_required) {
6487 nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
6488 return 1;
6489 }
6490
6491 if (nested_vmx_reflect_vmexit(vcpu))
6492 return 1;
6493 }
6494
6495 /* If guest state is invalid, start emulating. L2 is handled above. */
6496 if (vmx->emulation_required)
6497 return handle_invalid_guest_state(vcpu);
6498
6499 if (exit_reason.failed_vmentry) {
6500 dump_vmcs(vcpu);
6501 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6502 vcpu->run->fail_entry.hardware_entry_failure_reason
6503 = exit_reason.full;
6504 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6505 return 0;
6506 }
6507
6508 if (unlikely(vmx->fail)) {
6509 dump_vmcs(vcpu);
6510 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6511 vcpu->run->fail_entry.hardware_entry_failure_reason
6512 = vmcs_read32(VM_INSTRUCTION_ERROR);
6513 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6514 return 0;
6515 }
6516
6517 /*
6518 * Note:
6519 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6520 * delivery event since it indicates guest is accessing MMIO.
6521 * The vm-exit can be triggered again after return to guest that
6522 * will cause infinite loop.
6523 */
6524 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6525 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6526 exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6527 exit_reason.basic != EXIT_REASON_PML_FULL &&
6528 exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6529 exit_reason.basic != EXIT_REASON_TASK_SWITCH &&
6530 exit_reason.basic != EXIT_REASON_NOTIFY)) {
6531 int ndata = 3;
6532
6533 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6534 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6535 vcpu->run->internal.data[0] = vectoring_info;
6536 vcpu->run->internal.data[1] = exit_reason.full;
6537 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6538 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6539 vcpu->run->internal.data[ndata++] =
6540 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6541 }
6542 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6543 vcpu->run->internal.ndata = ndata;
6544 return 0;
6545 }
6546
6547 if (unlikely(!enable_vnmi &&
6548 vmx->loaded_vmcs->soft_vnmi_blocked)) {
6549 if (!vmx_interrupt_blocked(vcpu)) {
6550 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6551 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6552 vcpu->arch.nmi_pending) {
6553 /*
6554 * This CPU don't support us in finding the end of an
6555 * NMI-blocked window if the guest runs with IRQs
6556 * disabled. So we pull the trigger after 1 s of
6557 * futile waiting, but inform the user about this.
6558 */
6559 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6560 "state on VCPU %d after 1 s timeout\n",
6561 __func__, vcpu->vcpu_id);
6562 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6563 }
6564 }
6565
6566 if (exit_fastpath != EXIT_FASTPATH_NONE)
6567 return 1;
6568
6569 if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6570 goto unexpected_vmexit;
6571 #ifdef CONFIG_RETPOLINE
6572 if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6573 return kvm_emulate_wrmsr(vcpu);
6574 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6575 return handle_preemption_timer(vcpu);
6576 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6577 return handle_interrupt_window(vcpu);
6578 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6579 return handle_external_interrupt(vcpu);
6580 else if (exit_reason.basic == EXIT_REASON_HLT)
6581 return kvm_emulate_halt(vcpu);
6582 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6583 return handle_ept_misconfig(vcpu);
6584 #endif
6585
6586 exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6587 kvm_vmx_max_exit_handlers);
6588 if (!kvm_vmx_exit_handlers[exit_handler_index])
6589 goto unexpected_vmexit;
6590
6591 return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6592
6593 unexpected_vmexit:
6594 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6595 exit_reason.full);
6596 dump_vmcs(vcpu);
6597 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6598 vcpu->run->internal.suberror =
6599 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6600 vcpu->run->internal.ndata = 2;
6601 vcpu->run->internal.data[0] = exit_reason.full;
6602 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6603 return 0;
6604 }
6605
vmx_handle_exit(struct kvm_vcpu * vcpu,fastpath_t exit_fastpath)6606 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6607 {
6608 int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6609
6610 /*
6611 * Exit to user space when bus lock detected to inform that there is
6612 * a bus lock in guest.
6613 */
6614 if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6615 if (ret > 0)
6616 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6617
6618 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6619 return 0;
6620 }
6621 return ret;
6622 }
6623
6624 /*
6625 * Software based L1D cache flush which is used when microcode providing
6626 * the cache control MSR is not loaded.
6627 *
6628 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6629 * flush it is required to read in 64 KiB because the replacement algorithm
6630 * is not exactly LRU. This could be sized at runtime via topology
6631 * information but as all relevant affected CPUs have 32KiB L1D cache size
6632 * there is no point in doing so.
6633 */
vmx_l1d_flush(struct kvm_vcpu * vcpu)6634 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6635 {
6636 int size = PAGE_SIZE << L1D_CACHE_ORDER;
6637
6638 /*
6639 * This code is only executed when the flush mode is 'cond' or
6640 * 'always'
6641 */
6642 if (static_branch_likely(&vmx_l1d_flush_cond)) {
6643 bool flush_l1d;
6644
6645 /*
6646 * Clear the per-vcpu flush bit, it gets set again
6647 * either from vcpu_run() or from one of the unsafe
6648 * VMEXIT handlers.
6649 */
6650 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6651 vcpu->arch.l1tf_flush_l1d = false;
6652
6653 /*
6654 * Clear the per-cpu flush bit, it gets set again from
6655 * the interrupt handlers.
6656 */
6657 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6658 kvm_clear_cpu_l1tf_flush_l1d();
6659
6660 if (!flush_l1d)
6661 return;
6662 }
6663
6664 vcpu->stat.l1d_flush++;
6665
6666 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6667 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6668 return;
6669 }
6670
6671 asm volatile(
6672 /* First ensure the pages are in the TLB */
6673 "xorl %%eax, %%eax\n"
6674 ".Lpopulate_tlb:\n\t"
6675 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6676 "addl $4096, %%eax\n\t"
6677 "cmpl %%eax, %[size]\n\t"
6678 "jne .Lpopulate_tlb\n\t"
6679 "xorl %%eax, %%eax\n\t"
6680 "cpuid\n\t"
6681 /* Now fill the cache */
6682 "xorl %%eax, %%eax\n"
6683 ".Lfill_cache:\n"
6684 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6685 "addl $64, %%eax\n\t"
6686 "cmpl %%eax, %[size]\n\t"
6687 "jne .Lfill_cache\n\t"
6688 "lfence\n"
6689 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6690 [size] "r" (size)
6691 : "eax", "ebx", "ecx", "edx");
6692 }
6693
vmx_update_cr8_intercept(struct kvm_vcpu * vcpu,int tpr,int irr)6694 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6695 {
6696 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6697 int tpr_threshold;
6698
6699 if (is_guest_mode(vcpu) &&
6700 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6701 return;
6702
6703 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6704 if (is_guest_mode(vcpu))
6705 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6706 else
6707 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6708 }
6709
vmx_set_virtual_apic_mode(struct kvm_vcpu * vcpu)6710 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6711 {
6712 struct vcpu_vmx *vmx = to_vmx(vcpu);
6713 u32 sec_exec_control;
6714
6715 if (!lapic_in_kernel(vcpu))
6716 return;
6717
6718 if (!flexpriority_enabled &&
6719 !cpu_has_vmx_virtualize_x2apic_mode())
6720 return;
6721
6722 /* Postpone execution until vmcs01 is the current VMCS. */
6723 if (is_guest_mode(vcpu)) {
6724 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6725 return;
6726 }
6727
6728 sec_exec_control = secondary_exec_controls_get(vmx);
6729 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6730 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6731
6732 switch (kvm_get_apic_mode(vcpu)) {
6733 case LAPIC_MODE_INVALID:
6734 WARN_ONCE(true, "Invalid local APIC state");
6735 break;
6736 case LAPIC_MODE_DISABLED:
6737 break;
6738 case LAPIC_MODE_XAPIC:
6739 if (flexpriority_enabled) {
6740 sec_exec_control |=
6741 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6742 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6743
6744 /*
6745 * Flush the TLB, reloading the APIC access page will
6746 * only do so if its physical address has changed, but
6747 * the guest may have inserted a non-APIC mapping into
6748 * the TLB while the APIC access page was disabled.
6749 */
6750 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6751 }
6752 break;
6753 case LAPIC_MODE_X2APIC:
6754 if (cpu_has_vmx_virtualize_x2apic_mode())
6755 sec_exec_control |=
6756 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6757 break;
6758 }
6759 secondary_exec_controls_set(vmx, sec_exec_control);
6760
6761 vmx_update_msr_bitmap_x2apic(vcpu);
6762 }
6763
vmx_set_apic_access_page_addr(struct kvm_vcpu * vcpu)6764 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6765 {
6766 const gfn_t gfn = APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT;
6767 struct kvm *kvm = vcpu->kvm;
6768 struct kvm_memslots *slots = kvm_memslots(kvm);
6769 struct kvm_memory_slot *slot;
6770 unsigned long mmu_seq;
6771 kvm_pfn_t pfn;
6772
6773 /* Defer reload until vmcs01 is the current VMCS. */
6774 if (is_guest_mode(vcpu)) {
6775 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6776 return;
6777 }
6778
6779 if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6780 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6781 return;
6782
6783 /*
6784 * Grab the memslot so that the hva lookup for the mmu_notifier retry
6785 * is guaranteed to use the same memslot as the pfn lookup, i.e. rely
6786 * on the pfn lookup's validation of the memslot to ensure a valid hva
6787 * is used for the retry check.
6788 */
6789 slot = id_to_memslot(slots, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT);
6790 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
6791 return;
6792
6793 /*
6794 * Ensure that the mmu_notifier sequence count is read before KVM
6795 * retrieves the pfn from the primary MMU. Note, the memslot is
6796 * protected by SRCU, not the mmu_notifier. Pairs with the smp_wmb()
6797 * in kvm_mmu_invalidate_end().
6798 */
6799 mmu_seq = kvm->mmu_invalidate_seq;
6800 smp_rmb();
6801
6802 /*
6803 * No need to retry if the memslot does not exist or is invalid. KVM
6804 * controls the APIC-access page memslot, and only deletes the memslot
6805 * if APICv is permanently inhibited, i.e. the memslot won't reappear.
6806 */
6807 pfn = gfn_to_pfn_memslot(slot, gfn);
6808 if (is_error_noslot_pfn(pfn))
6809 return;
6810
6811 read_lock(&vcpu->kvm->mmu_lock);
6812 if (mmu_invalidate_retry_hva(kvm, mmu_seq,
6813 gfn_to_hva_memslot(slot, gfn))) {
6814 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6815 read_unlock(&vcpu->kvm->mmu_lock);
6816 goto out;
6817 }
6818
6819 vmcs_write64(APIC_ACCESS_ADDR, pfn_to_hpa(pfn));
6820 read_unlock(&vcpu->kvm->mmu_lock);
6821
6822 /*
6823 * No need for a manual TLB flush at this point, KVM has already done a
6824 * flush if there were SPTEs pointing at the previous page.
6825 */
6826 out:
6827 /*
6828 * Do not pin apic access page in memory, the MMU notifier
6829 * will call us again if it is migrated or swapped out.
6830 */
6831 kvm_release_pfn_clean(pfn);
6832 }
6833
vmx_hwapic_isr_update(int max_isr)6834 static void vmx_hwapic_isr_update(int max_isr)
6835 {
6836 u16 status;
6837 u8 old;
6838
6839 if (max_isr == -1)
6840 max_isr = 0;
6841
6842 status = vmcs_read16(GUEST_INTR_STATUS);
6843 old = status >> 8;
6844 if (max_isr != old) {
6845 status &= 0xff;
6846 status |= max_isr << 8;
6847 vmcs_write16(GUEST_INTR_STATUS, status);
6848 }
6849 }
6850
vmx_set_rvi(int vector)6851 static void vmx_set_rvi(int vector)
6852 {
6853 u16 status;
6854 u8 old;
6855
6856 if (vector == -1)
6857 vector = 0;
6858
6859 status = vmcs_read16(GUEST_INTR_STATUS);
6860 old = (u8)status & 0xff;
6861 if ((u8)vector != old) {
6862 status &= ~0xff;
6863 status |= (u8)vector;
6864 vmcs_write16(GUEST_INTR_STATUS, status);
6865 }
6866 }
6867
vmx_hwapic_irr_update(struct kvm_vcpu * vcpu,int max_irr)6868 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6869 {
6870 /*
6871 * When running L2, updating RVI is only relevant when
6872 * vmcs12 virtual-interrupt-delivery enabled.
6873 * However, it can be enabled only when L1 also
6874 * intercepts external-interrupts and in that case
6875 * we should not update vmcs02 RVI but instead intercept
6876 * interrupt. Therefore, do nothing when running L2.
6877 */
6878 if (!is_guest_mode(vcpu))
6879 vmx_set_rvi(max_irr);
6880 }
6881
vmx_sync_pir_to_irr(struct kvm_vcpu * vcpu)6882 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6883 {
6884 struct vcpu_vmx *vmx = to_vmx(vcpu);
6885 int max_irr;
6886 bool got_posted_interrupt;
6887
6888 if (KVM_BUG_ON(!enable_apicv, vcpu->kvm))
6889 return -EIO;
6890
6891 if (pi_test_on(&vmx->pi_desc)) {
6892 pi_clear_on(&vmx->pi_desc);
6893 /*
6894 * IOMMU can write to PID.ON, so the barrier matters even on UP.
6895 * But on x86 this is just a compiler barrier anyway.
6896 */
6897 smp_mb__after_atomic();
6898 got_posted_interrupt =
6899 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6900 } else {
6901 max_irr = kvm_lapic_find_highest_irr(vcpu);
6902 got_posted_interrupt = false;
6903 }
6904
6905 /*
6906 * Newly recognized interrupts are injected via either virtual interrupt
6907 * delivery (RVI) or KVM_REQ_EVENT. Virtual interrupt delivery is
6908 * disabled in two cases:
6909 *
6910 * 1) If L2 is running and the vCPU has a new pending interrupt. If L1
6911 * wants to exit on interrupts, KVM_REQ_EVENT is needed to synthesize a
6912 * VM-Exit to L1. If L1 doesn't want to exit, the interrupt is injected
6913 * into L2, but KVM doesn't use virtual interrupt delivery to inject
6914 * interrupts into L2, and so KVM_REQ_EVENT is again needed.
6915 *
6916 * 2) If APICv is disabled for this vCPU, assigned devices may still
6917 * attempt to post interrupts. The posted interrupt vector will cause
6918 * a VM-Exit and the subsequent entry will call sync_pir_to_irr.
6919 */
6920 if (!is_guest_mode(vcpu) && kvm_vcpu_apicv_active(vcpu))
6921 vmx_set_rvi(max_irr);
6922 else if (got_posted_interrupt)
6923 kvm_make_request(KVM_REQ_EVENT, vcpu);
6924
6925 return max_irr;
6926 }
6927
vmx_load_eoi_exitmap(struct kvm_vcpu * vcpu,u64 * eoi_exit_bitmap)6928 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6929 {
6930 if (!kvm_vcpu_apicv_active(vcpu))
6931 return;
6932
6933 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6934 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6935 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6936 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6937 }
6938
vmx_apicv_pre_state_restore(struct kvm_vcpu * vcpu)6939 static void vmx_apicv_pre_state_restore(struct kvm_vcpu *vcpu)
6940 {
6941 struct vcpu_vmx *vmx = to_vmx(vcpu);
6942
6943 pi_clear_on(&vmx->pi_desc);
6944 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6945 }
6946
6947 void vmx_do_interrupt_irqoff(unsigned long entry);
6948 void vmx_do_nmi_irqoff(void);
6949
handle_nm_fault_irqoff(struct kvm_vcpu * vcpu)6950 static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
6951 {
6952 /*
6953 * Save xfd_err to guest_fpu before interrupt is enabled, so the
6954 * MSR value is not clobbered by the host activity before the guest
6955 * has chance to consume it.
6956 *
6957 * Do not blindly read xfd_err here, since this exception might
6958 * be caused by L1 interception on a platform which doesn't
6959 * support xfd at all.
6960 *
6961 * Do it conditionally upon guest_fpu::xfd. xfd_err matters
6962 * only when xfd contains a non-zero value.
6963 *
6964 * Queuing exception is done in vmx_handle_exit. See comment there.
6965 */
6966 if (vcpu->arch.guest_fpu.fpstate->xfd)
6967 rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
6968 }
6969
handle_exception_irqoff(struct vcpu_vmx * vmx)6970 static void handle_exception_irqoff(struct vcpu_vmx *vmx)
6971 {
6972 u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6973
6974 /* if exit due to PF check for async PF */
6975 if (is_page_fault(intr_info))
6976 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6977 /* if exit due to NM, handle before interrupts are enabled */
6978 else if (is_nm_fault(intr_info))
6979 handle_nm_fault_irqoff(&vmx->vcpu);
6980 /* Handle machine checks before interrupts are enabled */
6981 else if (is_machine_check(intr_info))
6982 kvm_machine_check();
6983 }
6984
handle_external_interrupt_irqoff(struct kvm_vcpu * vcpu)6985 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6986 {
6987 u32 intr_info = vmx_get_intr_info(vcpu);
6988 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6989 gate_desc *desc = (gate_desc *)host_idt_base + vector;
6990
6991 if (KVM_BUG(!is_external_intr(intr_info), vcpu->kvm,
6992 "unexpected VM-Exit interrupt info: 0x%x", intr_info))
6993 return;
6994
6995 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
6996 vmx_do_interrupt_irqoff(gate_offset(desc));
6997 kvm_after_interrupt(vcpu);
6998
6999 vcpu->arch.at_instruction_boundary = true;
7000 }
7001
vmx_handle_exit_irqoff(struct kvm_vcpu * vcpu)7002 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
7003 {
7004 struct vcpu_vmx *vmx = to_vmx(vcpu);
7005
7006 if (vmx->emulation_required)
7007 return;
7008
7009 if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
7010 handle_external_interrupt_irqoff(vcpu);
7011 else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
7012 handle_exception_irqoff(vmx);
7013 }
7014
7015 /*
7016 * The kvm parameter can be NULL (module initialization, or invocation before
7017 * VM creation). Be sure to check the kvm parameter before using it.
7018 */
vmx_has_emulated_msr(struct kvm * kvm,u32 index)7019 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
7020 {
7021 switch (index) {
7022 case MSR_IA32_SMBASE:
7023 if (!IS_ENABLED(CONFIG_KVM_SMM))
7024 return false;
7025 /*
7026 * We cannot do SMM unless we can run the guest in big
7027 * real mode.
7028 */
7029 return enable_unrestricted_guest || emulate_invalid_guest_state;
7030 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR:
7031 return nested;
7032 case MSR_AMD64_VIRT_SPEC_CTRL:
7033 case MSR_AMD64_TSC_RATIO:
7034 /* This is AMD only. */
7035 return false;
7036 default:
7037 return true;
7038 }
7039 }
7040
vmx_recover_nmi_blocking(struct vcpu_vmx * vmx)7041 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
7042 {
7043 u32 exit_intr_info;
7044 bool unblock_nmi;
7045 u8 vector;
7046 bool idtv_info_valid;
7047
7048 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
7049
7050 if (enable_vnmi) {
7051 if (vmx->loaded_vmcs->nmi_known_unmasked)
7052 return;
7053
7054 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
7055 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
7056 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
7057 /*
7058 * SDM 3: 27.7.1.2 (September 2008)
7059 * Re-set bit "block by NMI" before VM entry if vmexit caused by
7060 * a guest IRET fault.
7061 * SDM 3: 23.2.2 (September 2008)
7062 * Bit 12 is undefined in any of the following cases:
7063 * If the VM exit sets the valid bit in the IDT-vectoring
7064 * information field.
7065 * If the VM exit is due to a double fault.
7066 */
7067 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
7068 vector != DF_VECTOR && !idtv_info_valid)
7069 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
7070 GUEST_INTR_STATE_NMI);
7071 else
7072 vmx->loaded_vmcs->nmi_known_unmasked =
7073 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
7074 & GUEST_INTR_STATE_NMI);
7075 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
7076 vmx->loaded_vmcs->vnmi_blocked_time +=
7077 ktime_to_ns(ktime_sub(ktime_get(),
7078 vmx->loaded_vmcs->entry_time));
7079 }
7080
__vmx_complete_interrupts(struct kvm_vcpu * vcpu,u32 idt_vectoring_info,int instr_len_field,int error_code_field)7081 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
7082 u32 idt_vectoring_info,
7083 int instr_len_field,
7084 int error_code_field)
7085 {
7086 u8 vector;
7087 int type;
7088 bool idtv_info_valid;
7089
7090 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
7091
7092 vcpu->arch.nmi_injected = false;
7093 kvm_clear_exception_queue(vcpu);
7094 kvm_clear_interrupt_queue(vcpu);
7095
7096 if (!idtv_info_valid)
7097 return;
7098
7099 kvm_make_request(KVM_REQ_EVENT, vcpu);
7100
7101 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
7102 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
7103
7104 switch (type) {
7105 case INTR_TYPE_NMI_INTR:
7106 vcpu->arch.nmi_injected = true;
7107 /*
7108 * SDM 3: 27.7.1.2 (September 2008)
7109 * Clear bit "block by NMI" before VM entry if a NMI
7110 * delivery faulted.
7111 */
7112 vmx_set_nmi_mask(vcpu, false);
7113 break;
7114 case INTR_TYPE_SOFT_EXCEPTION:
7115 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
7116 fallthrough;
7117 case INTR_TYPE_HARD_EXCEPTION:
7118 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
7119 u32 err = vmcs_read32(error_code_field);
7120 kvm_requeue_exception_e(vcpu, vector, err);
7121 } else
7122 kvm_requeue_exception(vcpu, vector);
7123 break;
7124 case INTR_TYPE_SOFT_INTR:
7125 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
7126 fallthrough;
7127 case INTR_TYPE_EXT_INTR:
7128 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
7129 break;
7130 default:
7131 break;
7132 }
7133 }
7134
vmx_complete_interrupts(struct vcpu_vmx * vmx)7135 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
7136 {
7137 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
7138 VM_EXIT_INSTRUCTION_LEN,
7139 IDT_VECTORING_ERROR_CODE);
7140 }
7141
vmx_cancel_injection(struct kvm_vcpu * vcpu)7142 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
7143 {
7144 __vmx_complete_interrupts(vcpu,
7145 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
7146 VM_ENTRY_INSTRUCTION_LEN,
7147 VM_ENTRY_EXCEPTION_ERROR_CODE);
7148
7149 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
7150 }
7151
atomic_switch_perf_msrs(struct vcpu_vmx * vmx)7152 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
7153 {
7154 int i, nr_msrs;
7155 struct perf_guest_switch_msr *msrs;
7156 struct kvm_pmu *pmu = vcpu_to_pmu(&vmx->vcpu);
7157
7158 pmu->host_cross_mapped_mask = 0;
7159 if (pmu->pebs_enable & pmu->global_ctrl)
7160 intel_pmu_cross_mapped_check(pmu);
7161
7162 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
7163 msrs = perf_guest_get_msrs(&nr_msrs, (void *)pmu);
7164 if (!msrs)
7165 return;
7166
7167 for (i = 0; i < nr_msrs; i++)
7168 if (msrs[i].host == msrs[i].guest)
7169 clear_atomic_switch_msr(vmx, msrs[i].msr);
7170 else
7171 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
7172 msrs[i].host, false);
7173 }
7174
vmx_update_hv_timer(struct kvm_vcpu * vcpu)7175 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
7176 {
7177 struct vcpu_vmx *vmx = to_vmx(vcpu);
7178 u64 tscl;
7179 u32 delta_tsc;
7180
7181 if (vmx->req_immediate_exit) {
7182 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
7183 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
7184 } else if (vmx->hv_deadline_tsc != -1) {
7185 tscl = rdtsc();
7186 if (vmx->hv_deadline_tsc > tscl)
7187 /* set_hv_timer ensures the delta fits in 32-bits */
7188 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
7189 cpu_preemption_timer_multi);
7190 else
7191 delta_tsc = 0;
7192
7193 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
7194 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
7195 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
7196 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
7197 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
7198 }
7199 }
7200
vmx_update_host_rsp(struct vcpu_vmx * vmx,unsigned long host_rsp)7201 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
7202 {
7203 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
7204 vmx->loaded_vmcs->host_state.rsp = host_rsp;
7205 vmcs_writel(HOST_RSP, host_rsp);
7206 }
7207 }
7208
vmx_spec_ctrl_restore_host(struct vcpu_vmx * vmx,unsigned int flags)7209 void noinstr vmx_spec_ctrl_restore_host(struct vcpu_vmx *vmx,
7210 unsigned int flags)
7211 {
7212 u64 hostval = this_cpu_read(x86_spec_ctrl_current);
7213
7214 if (!cpu_feature_enabled(X86_FEATURE_MSR_SPEC_CTRL))
7215 return;
7216
7217 if (flags & VMX_RUN_SAVE_SPEC_CTRL)
7218 vmx->spec_ctrl = __rdmsr(MSR_IA32_SPEC_CTRL);
7219
7220 /*
7221 * If the guest/host SPEC_CTRL values differ, restore the host value.
7222 *
7223 * For legacy IBRS, the IBRS bit always needs to be written after
7224 * transitioning from a less privileged predictor mode, regardless of
7225 * whether the guest/host values differ.
7226 */
7227 if (cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS) ||
7228 vmx->spec_ctrl != hostval)
7229 native_wrmsrl(MSR_IA32_SPEC_CTRL, hostval);
7230
7231 barrier_nospec();
7232 }
7233
vmx_exit_handlers_fastpath(struct kvm_vcpu * vcpu)7234 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
7235 {
7236 switch (to_vmx(vcpu)->exit_reason.basic) {
7237 case EXIT_REASON_MSR_WRITE:
7238 return handle_fastpath_set_msr_irqoff(vcpu);
7239 case EXIT_REASON_PREEMPTION_TIMER:
7240 return handle_fastpath_preemption_timer(vcpu);
7241 default:
7242 return EXIT_FASTPATH_NONE;
7243 }
7244 }
7245
vmx_vcpu_enter_exit(struct kvm_vcpu * vcpu,unsigned int flags)7246 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
7247 unsigned int flags)
7248 {
7249 struct vcpu_vmx *vmx = to_vmx(vcpu);
7250
7251 guest_state_enter_irqoff();
7252
7253 /*
7254 * L1D Flush includes CPU buffer clear to mitigate MDS, but VERW
7255 * mitigation for MDS is done late in VMentry and is still
7256 * executed in spite of L1D Flush. This is because an extra VERW
7257 * should not matter much after the big hammer L1D Flush.
7258 */
7259 if (static_branch_unlikely(&vmx_l1d_should_flush))
7260 vmx_l1d_flush(vcpu);
7261 else if (static_branch_unlikely(&mmio_stale_data_clear) &&
7262 kvm_arch_has_assigned_device(vcpu->kvm))
7263 mds_clear_cpu_buffers();
7264
7265 vmx_disable_fb_clear(vmx);
7266
7267 if (vcpu->arch.cr2 != native_read_cr2())
7268 native_write_cr2(vcpu->arch.cr2);
7269
7270 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
7271 flags);
7272
7273 vcpu->arch.cr2 = native_read_cr2();
7274 vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
7275
7276 vmx->idt_vectoring_info = 0;
7277
7278 vmx_enable_fb_clear(vmx);
7279
7280 if (unlikely(vmx->fail)) {
7281 vmx->exit_reason.full = 0xdead;
7282 goto out;
7283 }
7284
7285 vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
7286 if (likely(!vmx->exit_reason.failed_vmentry))
7287 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
7288
7289 if ((u16)vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI &&
7290 is_nmi(vmx_get_intr_info(vcpu))) {
7291 kvm_before_interrupt(vcpu, KVM_HANDLING_NMI);
7292 vmx_do_nmi_irqoff();
7293 kvm_after_interrupt(vcpu);
7294 }
7295
7296 out:
7297 guest_state_exit_irqoff();
7298 }
7299
vmx_vcpu_run(struct kvm_vcpu * vcpu)7300 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
7301 {
7302 struct vcpu_vmx *vmx = to_vmx(vcpu);
7303 unsigned long cr3, cr4;
7304
7305 /* Record the guest's net vcpu time for enforced NMI injections. */
7306 if (unlikely(!enable_vnmi &&
7307 vmx->loaded_vmcs->soft_vnmi_blocked))
7308 vmx->loaded_vmcs->entry_time = ktime_get();
7309
7310 /*
7311 * Don't enter VMX if guest state is invalid, let the exit handler
7312 * start emulation until we arrive back to a valid state. Synthesize a
7313 * consistency check VM-Exit due to invalid guest state and bail.
7314 */
7315 if (unlikely(vmx->emulation_required)) {
7316 vmx->fail = 0;
7317
7318 vmx->exit_reason.full = EXIT_REASON_INVALID_STATE;
7319 vmx->exit_reason.failed_vmentry = 1;
7320 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_1);
7321 vmx->exit_qualification = ENTRY_FAIL_DEFAULT;
7322 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_2);
7323 vmx->exit_intr_info = 0;
7324 return EXIT_FASTPATH_NONE;
7325 }
7326
7327 trace_kvm_entry(vcpu);
7328
7329 if (vmx->ple_window_dirty) {
7330 vmx->ple_window_dirty = false;
7331 vmcs_write32(PLE_WINDOW, vmx->ple_window);
7332 }
7333
7334 /*
7335 * We did this in prepare_switch_to_guest, because it needs to
7336 * be within srcu_read_lock.
7337 */
7338 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
7339
7340 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
7341 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
7342 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
7343 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
7344 vcpu->arch.regs_dirty = 0;
7345
7346 /*
7347 * Refresh vmcs.HOST_CR3 if necessary. This must be done immediately
7348 * prior to VM-Enter, as the kernel may load a new ASID (PCID) any time
7349 * it switches back to the current->mm, which can occur in KVM context
7350 * when switching to a temporary mm to patch kernel code, e.g. if KVM
7351 * toggles a static key while handling a VM-Exit.
7352 */
7353 cr3 = __get_current_cr3_fast();
7354 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
7355 vmcs_writel(HOST_CR3, cr3);
7356 vmx->loaded_vmcs->host_state.cr3 = cr3;
7357 }
7358
7359 cr4 = cr4_read_shadow();
7360 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
7361 vmcs_writel(HOST_CR4, cr4);
7362 vmx->loaded_vmcs->host_state.cr4 = cr4;
7363 }
7364
7365 /* When single-stepping over STI and MOV SS, we must clear the
7366 * corresponding interruptibility bits in the guest state. Otherwise
7367 * vmentry fails as it then expects bit 14 (BS) in pending debug
7368 * exceptions being set, but that's not correct for the guest debugging
7369 * case. */
7370 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7371 vmx_set_interrupt_shadow(vcpu, 0);
7372
7373 kvm_load_guest_xsave_state(vcpu);
7374
7375 pt_guest_enter(vmx);
7376
7377 atomic_switch_perf_msrs(vmx);
7378 if (intel_pmu_lbr_is_enabled(vcpu))
7379 vmx_passthrough_lbr_msrs(vcpu);
7380
7381 if (enable_preemption_timer)
7382 vmx_update_hv_timer(vcpu);
7383
7384 kvm_wait_lapic_expire(vcpu);
7385
7386 /* The actual VMENTER/EXIT is in the .noinstr.text section. */
7387 vmx_vcpu_enter_exit(vcpu, __vmx_vcpu_run_flags(vmx));
7388
7389 /* All fields are clean at this point */
7390 if (kvm_is_using_evmcs()) {
7391 current_evmcs->hv_clean_fields |=
7392 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
7393
7394 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
7395 }
7396
7397 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
7398 if (vmx->host_debugctlmsr)
7399 update_debugctlmsr(vmx->host_debugctlmsr);
7400
7401 #ifndef CONFIG_X86_64
7402 /*
7403 * The sysexit path does not restore ds/es, so we must set them to
7404 * a reasonable value ourselves.
7405 *
7406 * We can't defer this to vmx_prepare_switch_to_host() since that
7407 * function may be executed in interrupt context, which saves and
7408 * restore segments around it, nullifying its effect.
7409 */
7410 loadsegment(ds, __USER_DS);
7411 loadsegment(es, __USER_DS);
7412 #endif
7413
7414 pt_guest_exit(vmx);
7415
7416 kvm_load_host_xsave_state(vcpu);
7417
7418 if (is_guest_mode(vcpu)) {
7419 /*
7420 * Track VMLAUNCH/VMRESUME that have made past guest state
7421 * checking.
7422 */
7423 if (vmx->nested.nested_run_pending &&
7424 !vmx->exit_reason.failed_vmentry)
7425 ++vcpu->stat.nested_run;
7426
7427 vmx->nested.nested_run_pending = 0;
7428 }
7429
7430 if (unlikely(vmx->fail))
7431 return EXIT_FASTPATH_NONE;
7432
7433 if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
7434 kvm_machine_check();
7435
7436 trace_kvm_exit(vcpu, KVM_ISA_VMX);
7437
7438 if (unlikely(vmx->exit_reason.failed_vmentry))
7439 return EXIT_FASTPATH_NONE;
7440
7441 vmx->loaded_vmcs->launched = 1;
7442
7443 vmx_recover_nmi_blocking(vmx);
7444 vmx_complete_interrupts(vmx);
7445
7446 if (is_guest_mode(vcpu))
7447 return EXIT_FASTPATH_NONE;
7448
7449 return vmx_exit_handlers_fastpath(vcpu);
7450 }
7451
vmx_vcpu_free(struct kvm_vcpu * vcpu)7452 static void vmx_vcpu_free(struct kvm_vcpu *vcpu)
7453 {
7454 struct vcpu_vmx *vmx = to_vmx(vcpu);
7455
7456 if (enable_pml)
7457 vmx_destroy_pml_buffer(vmx);
7458 free_vpid(vmx->vpid);
7459 nested_vmx_free_vcpu(vcpu);
7460 free_loaded_vmcs(vmx->loaded_vmcs);
7461 }
7462
vmx_vcpu_create(struct kvm_vcpu * vcpu)7463 static int vmx_vcpu_create(struct kvm_vcpu *vcpu)
7464 {
7465 struct vmx_uret_msr *tsx_ctrl;
7466 struct vcpu_vmx *vmx;
7467 int i, err;
7468
7469 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
7470 vmx = to_vmx(vcpu);
7471
7472 INIT_LIST_HEAD(&vmx->pi_wakeup_list);
7473
7474 err = -ENOMEM;
7475
7476 vmx->vpid = allocate_vpid();
7477
7478 /*
7479 * If PML is turned on, failure on enabling PML just results in failure
7480 * of creating the vcpu, therefore we can simplify PML logic (by
7481 * avoiding dealing with cases, such as enabling PML partially on vcpus
7482 * for the guest), etc.
7483 */
7484 if (enable_pml) {
7485 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
7486 if (!vmx->pml_pg)
7487 goto free_vpid;
7488 }
7489
7490 for (i = 0; i < kvm_nr_uret_msrs; ++i)
7491 vmx->guest_uret_msrs[i].mask = -1ull;
7492 if (boot_cpu_has(X86_FEATURE_RTM)) {
7493 /*
7494 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception.
7495 * Keep the host value unchanged to avoid changing CPUID bits
7496 * under the host kernel's feet.
7497 */
7498 tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7499 if (tsx_ctrl)
7500 tsx_ctrl->mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
7501 }
7502
7503 err = alloc_loaded_vmcs(&vmx->vmcs01);
7504 if (err < 0)
7505 goto free_pml;
7506
7507 /*
7508 * Use Hyper-V 'Enlightened MSR Bitmap' feature when KVM runs as a
7509 * nested (L1) hypervisor and Hyper-V in L0 supports it. Enable the
7510 * feature only for vmcs01, KVM currently isn't equipped to realize any
7511 * performance benefits from enabling it for vmcs02.
7512 */
7513 if (kvm_is_using_evmcs() &&
7514 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
7515 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
7516
7517 evmcs->hv_enlightenments_control.msr_bitmap = 1;
7518 }
7519
7520 /* The MSR bitmap starts with all ones */
7521 bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7522 bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7523
7524 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
7525 #ifdef CONFIG_X86_64
7526 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
7527 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
7528 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
7529 #endif
7530 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
7531 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
7532 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
7533 if (kvm_cstate_in_guest(vcpu->kvm)) {
7534 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
7535 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
7536 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
7537 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
7538 }
7539
7540 vmx->loaded_vmcs = &vmx->vmcs01;
7541
7542 if (cpu_need_virtualize_apic_accesses(vcpu)) {
7543 err = kvm_alloc_apic_access_page(vcpu->kvm);
7544 if (err)
7545 goto free_vmcs;
7546 }
7547
7548 if (enable_ept && !enable_unrestricted_guest) {
7549 err = init_rmode_identity_map(vcpu->kvm);
7550 if (err)
7551 goto free_vmcs;
7552 }
7553
7554 if (vmx_can_use_ipiv(vcpu))
7555 WRITE_ONCE(to_kvm_vmx(vcpu->kvm)->pid_table[vcpu->vcpu_id],
7556 __pa(&vmx->pi_desc) | PID_TABLE_ENTRY_VALID);
7557
7558 return 0;
7559
7560 free_vmcs:
7561 free_loaded_vmcs(vmx->loaded_vmcs);
7562 free_pml:
7563 vmx_destroy_pml_buffer(vmx);
7564 free_vpid:
7565 free_vpid(vmx->vpid);
7566 return err;
7567 }
7568
7569 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
7570 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
7571
vmx_vm_init(struct kvm * kvm)7572 static int vmx_vm_init(struct kvm *kvm)
7573 {
7574 if (!ple_gap)
7575 kvm->arch.pause_in_guest = true;
7576
7577 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7578 switch (l1tf_mitigation) {
7579 case L1TF_MITIGATION_OFF:
7580 case L1TF_MITIGATION_FLUSH_NOWARN:
7581 /* 'I explicitly don't care' is set */
7582 break;
7583 case L1TF_MITIGATION_FLUSH:
7584 case L1TF_MITIGATION_FLUSH_NOSMT:
7585 case L1TF_MITIGATION_FULL:
7586 /*
7587 * Warn upon starting the first VM in a potentially
7588 * insecure environment.
7589 */
7590 if (sched_smt_active())
7591 pr_warn_once(L1TF_MSG_SMT);
7592 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7593 pr_warn_once(L1TF_MSG_L1D);
7594 break;
7595 case L1TF_MITIGATION_FULL_FORCE:
7596 /* Flush is enforced */
7597 break;
7598 }
7599 }
7600 return 0;
7601 }
7602
vmx_get_mt_mask(struct kvm_vcpu * vcpu,gfn_t gfn,bool is_mmio)7603 static u8 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7604 {
7605 u8 cache;
7606
7607 /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7608 * memory aliases with conflicting memory types and sometimes MCEs.
7609 * We have to be careful as to what are honored and when.
7610 *
7611 * For MMIO, guest CD/MTRR are ignored. The EPT memory type is set to
7612 * UC. The effective memory type is UC or WC depending on guest PAT.
7613 * This was historically the source of MCEs and we want to be
7614 * conservative.
7615 *
7616 * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7617 * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored. The
7618 * EPT memory type is set to WB. The effective memory type is forced
7619 * WB.
7620 *
7621 * Otherwise, we trust guest. Guest CD/MTRR/PAT are all honored. The
7622 * EPT memory type is used to emulate guest CD/MTRR.
7623 */
7624
7625 if (is_mmio)
7626 return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
7627
7628 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
7629 return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7630
7631 if (kvm_read_cr0_bits(vcpu, X86_CR0_CD)) {
7632 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7633 cache = MTRR_TYPE_WRBACK;
7634 else
7635 cache = MTRR_TYPE_UNCACHABLE;
7636
7637 return (cache << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7638 }
7639
7640 return kvm_mtrr_get_guest_memory_type(vcpu, gfn) << VMX_EPT_MT_EPTE_SHIFT;
7641 }
7642
vmcs_set_secondary_exec_control(struct vcpu_vmx * vmx,u32 new_ctl)7643 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx, u32 new_ctl)
7644 {
7645 /*
7646 * These bits in the secondary execution controls field
7647 * are dynamic, the others are mostly based on the hypervisor
7648 * architecture and the guest's CPUID. Do not touch the
7649 * dynamic bits.
7650 */
7651 u32 mask =
7652 SECONDARY_EXEC_SHADOW_VMCS |
7653 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7654 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7655 SECONDARY_EXEC_DESC;
7656
7657 u32 cur_ctl = secondary_exec_controls_get(vmx);
7658
7659 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7660 }
7661
7662 /*
7663 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7664 * (indicating "allowed-1") if they are supported in the guest's CPUID.
7665 */
nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu * vcpu)7666 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7667 {
7668 struct vcpu_vmx *vmx = to_vmx(vcpu);
7669 struct kvm_cpuid_entry2 *entry;
7670
7671 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7672 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7673
7674 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
7675 if (entry && (entry->_reg & (_cpuid_mask))) \
7676 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
7677 } while (0)
7678
7679 entry = kvm_find_cpuid_entry(vcpu, 0x1);
7680 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME));
7681 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME));
7682 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC));
7683 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE));
7684 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE));
7685 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE));
7686 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE));
7687 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE));
7688 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR));
7689 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7690 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX));
7691 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX));
7692 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID));
7693 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE));
7694
7695 entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 0);
7696 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE));
7697 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP));
7698 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP));
7699 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU));
7700 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP));
7701 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57));
7702
7703 #undef cr4_fixed1_update
7704 }
7705
update_intel_pt_cfg(struct kvm_vcpu * vcpu)7706 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7707 {
7708 struct vcpu_vmx *vmx = to_vmx(vcpu);
7709 struct kvm_cpuid_entry2 *best = NULL;
7710 int i;
7711
7712 for (i = 0; i < PT_CPUID_LEAVES; i++) {
7713 best = kvm_find_cpuid_entry_index(vcpu, 0x14, i);
7714 if (!best)
7715 return;
7716 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7717 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7718 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7719 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7720 }
7721
7722 /* Get the number of configurable Address Ranges for filtering */
7723 vmx->pt_desc.num_address_ranges = intel_pt_validate_cap(vmx->pt_desc.caps,
7724 PT_CAP_num_address_ranges);
7725
7726 /* Initialize and clear the no dependency bits */
7727 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7728 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC |
7729 RTIT_CTL_BRANCH_EN);
7730
7731 /*
7732 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7733 * will inject an #GP
7734 */
7735 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7736 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7737
7738 /*
7739 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7740 * PSBFreq can be set
7741 */
7742 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7743 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7744 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7745
7746 /*
7747 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn and MTCFreq can be set
7748 */
7749 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7750 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7751 RTIT_CTL_MTC_RANGE);
7752
7753 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7754 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7755 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7756 RTIT_CTL_PTW_EN);
7757
7758 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7759 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7760 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7761
7762 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7763 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7764 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7765
7766 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7767 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7768 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7769
7770 /* unmask address range configure area */
7771 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++)
7772 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7773 }
7774
vmx_vcpu_after_set_cpuid(struct kvm_vcpu * vcpu)7775 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7776 {
7777 struct vcpu_vmx *vmx = to_vmx(vcpu);
7778
7779 /*
7780 * XSAVES is effectively enabled if and only if XSAVE is also exposed
7781 * to the guest. XSAVES depends on CR4.OSXSAVE, and CR4.OSXSAVE can be
7782 * set if and only if XSAVE is supported.
7783 */
7784 if (boot_cpu_has(X86_FEATURE_XSAVE) &&
7785 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE))
7786 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_XSAVES);
7787
7788 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_VMX);
7789
7790 vmx_setup_uret_msrs(vmx);
7791
7792 if (cpu_has_secondary_exec_ctrls())
7793 vmcs_set_secondary_exec_control(vmx,
7794 vmx_secondary_exec_control(vmx));
7795
7796 if (guest_can_use(vcpu, X86_FEATURE_VMX))
7797 vmx->msr_ia32_feature_control_valid_bits |=
7798 FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7799 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7800 else
7801 vmx->msr_ia32_feature_control_valid_bits &=
7802 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7803 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7804
7805 if (guest_can_use(vcpu, X86_FEATURE_VMX))
7806 nested_vmx_cr_fixed1_bits_update(vcpu);
7807
7808 if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7809 guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7810 update_intel_pt_cfg(vcpu);
7811
7812 if (boot_cpu_has(X86_FEATURE_RTM)) {
7813 struct vmx_uret_msr *msr;
7814 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7815 if (msr) {
7816 bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7817 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7818 }
7819 }
7820
7821 if (kvm_cpu_cap_has(X86_FEATURE_XFD))
7822 vmx_set_intercept_for_msr(vcpu, MSR_IA32_XFD_ERR, MSR_TYPE_R,
7823 !guest_cpuid_has(vcpu, X86_FEATURE_XFD));
7824
7825 if (boot_cpu_has(X86_FEATURE_IBPB))
7826 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W,
7827 !guest_has_pred_cmd_msr(vcpu));
7828
7829 if (boot_cpu_has(X86_FEATURE_FLUSH_L1D))
7830 vmx_set_intercept_for_msr(vcpu, MSR_IA32_FLUSH_CMD, MSR_TYPE_W,
7831 !guest_cpuid_has(vcpu, X86_FEATURE_FLUSH_L1D));
7832
7833 set_cr4_guest_host_mask(vmx);
7834
7835 vmx_write_encls_bitmap(vcpu, NULL);
7836 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7837 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7838 else
7839 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7840
7841 if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7842 vmx->msr_ia32_feature_control_valid_bits |=
7843 FEAT_CTL_SGX_LC_ENABLED;
7844 else
7845 vmx->msr_ia32_feature_control_valid_bits &=
7846 ~FEAT_CTL_SGX_LC_ENABLED;
7847
7848 /* Refresh #PF interception to account for MAXPHYADDR changes. */
7849 vmx_update_exception_bitmap(vcpu);
7850 }
7851
vmx_get_perf_capabilities(void)7852 static u64 vmx_get_perf_capabilities(void)
7853 {
7854 u64 perf_cap = PMU_CAP_FW_WRITES;
7855 struct x86_pmu_lbr lbr;
7856 u64 host_perf_cap = 0;
7857
7858 if (!enable_pmu)
7859 return 0;
7860
7861 if (boot_cpu_has(X86_FEATURE_PDCM))
7862 rdmsrl(MSR_IA32_PERF_CAPABILITIES, host_perf_cap);
7863
7864 if (!cpu_feature_enabled(X86_FEATURE_ARCH_LBR)) {
7865 x86_perf_get_lbr(&lbr);
7866 if (lbr.nr)
7867 perf_cap |= host_perf_cap & PMU_CAP_LBR_FMT;
7868 }
7869
7870 if (vmx_pebs_supported()) {
7871 perf_cap |= host_perf_cap & PERF_CAP_PEBS_MASK;
7872
7873 /*
7874 * Disallow adaptive PEBS as it is functionally broken, can be
7875 * used by the guest to read *host* LBRs, and can be used to
7876 * bypass userspace event filters. To correctly and safely
7877 * support adaptive PEBS, KVM needs to:
7878 *
7879 * 1. Account for the ADAPTIVE flag when (re)programming fixed
7880 * counters.
7881 *
7882 * 2. Gain support from perf (or take direct control of counter
7883 * programming) to support events without adaptive PEBS
7884 * enabled for the hardware counter.
7885 *
7886 * 3. Ensure LBR MSRs cannot hold host data on VM-Entry with
7887 * adaptive PEBS enabled and MSR_PEBS_DATA_CFG.LBRS=1.
7888 *
7889 * 4. Document which PMU events are effectively exposed to the
7890 * guest via adaptive PEBS, and make adaptive PEBS mutually
7891 * exclusive with KVM_SET_PMU_EVENT_FILTER if necessary.
7892 */
7893 perf_cap &= ~PERF_CAP_PEBS_BASELINE;
7894 }
7895
7896 return perf_cap;
7897 }
7898
vmx_set_cpu_caps(void)7899 static __init void vmx_set_cpu_caps(void)
7900 {
7901 kvm_set_cpu_caps();
7902
7903 /* CPUID 0x1 */
7904 if (nested)
7905 kvm_cpu_cap_set(X86_FEATURE_VMX);
7906
7907 /* CPUID 0x7 */
7908 if (kvm_mpx_supported())
7909 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7910 if (!cpu_has_vmx_invpcid())
7911 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7912 if (vmx_pt_mode_is_host_guest())
7913 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7914 if (vmx_pebs_supported()) {
7915 kvm_cpu_cap_check_and_set(X86_FEATURE_DS);
7916 kvm_cpu_cap_check_and_set(X86_FEATURE_DTES64);
7917 }
7918
7919 if (!enable_pmu)
7920 kvm_cpu_cap_clear(X86_FEATURE_PDCM);
7921 kvm_caps.supported_perf_cap = vmx_get_perf_capabilities();
7922
7923 if (!enable_sgx) {
7924 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7925 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7926 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7927 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7928 }
7929
7930 if (vmx_umip_emulated())
7931 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7932
7933 /* CPUID 0xD.1 */
7934 kvm_caps.supported_xss = 0;
7935 if (!cpu_has_vmx_xsaves())
7936 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7937
7938 /* CPUID 0x80000001 and 0x7 (RDPID) */
7939 if (!cpu_has_vmx_rdtscp()) {
7940 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7941 kvm_cpu_cap_clear(X86_FEATURE_RDPID);
7942 }
7943
7944 if (cpu_has_vmx_waitpkg())
7945 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7946 }
7947
vmx_request_immediate_exit(struct kvm_vcpu * vcpu)7948 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7949 {
7950 to_vmx(vcpu)->req_immediate_exit = true;
7951 }
7952
vmx_check_intercept_io(struct kvm_vcpu * vcpu,struct x86_instruction_info * info)7953 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7954 struct x86_instruction_info *info)
7955 {
7956 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7957 unsigned short port;
7958 bool intercept;
7959 int size;
7960
7961 if (info->intercept == x86_intercept_in ||
7962 info->intercept == x86_intercept_ins) {
7963 port = info->src_val;
7964 size = info->dst_bytes;
7965 } else {
7966 port = info->dst_val;
7967 size = info->src_bytes;
7968 }
7969
7970 /*
7971 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7972 * VM-exits depend on the 'unconditional IO exiting' VM-execution
7973 * control.
7974 *
7975 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7976 */
7977 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7978 intercept = nested_cpu_has(vmcs12,
7979 CPU_BASED_UNCOND_IO_EXITING);
7980 else
7981 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7982
7983 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
7984 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7985 }
7986
vmx_check_intercept(struct kvm_vcpu * vcpu,struct x86_instruction_info * info,enum x86_intercept_stage stage,struct x86_exception * exception)7987 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7988 struct x86_instruction_info *info,
7989 enum x86_intercept_stage stage,
7990 struct x86_exception *exception)
7991 {
7992 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7993
7994 switch (info->intercept) {
7995 /*
7996 * RDPID causes #UD if disabled through secondary execution controls.
7997 * Because it is marked as EmulateOnUD, we need to intercept it here.
7998 * Note, RDPID is hidden behind ENABLE_RDTSCP.
7999 */
8000 case x86_intercept_rdpid:
8001 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
8002 exception->vector = UD_VECTOR;
8003 exception->error_code_valid = false;
8004 return X86EMUL_PROPAGATE_FAULT;
8005 }
8006 break;
8007
8008 case x86_intercept_in:
8009 case x86_intercept_ins:
8010 case x86_intercept_out:
8011 case x86_intercept_outs:
8012 return vmx_check_intercept_io(vcpu, info);
8013
8014 case x86_intercept_lgdt:
8015 case x86_intercept_lidt:
8016 case x86_intercept_lldt:
8017 case x86_intercept_ltr:
8018 case x86_intercept_sgdt:
8019 case x86_intercept_sidt:
8020 case x86_intercept_sldt:
8021 case x86_intercept_str:
8022 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
8023 return X86EMUL_CONTINUE;
8024
8025 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
8026 break;
8027
8028 case x86_intercept_pause:
8029 /*
8030 * PAUSE is a single-byte NOP with a REPE prefix, i.e. collides
8031 * with vanilla NOPs in the emulator. Apply the interception
8032 * check only to actual PAUSE instructions. Don't check
8033 * PAUSE-loop-exiting, software can't expect a given PAUSE to
8034 * exit, i.e. KVM is within its rights to allow L2 to execute
8035 * the PAUSE.
8036 */
8037 if ((info->rep_prefix != REPE_PREFIX) ||
8038 !nested_cpu_has2(vmcs12, CPU_BASED_PAUSE_EXITING))
8039 return X86EMUL_CONTINUE;
8040
8041 break;
8042
8043 /* TODO: check more intercepts... */
8044 default:
8045 break;
8046 }
8047
8048 return X86EMUL_UNHANDLEABLE;
8049 }
8050
8051 #ifdef CONFIG_X86_64
8052 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
u64_shl_div_u64(u64 a,unsigned int shift,u64 divisor,u64 * result)8053 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
8054 u64 divisor, u64 *result)
8055 {
8056 u64 low = a << shift, high = a >> (64 - shift);
8057
8058 /* To avoid the overflow on divq */
8059 if (high >= divisor)
8060 return 1;
8061
8062 /* Low hold the result, high hold rem which is discarded */
8063 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
8064 "rm" (divisor), "0" (low), "1" (high));
8065 *result = low;
8066
8067 return 0;
8068 }
8069
vmx_set_hv_timer(struct kvm_vcpu * vcpu,u64 guest_deadline_tsc,bool * expired)8070 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
8071 bool *expired)
8072 {
8073 struct vcpu_vmx *vmx;
8074 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
8075 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
8076
8077 vmx = to_vmx(vcpu);
8078 tscl = rdtsc();
8079 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
8080 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
8081 lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
8082 ktimer->timer_advance_ns);
8083
8084 if (delta_tsc > lapic_timer_advance_cycles)
8085 delta_tsc -= lapic_timer_advance_cycles;
8086 else
8087 delta_tsc = 0;
8088
8089 /* Convert to host delta tsc if tsc scaling is enabled */
8090 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio &&
8091 delta_tsc && u64_shl_div_u64(delta_tsc,
8092 kvm_caps.tsc_scaling_ratio_frac_bits,
8093 vcpu->arch.l1_tsc_scaling_ratio, &delta_tsc))
8094 return -ERANGE;
8095
8096 /*
8097 * If the delta tsc can't fit in the 32 bit after the multi shift,
8098 * we can't use the preemption timer.
8099 * It's possible that it fits on later vmentries, but checking
8100 * on every vmentry is costly so we just use an hrtimer.
8101 */
8102 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
8103 return -ERANGE;
8104
8105 vmx->hv_deadline_tsc = tscl + delta_tsc;
8106 *expired = !delta_tsc;
8107 return 0;
8108 }
8109
vmx_cancel_hv_timer(struct kvm_vcpu * vcpu)8110 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
8111 {
8112 to_vmx(vcpu)->hv_deadline_tsc = -1;
8113 }
8114 #endif
8115
vmx_sched_in(struct kvm_vcpu * vcpu,int cpu)8116 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
8117 {
8118 if (!kvm_pause_in_guest(vcpu->kvm))
8119 shrink_ple_window(vcpu);
8120 }
8121
vmx_update_cpu_dirty_logging(struct kvm_vcpu * vcpu)8122 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
8123 {
8124 struct vcpu_vmx *vmx = to_vmx(vcpu);
8125
8126 if (WARN_ON_ONCE(!enable_pml))
8127 return;
8128
8129 if (is_guest_mode(vcpu)) {
8130 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
8131 return;
8132 }
8133
8134 /*
8135 * Note, nr_memslots_dirty_logging can be changed concurrent with this
8136 * code, but in that case another update request will be made and so
8137 * the guest will never run with a stale PML value.
8138 */
8139 if (atomic_read(&vcpu->kvm->nr_memslots_dirty_logging))
8140 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
8141 else
8142 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
8143 }
8144
vmx_setup_mce(struct kvm_vcpu * vcpu)8145 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
8146 {
8147 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
8148 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
8149 FEAT_CTL_LMCE_ENABLED;
8150 else
8151 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
8152 ~FEAT_CTL_LMCE_ENABLED;
8153 }
8154
8155 #ifdef CONFIG_KVM_SMM
vmx_smi_allowed(struct kvm_vcpu * vcpu,bool for_injection)8156 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
8157 {
8158 /* we need a nested vmexit to enter SMM, postpone if run is pending */
8159 if (to_vmx(vcpu)->nested.nested_run_pending)
8160 return -EBUSY;
8161 return !is_smm(vcpu);
8162 }
8163
vmx_enter_smm(struct kvm_vcpu * vcpu,union kvm_smram * smram)8164 static int vmx_enter_smm(struct kvm_vcpu *vcpu, union kvm_smram *smram)
8165 {
8166 struct vcpu_vmx *vmx = to_vmx(vcpu);
8167
8168 /*
8169 * TODO: Implement custom flows for forcing the vCPU out/in of L2 on
8170 * SMI and RSM. Using the common VM-Exit + VM-Enter routines is wrong
8171 * SMI and RSM only modify state that is saved and restored via SMRAM.
8172 * E.g. most MSRs are left untouched, but many are modified by VM-Exit
8173 * and VM-Enter, and thus L2's values may be corrupted on SMI+RSM.
8174 */
8175 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
8176 if (vmx->nested.smm.guest_mode)
8177 nested_vmx_vmexit(vcpu, -1, 0, 0);
8178
8179 vmx->nested.smm.vmxon = vmx->nested.vmxon;
8180 vmx->nested.vmxon = false;
8181 vmx_clear_hlt(vcpu);
8182 return 0;
8183 }
8184
vmx_leave_smm(struct kvm_vcpu * vcpu,const union kvm_smram * smram)8185 static int vmx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram)
8186 {
8187 struct vcpu_vmx *vmx = to_vmx(vcpu);
8188 int ret;
8189
8190 if (vmx->nested.smm.vmxon) {
8191 vmx->nested.vmxon = true;
8192 vmx->nested.smm.vmxon = false;
8193 }
8194
8195 if (vmx->nested.smm.guest_mode) {
8196 ret = nested_vmx_enter_non_root_mode(vcpu, false);
8197 if (ret)
8198 return ret;
8199
8200 vmx->nested.nested_run_pending = 1;
8201 vmx->nested.smm.guest_mode = false;
8202 }
8203 return 0;
8204 }
8205
vmx_enable_smi_window(struct kvm_vcpu * vcpu)8206 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
8207 {
8208 /* RSM will cause a vmexit anyway. */
8209 }
8210 #endif
8211
vmx_apic_init_signal_blocked(struct kvm_vcpu * vcpu)8212 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
8213 {
8214 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
8215 }
8216
vmx_migrate_timers(struct kvm_vcpu * vcpu)8217 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
8218 {
8219 if (is_guest_mode(vcpu)) {
8220 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
8221
8222 if (hrtimer_try_to_cancel(timer) == 1)
8223 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
8224 }
8225 }
8226
vmx_hardware_unsetup(void)8227 static void vmx_hardware_unsetup(void)
8228 {
8229 kvm_set_posted_intr_wakeup_handler(NULL);
8230
8231 if (nested)
8232 nested_vmx_hardware_unsetup();
8233
8234 free_kvm_area();
8235 }
8236
8237 #define VMX_REQUIRED_APICV_INHIBITS \
8238 ( \
8239 BIT(APICV_INHIBIT_REASON_DISABLE)| \
8240 BIT(APICV_INHIBIT_REASON_ABSENT) | \
8241 BIT(APICV_INHIBIT_REASON_HYPERV) | \
8242 BIT(APICV_INHIBIT_REASON_BLOCKIRQ) | \
8243 BIT(APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED) | \
8244 BIT(APICV_INHIBIT_REASON_APIC_ID_MODIFIED) | \
8245 BIT(APICV_INHIBIT_REASON_APIC_BASE_MODIFIED) \
8246 )
8247
vmx_vm_destroy(struct kvm * kvm)8248 static void vmx_vm_destroy(struct kvm *kvm)
8249 {
8250 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
8251
8252 free_pages((unsigned long)kvm_vmx->pid_table, vmx_get_pid_table_order(kvm));
8253 }
8254
8255 static struct kvm_x86_ops vmx_x86_ops __initdata = {
8256 .name = KBUILD_MODNAME,
8257
8258 .check_processor_compatibility = vmx_check_processor_compat,
8259
8260 .hardware_unsetup = vmx_hardware_unsetup,
8261
8262 .hardware_enable = vmx_hardware_enable,
8263 .hardware_disable = vmx_hardware_disable,
8264 .has_emulated_msr = vmx_has_emulated_msr,
8265
8266 .vm_size = sizeof(struct kvm_vmx),
8267 .vm_init = vmx_vm_init,
8268 .vm_destroy = vmx_vm_destroy,
8269
8270 .vcpu_precreate = vmx_vcpu_precreate,
8271 .vcpu_create = vmx_vcpu_create,
8272 .vcpu_free = vmx_vcpu_free,
8273 .vcpu_reset = vmx_vcpu_reset,
8274
8275 .prepare_switch_to_guest = vmx_prepare_switch_to_guest,
8276 .vcpu_load = vmx_vcpu_load,
8277 .vcpu_put = vmx_vcpu_put,
8278
8279 .update_exception_bitmap = vmx_update_exception_bitmap,
8280 .get_msr_feature = vmx_get_msr_feature,
8281 .get_msr = vmx_get_msr,
8282 .set_msr = vmx_set_msr,
8283 .get_segment_base = vmx_get_segment_base,
8284 .get_segment = vmx_get_segment,
8285 .set_segment = vmx_set_segment,
8286 .get_cpl = vmx_get_cpl,
8287 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
8288 .is_valid_cr0 = vmx_is_valid_cr0,
8289 .set_cr0 = vmx_set_cr0,
8290 .is_valid_cr4 = vmx_is_valid_cr4,
8291 .set_cr4 = vmx_set_cr4,
8292 .set_efer = vmx_set_efer,
8293 .get_idt = vmx_get_idt,
8294 .set_idt = vmx_set_idt,
8295 .get_gdt = vmx_get_gdt,
8296 .set_gdt = vmx_set_gdt,
8297 .set_dr6 = vmx_set_dr6,
8298 .set_dr7 = vmx_set_dr7,
8299 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
8300 .cache_reg = vmx_cache_reg,
8301 .get_rflags = vmx_get_rflags,
8302 .set_rflags = vmx_set_rflags,
8303 .get_if_flag = vmx_get_if_flag,
8304
8305 .flush_tlb_all = vmx_flush_tlb_all,
8306 .flush_tlb_current = vmx_flush_tlb_current,
8307 .flush_tlb_gva = vmx_flush_tlb_gva,
8308 .flush_tlb_guest = vmx_flush_tlb_guest,
8309
8310 .vcpu_pre_run = vmx_vcpu_pre_run,
8311 .vcpu_run = vmx_vcpu_run,
8312 .handle_exit = vmx_handle_exit,
8313 .skip_emulated_instruction = vmx_skip_emulated_instruction,
8314 .update_emulated_instruction = vmx_update_emulated_instruction,
8315 .set_interrupt_shadow = vmx_set_interrupt_shadow,
8316 .get_interrupt_shadow = vmx_get_interrupt_shadow,
8317 .patch_hypercall = vmx_patch_hypercall,
8318 .inject_irq = vmx_inject_irq,
8319 .inject_nmi = vmx_inject_nmi,
8320 .inject_exception = vmx_inject_exception,
8321 .cancel_injection = vmx_cancel_injection,
8322 .interrupt_allowed = vmx_interrupt_allowed,
8323 .nmi_allowed = vmx_nmi_allowed,
8324 .get_nmi_mask = vmx_get_nmi_mask,
8325 .set_nmi_mask = vmx_set_nmi_mask,
8326 .enable_nmi_window = vmx_enable_nmi_window,
8327 .enable_irq_window = vmx_enable_irq_window,
8328 .update_cr8_intercept = vmx_update_cr8_intercept,
8329
8330 .x2apic_icr_is_split = false,
8331 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
8332 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
8333 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
8334 .load_eoi_exitmap = vmx_load_eoi_exitmap,
8335 .apicv_pre_state_restore = vmx_apicv_pre_state_restore,
8336 .required_apicv_inhibits = VMX_REQUIRED_APICV_INHIBITS,
8337 .hwapic_irr_update = vmx_hwapic_irr_update,
8338 .hwapic_isr_update = vmx_hwapic_isr_update,
8339 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
8340 .sync_pir_to_irr = vmx_sync_pir_to_irr,
8341 .deliver_interrupt = vmx_deliver_interrupt,
8342 .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
8343
8344 .set_tss_addr = vmx_set_tss_addr,
8345 .set_identity_map_addr = vmx_set_identity_map_addr,
8346 .get_mt_mask = vmx_get_mt_mask,
8347
8348 .get_exit_info = vmx_get_exit_info,
8349
8350 .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
8351
8352 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
8353
8354 .get_l2_tsc_offset = vmx_get_l2_tsc_offset,
8355 .get_l2_tsc_multiplier = vmx_get_l2_tsc_multiplier,
8356 .write_tsc_offset = vmx_write_tsc_offset,
8357 .write_tsc_multiplier = vmx_write_tsc_multiplier,
8358
8359 .load_mmu_pgd = vmx_load_mmu_pgd,
8360
8361 .check_intercept = vmx_check_intercept,
8362 .handle_exit_irqoff = vmx_handle_exit_irqoff,
8363
8364 .request_immediate_exit = vmx_request_immediate_exit,
8365
8366 .sched_in = vmx_sched_in,
8367
8368 .cpu_dirty_log_size = PML_ENTITY_NUM,
8369 .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
8370
8371 .nested_ops = &vmx_nested_ops,
8372
8373 .pi_update_irte = vmx_pi_update_irte,
8374 .pi_start_assignment = vmx_pi_start_assignment,
8375
8376 #ifdef CONFIG_X86_64
8377 .set_hv_timer = vmx_set_hv_timer,
8378 .cancel_hv_timer = vmx_cancel_hv_timer,
8379 #endif
8380
8381 .setup_mce = vmx_setup_mce,
8382
8383 #ifdef CONFIG_KVM_SMM
8384 .smi_allowed = vmx_smi_allowed,
8385 .enter_smm = vmx_enter_smm,
8386 .leave_smm = vmx_leave_smm,
8387 .enable_smi_window = vmx_enable_smi_window,
8388 #endif
8389
8390 .can_emulate_instruction = vmx_can_emulate_instruction,
8391 .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
8392 .migrate_timers = vmx_migrate_timers,
8393
8394 .msr_filter_changed = vmx_msr_filter_changed,
8395 .complete_emulated_msr = kvm_complete_insn_gp,
8396
8397 .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
8398 };
8399
vmx_handle_intel_pt_intr(void)8400 static unsigned int vmx_handle_intel_pt_intr(void)
8401 {
8402 struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
8403
8404 /* '0' on failure so that the !PT case can use a RET0 static call. */
8405 if (!vcpu || !kvm_handling_nmi_from_guest(vcpu))
8406 return 0;
8407
8408 kvm_make_request(KVM_REQ_PMI, vcpu);
8409 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
8410 (unsigned long *)&vcpu->arch.pmu.global_status);
8411 return 1;
8412 }
8413
vmx_setup_user_return_msrs(void)8414 static __init void vmx_setup_user_return_msrs(void)
8415 {
8416
8417 /*
8418 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
8419 * will emulate SYSCALL in legacy mode if the vendor string in guest
8420 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
8421 * support this emulation, MSR_STAR is included in the list for i386,
8422 * but is never loaded into hardware. MSR_CSTAR is also never loaded
8423 * into hardware and is here purely for emulation purposes.
8424 */
8425 const u32 vmx_uret_msrs_list[] = {
8426 #ifdef CONFIG_X86_64
8427 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
8428 #endif
8429 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
8430 MSR_IA32_TSX_CTRL,
8431 };
8432 int i;
8433
8434 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
8435
8436 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
8437 kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
8438 }
8439
vmx_setup_me_spte_mask(void)8440 static void __init vmx_setup_me_spte_mask(void)
8441 {
8442 u64 me_mask = 0;
8443
8444 /*
8445 * kvm_get_shadow_phys_bits() returns shadow_phys_bits. Use
8446 * the former to avoid exposing shadow_phys_bits.
8447 *
8448 * On pre-MKTME system, boot_cpu_data.x86_phys_bits equals to
8449 * shadow_phys_bits. On MKTME and/or TDX capable systems,
8450 * boot_cpu_data.x86_phys_bits holds the actual physical address
8451 * w/o the KeyID bits, and shadow_phys_bits equals to MAXPHYADDR
8452 * reported by CPUID. Those bits between are KeyID bits.
8453 */
8454 if (boot_cpu_data.x86_phys_bits != kvm_get_shadow_phys_bits())
8455 me_mask = rsvd_bits(boot_cpu_data.x86_phys_bits,
8456 kvm_get_shadow_phys_bits() - 1);
8457 /*
8458 * Unlike SME, host kernel doesn't support setting up any
8459 * MKTME KeyID on Intel platforms. No memory encryption
8460 * bits should be included into the SPTE.
8461 */
8462 kvm_mmu_set_me_spte_mask(0, me_mask);
8463 }
8464
8465 static struct kvm_x86_init_ops vmx_init_ops __initdata;
8466
hardware_setup(void)8467 static __init int hardware_setup(void)
8468 {
8469 unsigned long host_bndcfgs;
8470 struct desc_ptr dt;
8471 int r;
8472
8473 store_idt(&dt);
8474 host_idt_base = dt.address;
8475
8476 vmx_setup_user_return_msrs();
8477
8478 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
8479 return -EIO;
8480
8481 if (cpu_has_perf_global_ctrl_bug())
8482 pr_warn_once("VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
8483 "does not work properly. Using workaround\n");
8484
8485 if (boot_cpu_has(X86_FEATURE_NX))
8486 kvm_enable_efer_bits(EFER_NX);
8487
8488 if (boot_cpu_has(X86_FEATURE_MPX)) {
8489 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
8490 WARN_ONCE(host_bndcfgs, "BNDCFGS in host will be lost");
8491 }
8492
8493 if (!cpu_has_vmx_mpx())
8494 kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
8495 XFEATURE_MASK_BNDCSR);
8496
8497 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
8498 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
8499 enable_vpid = 0;
8500
8501 if (!cpu_has_vmx_ept() ||
8502 !cpu_has_vmx_ept_4levels() ||
8503 !cpu_has_vmx_ept_mt_wb() ||
8504 !cpu_has_vmx_invept_global())
8505 enable_ept = 0;
8506
8507 /* NX support is required for shadow paging. */
8508 if (!enable_ept && !boot_cpu_has(X86_FEATURE_NX)) {
8509 pr_err_ratelimited("NX (Execute Disable) not supported\n");
8510 return -EOPNOTSUPP;
8511 }
8512
8513 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
8514 enable_ept_ad_bits = 0;
8515
8516 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
8517 enable_unrestricted_guest = 0;
8518
8519 if (!cpu_has_vmx_flexpriority())
8520 flexpriority_enabled = 0;
8521
8522 if (!cpu_has_virtual_nmis())
8523 enable_vnmi = 0;
8524
8525 #ifdef CONFIG_X86_SGX_KVM
8526 if (!cpu_has_vmx_encls_vmexit())
8527 enable_sgx = false;
8528 #endif
8529
8530 /*
8531 * set_apic_access_page_addr() is used to reload apic access
8532 * page upon invalidation. No need to do anything if not
8533 * using the APIC_ACCESS_ADDR VMCS field.
8534 */
8535 if (!flexpriority_enabled)
8536 vmx_x86_ops.set_apic_access_page_addr = NULL;
8537
8538 if (!cpu_has_vmx_tpr_shadow())
8539 vmx_x86_ops.update_cr8_intercept = NULL;
8540
8541 #if IS_ENABLED(CONFIG_HYPERV)
8542 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
8543 && enable_ept) {
8544 vmx_x86_ops.flush_remote_tlbs = hv_flush_remote_tlbs;
8545 vmx_x86_ops.flush_remote_tlbs_range = hv_flush_remote_tlbs_range;
8546 }
8547 #endif
8548
8549 if (!cpu_has_vmx_ple()) {
8550 ple_gap = 0;
8551 ple_window = 0;
8552 ple_window_grow = 0;
8553 ple_window_max = 0;
8554 ple_window_shrink = 0;
8555 }
8556
8557 if (!cpu_has_vmx_apicv())
8558 enable_apicv = 0;
8559 if (!enable_apicv)
8560 vmx_x86_ops.sync_pir_to_irr = NULL;
8561
8562 if (!enable_apicv || !cpu_has_vmx_ipiv())
8563 enable_ipiv = false;
8564
8565 if (cpu_has_vmx_tsc_scaling())
8566 kvm_caps.has_tsc_control = true;
8567
8568 kvm_caps.max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
8569 kvm_caps.tsc_scaling_ratio_frac_bits = 48;
8570 kvm_caps.has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
8571 kvm_caps.has_notify_vmexit = cpu_has_notify_vmexit();
8572
8573 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8574
8575 if (enable_ept)
8576 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
8577 cpu_has_vmx_ept_execute_only());
8578
8579 /*
8580 * Setup shadow_me_value/shadow_me_mask to include MKTME KeyID
8581 * bits to shadow_zero_check.
8582 */
8583 vmx_setup_me_spte_mask();
8584
8585 kvm_configure_mmu(enable_ept, 0, vmx_get_max_ept_level(),
8586 ept_caps_to_lpage_level(vmx_capability.ept));
8587
8588 /*
8589 * Only enable PML when hardware supports PML feature, and both EPT
8590 * and EPT A/D bit features are enabled -- PML depends on them to work.
8591 */
8592 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8593 enable_pml = 0;
8594
8595 if (!enable_pml)
8596 vmx_x86_ops.cpu_dirty_log_size = 0;
8597
8598 if (!cpu_has_vmx_preemption_timer())
8599 enable_preemption_timer = false;
8600
8601 if (enable_preemption_timer) {
8602 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8603
8604 cpu_preemption_timer_multi =
8605 vmcs_config.misc & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8606
8607 if (tsc_khz)
8608 use_timer_freq = (u64)tsc_khz * 1000;
8609 use_timer_freq >>= cpu_preemption_timer_multi;
8610
8611 /*
8612 * KVM "disables" the preemption timer by setting it to its max
8613 * value. Don't use the timer if it might cause spurious exits
8614 * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8615 */
8616 if (use_timer_freq > 0xffffffffu / 10)
8617 enable_preemption_timer = false;
8618 }
8619
8620 if (!enable_preemption_timer) {
8621 vmx_x86_ops.set_hv_timer = NULL;
8622 vmx_x86_ops.cancel_hv_timer = NULL;
8623 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8624 }
8625
8626 kvm_caps.supported_mce_cap |= MCG_LMCE_P;
8627 kvm_caps.supported_mce_cap |= MCG_CMCI_P;
8628
8629 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8630 return -EINVAL;
8631 if (!enable_ept || !enable_pmu || !cpu_has_vmx_intel_pt())
8632 pt_mode = PT_MODE_SYSTEM;
8633 if (pt_mode == PT_MODE_HOST_GUEST)
8634 vmx_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr;
8635 else
8636 vmx_init_ops.handle_intel_pt_intr = NULL;
8637
8638 setup_default_sgx_lepubkeyhash();
8639
8640 if (nested) {
8641 nested_vmx_setup_ctls_msrs(&vmcs_config, vmx_capability.ept);
8642
8643 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8644 if (r)
8645 return r;
8646 }
8647
8648 vmx_set_cpu_caps();
8649
8650 r = alloc_kvm_area();
8651 if (r && nested)
8652 nested_vmx_hardware_unsetup();
8653
8654 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
8655
8656 return r;
8657 }
8658
8659 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8660 .hardware_setup = hardware_setup,
8661 .handle_intel_pt_intr = NULL,
8662
8663 .runtime_ops = &vmx_x86_ops,
8664 .pmu_ops = &intel_pmu_ops,
8665 };
8666
vmx_cleanup_l1d_flush(void)8667 static void vmx_cleanup_l1d_flush(void)
8668 {
8669 if (vmx_l1d_flush_pages) {
8670 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8671 vmx_l1d_flush_pages = NULL;
8672 }
8673 /* Restore state so sysfs ignores VMX */
8674 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8675 }
8676
__vmx_exit(void)8677 static void __vmx_exit(void)
8678 {
8679 allow_smaller_maxphyaddr = false;
8680
8681 cpu_emergency_unregister_virt_callback(vmx_emergency_disable);
8682
8683 vmx_cleanup_l1d_flush();
8684 }
8685
vmx_exit(void)8686 static void vmx_exit(void)
8687 {
8688 kvm_exit();
8689 kvm_x86_vendor_exit();
8690
8691 __vmx_exit();
8692 }
8693 module_exit(vmx_exit);
8694
vmx_init(void)8695 static int __init vmx_init(void)
8696 {
8697 int r, cpu;
8698
8699 if (!kvm_is_vmx_supported())
8700 return -EOPNOTSUPP;
8701
8702 /*
8703 * Note, hv_init_evmcs() touches only VMX knobs, i.e. there's nothing
8704 * to unwind if a later step fails.
8705 */
8706 hv_init_evmcs();
8707
8708 r = kvm_x86_vendor_init(&vmx_init_ops);
8709 if (r)
8710 return r;
8711
8712 /*
8713 * Must be called after common x86 init so enable_ept is properly set
8714 * up. Hand the parameter mitigation value in which was stored in
8715 * the pre module init parser. If no parameter was given, it will
8716 * contain 'auto' which will be turned into the default 'cond'
8717 * mitigation mode.
8718 */
8719 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8720 if (r)
8721 goto err_l1d_flush;
8722
8723 for_each_possible_cpu(cpu) {
8724 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8725
8726 pi_init_cpu(cpu);
8727 }
8728
8729 cpu_emergency_register_virt_callback(vmx_emergency_disable);
8730
8731 vmx_check_vmcs12_offsets();
8732
8733 /*
8734 * Shadow paging doesn't have a (further) performance penalty
8735 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8736 * by default
8737 */
8738 if (!enable_ept)
8739 allow_smaller_maxphyaddr = true;
8740
8741 /*
8742 * Common KVM initialization _must_ come last, after this, /dev/kvm is
8743 * exposed to userspace!
8744 */
8745 r = kvm_init(sizeof(struct vcpu_vmx), __alignof__(struct vcpu_vmx),
8746 THIS_MODULE);
8747 if (r)
8748 goto err_kvm_init;
8749
8750 return 0;
8751
8752 err_kvm_init:
8753 __vmx_exit();
8754 err_l1d_flush:
8755 kvm_x86_vendor_exit();
8756 return r;
8757 }
8758 module_init(vmx_init);
8759