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