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