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