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