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