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