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