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