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