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