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