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