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