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