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