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