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