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