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