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