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