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