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