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