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