1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * derived from drivers/kvm/kvm_main.c
6 *
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright (C) 2008 Qumranet, Inc.
9 * Copyright IBM Corporation, 2008
10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11 *
12 * Authors:
13 * Avi Kivity <avi@qumranet.com>
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Amit Shah <amit.shah@qumranet.com>
16 * Ben-Ami Yassour <benami@il.ibm.com>
17 */
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19
20 #include <linux/kvm_host.h>
21 #include "irq.h"
22 #include "ioapic.h"
23 #include "mmu.h"
24 #include "i8254.h"
25 #include "tss.h"
26 #include "kvm_cache_regs.h"
27 #include "kvm_emulate.h"
28 #include "mmu/page_track.h"
29 #include "x86.h"
30 #include "cpuid.h"
31 #include "pmu.h"
32 #include "hyperv.h"
33 #include "lapic.h"
34 #include "xen.h"
35 #include "smm.h"
36
37 #include <linux/clocksource.h>
38 #include <linux/interrupt.h>
39 #include <linux/kvm.h>
40 #include <linux/fs.h>
41 #include <linux/vmalloc.h>
42 #include <linux/export.h>
43 #include <linux/moduleparam.h>
44 #include <linux/mman.h>
45 #include <linux/highmem.h>
46 #include <linux/iommu.h>
47 #include <linux/cpufreq.h>
48 #include <linux/user-return-notifier.h>
49 #include <linux/srcu.h>
50 #include <linux/slab.h>
51 #include <linux/perf_event.h>
52 #include <linux/uaccess.h>
53 #include <linux/hash.h>
54 #include <linux/pci.h>
55 #include <linux/timekeeper_internal.h>
56 #include <linux/pvclock_gtod.h>
57 #include <linux/kvm_irqfd.h>
58 #include <linux/irqbypass.h>
59 #include <linux/sched/stat.h>
60 #include <linux/sched/isolation.h>
61 #include <linux/mem_encrypt.h>
62 #include <linux/suspend.h>
63 #include <linux/smp.h>
64
65 #include <trace/events/ipi.h>
66 #include <trace/events/kvm.h>
67
68 #include <asm/debugreg.h>
69 #include <asm/msr.h>
70 #include <asm/desc.h>
71 #include <asm/mce.h>
72 #include <asm/pkru.h>
73 #include <linux/kernel_stat.h>
74 #include <asm/fpu/api.h>
75 #include <asm/fpu/xcr.h>
76 #include <asm/fpu/xstate.h>
77 #include <asm/pvclock.h>
78 #include <asm/div64.h>
79 #include <asm/irq_remapping.h>
80 #include <asm/mshyperv.h>
81 #include <asm/hypervisor.h>
82 #include <asm/tlbflush.h>
83 #include <asm/intel_pt.h>
84 #include <asm/emulate_prefix.h>
85 #include <asm/sgx.h>
86 #include <clocksource/hyperv_timer.h>
87
88 #define CREATE_TRACE_POINTS
89 #include "trace.h"
90
91 #define MAX_IO_MSRS 256
92
93 /*
94 * Note, kvm_caps fields should *never* have default values, all fields must be
95 * recomputed from scratch during vendor module load, e.g. to account for a
96 * vendor module being reloaded with different module parameters.
97 */
98 struct kvm_caps kvm_caps __read_mostly;
99 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_caps);
100
101 struct kvm_host_values kvm_host __read_mostly;
102 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_host);
103
104 #define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
105
106 #define emul_to_vcpu(ctxt) \
107 ((struct kvm_vcpu *)(ctxt)->vcpu)
108
109 /* EFER defaults:
110 * - enable syscall per default because its emulated by KVM
111 * - enable LME and LMA per default on 64 bit KVM
112 */
113 #ifdef CONFIG_X86_64
114 static
115 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
116 #else
117 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
118 #endif
119
120 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
121
122 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
123
124 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
125 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
126
127 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
128 static void process_nmi(struct kvm_vcpu *vcpu);
129 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
130 static void store_regs(struct kvm_vcpu *vcpu);
131 static int sync_regs(struct kvm_vcpu *vcpu);
132 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
133
134 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
135 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
136
137 static DEFINE_MUTEX(vendor_module_lock);
138 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu);
139 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu);
140
141 struct kvm_x86_ops kvm_x86_ops __read_mostly;
142
143 #define KVM_X86_OP(func) \
144 DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
145 *(((struct kvm_x86_ops *)0)->func));
146 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
147 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
148 #include <asm/kvm-x86-ops.h>
149 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
150 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
151
152 static bool __read_mostly ignore_msrs = 0;
153 module_param(ignore_msrs, bool, 0644);
154
155 bool __read_mostly report_ignored_msrs = true;
156 module_param(report_ignored_msrs, bool, 0644);
157 EXPORT_SYMBOL_FOR_KVM_INTERNAL(report_ignored_msrs);
158
159 unsigned int min_timer_period_us = 200;
160 module_param(min_timer_period_us, uint, 0644);
161
162 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
163 static u32 __read_mostly tsc_tolerance_ppm = 250;
164 module_param(tsc_tolerance_ppm, uint, 0644);
165
166 bool __read_mostly enable_vmware_backdoor = false;
167 module_param(enable_vmware_backdoor, bool, 0444);
168 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_vmware_backdoor);
169
170 /*
171 * Flags to manipulate forced emulation behavior (any non-zero value will
172 * enable forced emulation).
173 */
174 #define KVM_FEP_CLEAR_RFLAGS_RF BIT(1)
175 static int __read_mostly force_emulation_prefix;
176 module_param(force_emulation_prefix, int, 0644);
177
178 int __read_mostly pi_inject_timer = -1;
179 module_param(pi_inject_timer, bint, 0644);
180
181 /* Enable/disable PMU virtualization */
182 bool __read_mostly enable_pmu = true;
183 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_pmu);
184 module_param(enable_pmu, bool, 0444);
185
186 bool __read_mostly eager_page_split = true;
187 module_param(eager_page_split, bool, 0644);
188
189 /* Enable/disable SMT_RSB bug mitigation */
190 static bool __read_mostly mitigate_smt_rsb;
191 module_param(mitigate_smt_rsb, bool, 0444);
192
193 /*
194 * Restoring the host value for MSRs that are only consumed when running in
195 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
196 * returns to userspace, i.e. the kernel can run with the guest's value.
197 */
198 #define KVM_MAX_NR_USER_RETURN_MSRS 16
199
200 struct kvm_user_return_msrs {
201 struct user_return_notifier urn;
202 bool registered;
203 struct kvm_user_return_msr_values {
204 u64 host;
205 u64 curr;
206 } values[KVM_MAX_NR_USER_RETURN_MSRS];
207 };
208
209 u32 __read_mostly kvm_nr_uret_msrs;
210 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_nr_uret_msrs);
211 static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
212 static DEFINE_PER_CPU(struct kvm_user_return_msrs, user_return_msrs);
213
214 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
215 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
216 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
217 | XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
218
219 #define XFEATURE_MASK_CET_ALL (XFEATURE_MASK_CET_USER | XFEATURE_MASK_CET_KERNEL)
220 /*
221 * Note, KVM supports exposing PT to the guest, but does not support context
222 * switching PT via XSTATE (KVM's PT virtualization relies on perf; swapping
223 * PT via guest XSTATE would clobber perf state), i.e. KVM doesn't support
224 * IA32_XSS[bit 8] (guests can/must use RDMSR/WRMSR to save/restore PT MSRs).
225 */
226 #define KVM_SUPPORTED_XSS (XFEATURE_MASK_CET_ALL)
227
228 bool __read_mostly allow_smaller_maxphyaddr = 0;
229 EXPORT_SYMBOL_FOR_KVM_INTERNAL(allow_smaller_maxphyaddr);
230
231 bool __read_mostly enable_apicv = true;
232 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_apicv);
233
234 bool __read_mostly enable_ipiv = true;
235 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_ipiv);
236
237 bool __read_mostly enable_device_posted_irqs = true;
238 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_device_posted_irqs);
239
240 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
241 KVM_GENERIC_VM_STATS(),
242 STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
243 STATS_DESC_COUNTER(VM, mmu_pte_write),
244 STATS_DESC_COUNTER(VM, mmu_pde_zapped),
245 STATS_DESC_COUNTER(VM, mmu_flooded),
246 STATS_DESC_COUNTER(VM, mmu_recycled),
247 STATS_DESC_COUNTER(VM, mmu_cache_miss),
248 STATS_DESC_ICOUNTER(VM, mmu_unsync),
249 STATS_DESC_ICOUNTER(VM, pages_4k),
250 STATS_DESC_ICOUNTER(VM, pages_2m),
251 STATS_DESC_ICOUNTER(VM, pages_1g),
252 STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
253 STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
254 STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
255 };
256
257 const struct kvm_stats_header kvm_vm_stats_header = {
258 .name_size = KVM_STATS_NAME_SIZE,
259 .num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
260 .id_offset = sizeof(struct kvm_stats_header),
261 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
262 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
263 sizeof(kvm_vm_stats_desc),
264 };
265
266 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
267 KVM_GENERIC_VCPU_STATS(),
268 STATS_DESC_COUNTER(VCPU, pf_taken),
269 STATS_DESC_COUNTER(VCPU, pf_fixed),
270 STATS_DESC_COUNTER(VCPU, pf_emulate),
271 STATS_DESC_COUNTER(VCPU, pf_spurious),
272 STATS_DESC_COUNTER(VCPU, pf_fast),
273 STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
274 STATS_DESC_COUNTER(VCPU, pf_guest),
275 STATS_DESC_COUNTER(VCPU, tlb_flush),
276 STATS_DESC_COUNTER(VCPU, invlpg),
277 STATS_DESC_COUNTER(VCPU, exits),
278 STATS_DESC_COUNTER(VCPU, io_exits),
279 STATS_DESC_COUNTER(VCPU, mmio_exits),
280 STATS_DESC_COUNTER(VCPU, signal_exits),
281 STATS_DESC_COUNTER(VCPU, irq_window_exits),
282 STATS_DESC_COUNTER(VCPU, nmi_window_exits),
283 STATS_DESC_COUNTER(VCPU, l1d_flush),
284 STATS_DESC_COUNTER(VCPU, halt_exits),
285 STATS_DESC_COUNTER(VCPU, request_irq_exits),
286 STATS_DESC_COUNTER(VCPU, irq_exits),
287 STATS_DESC_COUNTER(VCPU, host_state_reload),
288 STATS_DESC_COUNTER(VCPU, fpu_reload),
289 STATS_DESC_COUNTER(VCPU, insn_emulation),
290 STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
291 STATS_DESC_COUNTER(VCPU, hypercalls),
292 STATS_DESC_COUNTER(VCPU, irq_injections),
293 STATS_DESC_COUNTER(VCPU, nmi_injections),
294 STATS_DESC_COUNTER(VCPU, req_event),
295 STATS_DESC_COUNTER(VCPU, nested_run),
296 STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
297 STATS_DESC_COUNTER(VCPU, directed_yield_successful),
298 STATS_DESC_COUNTER(VCPU, preemption_reported),
299 STATS_DESC_COUNTER(VCPU, preemption_other),
300 STATS_DESC_IBOOLEAN(VCPU, guest_mode),
301 STATS_DESC_COUNTER(VCPU, notify_window_exits),
302 };
303
304 const struct kvm_stats_header kvm_vcpu_stats_header = {
305 .name_size = KVM_STATS_NAME_SIZE,
306 .num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
307 .id_offset = sizeof(struct kvm_stats_header),
308 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
309 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
310 sizeof(kvm_vcpu_stats_desc),
311 };
312
313 static struct kmem_cache *x86_emulator_cache;
314
315 /*
316 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features) track
317 * the set of MSRs that KVM exposes to userspace through KVM_GET_MSRS,
318 * KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST. msrs_to_save holds MSRs that
319 * require host support, i.e. should be probed via RDMSR. emulated_msrs holds
320 * MSRs that KVM emulates without strictly requiring host support.
321 * msr_based_features holds MSRs that enumerate features, i.e. are effectively
322 * CPUID leafs. Note, msr_based_features isn't mutually exclusive with
323 * msrs_to_save and emulated_msrs.
324 */
325
326 static const u32 msrs_to_save_base[] = {
327 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
328 MSR_STAR,
329 #ifdef CONFIG_X86_64
330 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
331 #endif
332 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
333 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
334 MSR_IA32_SPEC_CTRL, MSR_IA32_TSX_CTRL,
335 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
336 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
337 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
338 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
339 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
340 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
341 MSR_IA32_UMWAIT_CONTROL,
342
343 MSR_IA32_XFD, MSR_IA32_XFD_ERR, MSR_IA32_XSS,
344
345 MSR_IA32_U_CET, MSR_IA32_S_CET,
346 MSR_IA32_PL0_SSP, MSR_IA32_PL1_SSP, MSR_IA32_PL2_SSP,
347 MSR_IA32_PL3_SSP, MSR_IA32_INT_SSP_TAB,
348 };
349
350 static const u32 msrs_to_save_pmu[] = {
351 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
352 MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
353 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
354 MSR_CORE_PERF_GLOBAL_CTRL,
355 MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
356
357 /* This part of MSRs should match KVM_MAX_NR_INTEL_GP_COUNTERS. */
358 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
359 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
360 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
361 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
362 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
363 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
364 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
365 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
366
367 MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
368 MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
369
370 /* This part of MSRs should match KVM_MAX_NR_AMD_GP_COUNTERS. */
371 MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
372 MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
373 MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
374 MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
375
376 MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
377 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
378 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
379 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET,
380 };
381
382 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_base) +
383 ARRAY_SIZE(msrs_to_save_pmu)];
384 static unsigned num_msrs_to_save;
385
386 static const u32 emulated_msrs_all[] = {
387 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
388 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
389
390 #ifdef CONFIG_KVM_HYPERV
391 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
392 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
393 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
394 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
395 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
396 HV_X64_MSR_RESET,
397 HV_X64_MSR_VP_INDEX,
398 HV_X64_MSR_VP_RUNTIME,
399 HV_X64_MSR_SCONTROL,
400 HV_X64_MSR_STIMER0_CONFIG,
401 HV_X64_MSR_VP_ASSIST_PAGE,
402 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
403 HV_X64_MSR_TSC_EMULATION_STATUS, HV_X64_MSR_TSC_INVARIANT_CONTROL,
404 HV_X64_MSR_SYNDBG_OPTIONS,
405 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
406 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
407 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
408 #endif
409
410 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
411 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
412
413 MSR_IA32_TSC_ADJUST,
414 MSR_IA32_TSC_DEADLINE,
415 MSR_IA32_ARCH_CAPABILITIES,
416 MSR_IA32_PERF_CAPABILITIES,
417 MSR_IA32_MISC_ENABLE,
418 MSR_IA32_MCG_STATUS,
419 MSR_IA32_MCG_CTL,
420 MSR_IA32_MCG_EXT_CTL,
421 MSR_IA32_SMBASE,
422 MSR_SMI_COUNT,
423 MSR_PLATFORM_INFO,
424 MSR_MISC_FEATURES_ENABLES,
425 MSR_AMD64_VIRT_SPEC_CTRL,
426 MSR_AMD64_TSC_RATIO,
427 MSR_IA32_POWER_CTL,
428 MSR_IA32_UCODE_REV,
429
430 /*
431 * KVM always supports the "true" VMX control MSRs, even if the host
432 * does not. The VMX MSRs as a whole are considered "emulated" as KVM
433 * doesn't strictly require them to exist in the host (ignoring that
434 * KVM would refuse to load in the first place if the core set of MSRs
435 * aren't supported).
436 */
437 MSR_IA32_VMX_BASIC,
438 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
439 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
440 MSR_IA32_VMX_TRUE_EXIT_CTLS,
441 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
442 MSR_IA32_VMX_MISC,
443 MSR_IA32_VMX_CR0_FIXED0,
444 MSR_IA32_VMX_CR4_FIXED0,
445 MSR_IA32_VMX_VMCS_ENUM,
446 MSR_IA32_VMX_PROCBASED_CTLS2,
447 MSR_IA32_VMX_EPT_VPID_CAP,
448 MSR_IA32_VMX_VMFUNC,
449
450 MSR_K7_HWCR,
451 MSR_KVM_POLL_CONTROL,
452 };
453
454 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
455 static unsigned num_emulated_msrs;
456
457 /*
458 * List of MSRs that control the existence of MSR-based features, i.e. MSRs
459 * that are effectively CPUID leafs. VMX MSRs are also included in the set of
460 * feature MSRs, but are handled separately to allow expedited lookups.
461 */
462 static const u32 msr_based_features_all_except_vmx[] = {
463 MSR_AMD64_DE_CFG,
464 MSR_IA32_UCODE_REV,
465 MSR_IA32_ARCH_CAPABILITIES,
466 MSR_IA32_PERF_CAPABILITIES,
467 MSR_PLATFORM_INFO,
468 };
469
470 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all_except_vmx) +
471 (KVM_LAST_EMULATED_VMX_MSR - KVM_FIRST_EMULATED_VMX_MSR + 1)];
472 static unsigned int num_msr_based_features;
473
474 /*
475 * All feature MSRs except uCode revID, which tracks the currently loaded uCode
476 * patch, are immutable once the vCPU model is defined.
477 */
kvm_is_immutable_feature_msr(u32 msr)478 static bool kvm_is_immutable_feature_msr(u32 msr)
479 {
480 int i;
481
482 if (msr >= KVM_FIRST_EMULATED_VMX_MSR && msr <= KVM_LAST_EMULATED_VMX_MSR)
483 return true;
484
485 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++) {
486 if (msr == msr_based_features_all_except_vmx[i])
487 return msr != MSR_IA32_UCODE_REV;
488 }
489
490 return false;
491 }
492
kvm_is_advertised_msr(u32 msr_index)493 static bool kvm_is_advertised_msr(u32 msr_index)
494 {
495 unsigned int i;
496
497 for (i = 0; i < num_msrs_to_save; i++) {
498 if (msrs_to_save[i] == msr_index)
499 return true;
500 }
501
502 for (i = 0; i < num_emulated_msrs; i++) {
503 if (emulated_msrs[i] == msr_index)
504 return true;
505 }
506
507 return false;
508 }
509
510 typedef int (*msr_access_t)(struct kvm_vcpu *vcpu, u32 index, u64 *data,
511 bool host_initiated);
512
kvm_do_msr_access(struct kvm_vcpu * vcpu,u32 msr,u64 * data,bool host_initiated,enum kvm_msr_access rw,msr_access_t msr_access_fn)513 static __always_inline int kvm_do_msr_access(struct kvm_vcpu *vcpu, u32 msr,
514 u64 *data, bool host_initiated,
515 enum kvm_msr_access rw,
516 msr_access_t msr_access_fn)
517 {
518 const char *op = rw == MSR_TYPE_W ? "wrmsr" : "rdmsr";
519 int ret;
520
521 BUILD_BUG_ON(rw != MSR_TYPE_R && rw != MSR_TYPE_W);
522
523 /*
524 * Zero the data on read failures to avoid leaking stack data to the
525 * guest and/or userspace, e.g. if the failure is ignored below.
526 */
527 ret = msr_access_fn(vcpu, msr, data, host_initiated);
528 if (ret && rw == MSR_TYPE_R)
529 *data = 0;
530
531 if (ret != KVM_MSR_RET_UNSUPPORTED)
532 return ret;
533
534 /*
535 * Userspace is allowed to read MSRs, and write '0' to MSRs, that KVM
536 * advertises to userspace, even if an MSR isn't fully supported.
537 * Simply check that @data is '0', which covers both the write '0' case
538 * and all reads (in which case @data is zeroed on failure; see above).
539 */
540 if (host_initiated && !*data && kvm_is_advertised_msr(msr))
541 return 0;
542
543 if (!ignore_msrs) {
544 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
545 op, msr, *data);
546 return ret;
547 }
548
549 if (report_ignored_msrs)
550 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n", op, msr, *data);
551
552 return 0;
553 }
554
kvm_alloc_emulator_cache(void)555 static struct kmem_cache *kvm_alloc_emulator_cache(void)
556 {
557 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
558 unsigned int size = sizeof(struct x86_emulate_ctxt);
559
560 return kmem_cache_create_usercopy("x86_emulator", size,
561 __alignof__(struct x86_emulate_ctxt),
562 SLAB_ACCOUNT, useroffset,
563 size - useroffset, NULL);
564 }
565
566 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
567
kvm_async_pf_hash_reset(struct kvm_vcpu * vcpu)568 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
569 {
570 int i;
571 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
572 vcpu->arch.apf.gfns[i] = ~0;
573 }
574
kvm_destroy_user_return_msrs(void)575 static void kvm_destroy_user_return_msrs(void)
576 {
577 int cpu;
578
579 for_each_possible_cpu(cpu)
580 WARN_ON_ONCE(per_cpu(user_return_msrs, cpu).registered);
581
582 kvm_nr_uret_msrs = 0;
583 }
584
kvm_on_user_return(struct user_return_notifier * urn)585 static void kvm_on_user_return(struct user_return_notifier *urn)
586 {
587 unsigned slot;
588 struct kvm_user_return_msrs *msrs
589 = container_of(urn, struct kvm_user_return_msrs, urn);
590 struct kvm_user_return_msr_values *values;
591
592 msrs->registered = false;
593 user_return_notifier_unregister(urn);
594
595 for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
596 values = &msrs->values[slot];
597 if (values->host != values->curr) {
598 wrmsrq(kvm_uret_msrs_list[slot], values->host);
599 values->curr = values->host;
600 }
601 }
602 }
603
kvm_probe_user_return_msr(u32 msr)604 static int kvm_probe_user_return_msr(u32 msr)
605 {
606 u64 val;
607 int ret;
608
609 preempt_disable();
610 ret = rdmsrq_safe(msr, &val);
611 if (ret)
612 goto out;
613 ret = wrmsrq_safe(msr, val);
614 out:
615 preempt_enable();
616 return ret;
617 }
618
kvm_add_user_return_msr(u32 msr)619 int kvm_add_user_return_msr(u32 msr)
620 {
621 BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
622
623 if (kvm_probe_user_return_msr(msr))
624 return -1;
625
626 kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
627 return kvm_nr_uret_msrs++;
628 }
629 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_add_user_return_msr);
630
kvm_find_user_return_msr(u32 msr)631 int kvm_find_user_return_msr(u32 msr)
632 {
633 int i;
634
635 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
636 if (kvm_uret_msrs_list[i] == msr)
637 return i;
638 }
639 return -1;
640 }
641 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_find_user_return_msr);
642
kvm_user_return_msr_cpu_online(void)643 static void kvm_user_return_msr_cpu_online(void)
644 {
645 struct kvm_user_return_msrs *msrs = this_cpu_ptr(&user_return_msrs);
646 u64 value;
647 int i;
648
649 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
650 rdmsrq_safe(kvm_uret_msrs_list[i], &value);
651 msrs->values[i].host = value;
652 msrs->values[i].curr = value;
653 }
654 }
655
kvm_user_return_register_notifier(struct kvm_user_return_msrs * msrs)656 static void kvm_user_return_register_notifier(struct kvm_user_return_msrs *msrs)
657 {
658 if (!msrs->registered) {
659 msrs->urn.on_user_return = kvm_on_user_return;
660 user_return_notifier_register(&msrs->urn);
661 msrs->registered = true;
662 }
663 }
664
kvm_set_user_return_msr(unsigned slot,u64 value,u64 mask)665 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
666 {
667 struct kvm_user_return_msrs *msrs = this_cpu_ptr(&user_return_msrs);
668 int err;
669
670 value = (value & mask) | (msrs->values[slot].host & ~mask);
671 if (value == msrs->values[slot].curr)
672 return 0;
673 err = wrmsrq_safe(kvm_uret_msrs_list[slot], value);
674 if (err)
675 return 1;
676
677 msrs->values[slot].curr = value;
678 kvm_user_return_register_notifier(msrs);
679 return 0;
680 }
681 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_user_return_msr);
682
kvm_get_user_return_msr(unsigned int slot)683 u64 kvm_get_user_return_msr(unsigned int slot)
684 {
685 return this_cpu_ptr(&user_return_msrs)->values[slot].curr;
686 }
687 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_user_return_msr);
688
drop_user_return_notifiers(void)689 static void drop_user_return_notifiers(void)
690 {
691 struct kvm_user_return_msrs *msrs = this_cpu_ptr(&user_return_msrs);
692
693 if (msrs->registered)
694 kvm_on_user_return(&msrs->urn);
695 }
696
697 /*
698 * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
699 *
700 * Hardware virtualization extension instructions may fault if a reboot turns
701 * off virtualization while processes are running. Usually after catching the
702 * fault we just panic; during reboot instead the instruction is ignored.
703 */
kvm_spurious_fault(void)704 noinstr void kvm_spurious_fault(void)
705 {
706 /* Fault while not rebooting. We want the trace. */
707 BUG_ON(!kvm_rebooting);
708 }
709 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_spurious_fault);
710
711 #define EXCPT_BENIGN 0
712 #define EXCPT_CONTRIBUTORY 1
713 #define EXCPT_PF 2
714
exception_class(int vector)715 static int exception_class(int vector)
716 {
717 switch (vector) {
718 case PF_VECTOR:
719 return EXCPT_PF;
720 case DE_VECTOR:
721 case TS_VECTOR:
722 case NP_VECTOR:
723 case SS_VECTOR:
724 case GP_VECTOR:
725 return EXCPT_CONTRIBUTORY;
726 default:
727 break;
728 }
729 return EXCPT_BENIGN;
730 }
731
732 #define EXCPT_FAULT 0
733 #define EXCPT_TRAP 1
734 #define EXCPT_ABORT 2
735 #define EXCPT_INTERRUPT 3
736 #define EXCPT_DB 4
737
exception_type(int vector)738 static int exception_type(int vector)
739 {
740 unsigned int mask;
741
742 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
743 return EXCPT_INTERRUPT;
744
745 mask = 1 << vector;
746
747 /*
748 * #DBs can be trap-like or fault-like, the caller must check other CPU
749 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
750 */
751 if (mask & (1 << DB_VECTOR))
752 return EXCPT_DB;
753
754 if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
755 return EXCPT_TRAP;
756
757 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
758 return EXCPT_ABORT;
759
760 /* Reserved exceptions will result in fault */
761 return EXCPT_FAULT;
762 }
763
kvm_deliver_exception_payload(struct kvm_vcpu * vcpu,struct kvm_queued_exception * ex)764 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
765 struct kvm_queued_exception *ex)
766 {
767 if (!ex->has_payload)
768 return;
769
770 switch (ex->vector) {
771 case DB_VECTOR:
772 /*
773 * "Certain debug exceptions may clear bit 0-3. The
774 * remaining contents of the DR6 register are never
775 * cleared by the processor".
776 */
777 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
778 /*
779 * In order to reflect the #DB exception payload in guest
780 * dr6, three components need to be considered: active low
781 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
782 * DR6_BS and DR6_BT)
783 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
784 * In the target guest dr6:
785 * FIXED_1 bits should always be set.
786 * Active low bits should be cleared if 1-setting in payload.
787 * Active high bits should be set if 1-setting in payload.
788 *
789 * Note, the payload is compatible with the pending debug
790 * exceptions/exit qualification under VMX, that active_low bits
791 * are active high in payload.
792 * So they need to be flipped for DR6.
793 */
794 vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
795 vcpu->arch.dr6 |= ex->payload;
796 vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
797
798 /*
799 * The #DB payload is defined as compatible with the 'pending
800 * debug exceptions' field under VMX, not DR6. While bit 12 is
801 * defined in the 'pending debug exceptions' field (enabled
802 * breakpoint), it is reserved and must be zero in DR6.
803 */
804 vcpu->arch.dr6 &= ~BIT(12);
805 break;
806 case PF_VECTOR:
807 vcpu->arch.cr2 = ex->payload;
808 break;
809 }
810
811 ex->has_payload = false;
812 ex->payload = 0;
813 }
814 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_deliver_exception_payload);
815
kvm_queue_exception_vmexit(struct kvm_vcpu * vcpu,unsigned int vector,bool has_error_code,u32 error_code,bool has_payload,unsigned long payload)816 static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
817 bool has_error_code, u32 error_code,
818 bool has_payload, unsigned long payload)
819 {
820 struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
821
822 ex->vector = vector;
823 ex->injected = false;
824 ex->pending = true;
825 ex->has_error_code = has_error_code;
826 ex->error_code = error_code;
827 ex->has_payload = has_payload;
828 ex->payload = payload;
829 }
830
kvm_multiple_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error,u32 error_code,bool has_payload,unsigned long payload)831 static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
832 bool has_error, u32 error_code,
833 bool has_payload, unsigned long payload)
834 {
835 u32 prev_nr;
836 int class1, class2;
837
838 kvm_make_request(KVM_REQ_EVENT, vcpu);
839
840 /*
841 * If the exception is destined for L2, morph it to a VM-Exit if L1
842 * wants to intercept the exception.
843 */
844 if (is_guest_mode(vcpu) &&
845 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
846 kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
847 has_payload, payload);
848 return;
849 }
850
851 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
852 queue:
853 vcpu->arch.exception.pending = true;
854 vcpu->arch.exception.injected = false;
855
856 vcpu->arch.exception.has_error_code = has_error;
857 vcpu->arch.exception.vector = nr;
858 vcpu->arch.exception.error_code = error_code;
859 vcpu->arch.exception.has_payload = has_payload;
860 vcpu->arch.exception.payload = payload;
861 if (!is_guest_mode(vcpu))
862 kvm_deliver_exception_payload(vcpu,
863 &vcpu->arch.exception);
864 return;
865 }
866
867 /* to check exception */
868 prev_nr = vcpu->arch.exception.vector;
869 if (prev_nr == DF_VECTOR) {
870 /* triple fault -> shutdown */
871 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
872 return;
873 }
874 class1 = exception_class(prev_nr);
875 class2 = exception_class(nr);
876 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
877 (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
878 /*
879 * Synthesize #DF. Clear the previously injected or pending
880 * exception so as not to incorrectly trigger shutdown.
881 */
882 vcpu->arch.exception.injected = false;
883 vcpu->arch.exception.pending = false;
884
885 kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
886 } else {
887 /* replace previous exception with a new one in a hope
888 that instruction re-execution will regenerate lost
889 exception */
890 goto queue;
891 }
892 }
893
kvm_queue_exception(struct kvm_vcpu * vcpu,unsigned nr)894 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
895 {
896 kvm_multiple_exception(vcpu, nr, false, 0, false, 0);
897 }
898 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception);
899
900
kvm_queue_exception_p(struct kvm_vcpu * vcpu,unsigned nr,unsigned long payload)901 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
902 unsigned long payload)
903 {
904 kvm_multiple_exception(vcpu, nr, false, 0, true, payload);
905 }
906 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_p);
907
kvm_queue_exception_e_p(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code,unsigned long payload)908 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
909 u32 error_code, unsigned long payload)
910 {
911 kvm_multiple_exception(vcpu, nr, true, error_code, true, payload);
912 }
913
kvm_requeue_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error_code,u32 error_code)914 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
915 bool has_error_code, u32 error_code)
916 {
917
918 /*
919 * On VM-Entry, an exception can be pending if and only if event
920 * injection was blocked by nested_run_pending. In that case, however,
921 * vcpu_enter_guest() requests an immediate exit, and the guest
922 * shouldn't proceed far enough to need reinjection.
923 */
924 WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
925
926 /*
927 * Do not check for interception when injecting an event for L2, as the
928 * exception was checked for intercept when it was original queued, and
929 * re-checking is incorrect if _L1_ injected the exception, in which
930 * case it's exempt from interception.
931 */
932 kvm_make_request(KVM_REQ_EVENT, vcpu);
933
934 vcpu->arch.exception.injected = true;
935 vcpu->arch.exception.has_error_code = has_error_code;
936 vcpu->arch.exception.vector = nr;
937 vcpu->arch.exception.error_code = error_code;
938 vcpu->arch.exception.has_payload = false;
939 vcpu->arch.exception.payload = 0;
940 }
941 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_requeue_exception);
942
kvm_complete_insn_gp(struct kvm_vcpu * vcpu,int err)943 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
944 {
945 if (err)
946 kvm_inject_gp(vcpu, 0);
947 else
948 return kvm_skip_emulated_instruction(vcpu);
949
950 return 1;
951 }
952 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_complete_insn_gp);
953
complete_emulated_insn_gp(struct kvm_vcpu * vcpu,int err)954 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
955 {
956 if (err) {
957 kvm_inject_gp(vcpu, 0);
958 return 1;
959 }
960
961 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
962 EMULTYPE_COMPLETE_USER_EXIT);
963 }
964
kvm_inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)965 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
966 {
967 ++vcpu->stat.pf_guest;
968
969 /*
970 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
971 * whether or not L1 wants to intercept "regular" #PF.
972 */
973 if (is_guest_mode(vcpu) && fault->async_page_fault)
974 kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
975 true, fault->error_code,
976 true, fault->address);
977 else
978 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
979 fault->address);
980 }
981
kvm_inject_emulated_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)982 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
983 struct x86_exception *fault)
984 {
985 struct kvm_mmu *fault_mmu;
986 WARN_ON_ONCE(fault->vector != PF_VECTOR);
987
988 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
989 vcpu->arch.walk_mmu;
990
991 /*
992 * Invalidate the TLB entry for the faulting address, if it exists,
993 * else the access will fault indefinitely (and to emulate hardware).
994 */
995 if ((fault->error_code & PFERR_PRESENT_MASK) &&
996 !(fault->error_code & PFERR_RSVD_MASK))
997 kvm_mmu_invalidate_addr(vcpu, fault_mmu, fault->address,
998 KVM_MMU_ROOT_CURRENT);
999
1000 fault_mmu->inject_page_fault(vcpu, fault);
1001 }
1002 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_emulated_page_fault);
1003
kvm_inject_nmi(struct kvm_vcpu * vcpu)1004 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
1005 {
1006 atomic_inc(&vcpu->arch.nmi_queued);
1007 kvm_make_request(KVM_REQ_NMI, vcpu);
1008 }
1009
kvm_queue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)1010 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
1011 {
1012 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0);
1013 }
1014 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_e);
1015
1016 /*
1017 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
1018 * a #GP and return false.
1019 */
kvm_require_cpl(struct kvm_vcpu * vcpu,int required_cpl)1020 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
1021 {
1022 if (kvm_x86_call(get_cpl)(vcpu) <= required_cpl)
1023 return true;
1024 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
1025 return false;
1026 }
1027
kvm_require_dr(struct kvm_vcpu * vcpu,int dr)1028 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
1029 {
1030 if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
1031 return true;
1032
1033 kvm_queue_exception(vcpu, UD_VECTOR);
1034 return false;
1035 }
1036 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_require_dr);
1037
kvm_pv_async_pf_enabled(struct kvm_vcpu * vcpu)1038 static bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
1039 {
1040 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
1041
1042 return (vcpu->arch.apf.msr_en_val & mask) == mask;
1043 }
1044
pdptr_rsvd_bits(struct kvm_vcpu * vcpu)1045 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
1046 {
1047 return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
1048 }
1049
1050 /*
1051 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
1052 */
load_pdptrs(struct kvm_vcpu * vcpu,unsigned long cr3)1053 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
1054 {
1055 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
1056 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
1057 gpa_t real_gpa;
1058 int i;
1059 int ret;
1060 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
1061
1062 /*
1063 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
1064 * to an L1 GPA.
1065 */
1066 real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
1067 PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
1068 if (real_gpa == INVALID_GPA)
1069 return 0;
1070
1071 /* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
1072 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
1073 cr3 & GENMASK(11, 5), sizeof(pdpte));
1074 if (ret < 0)
1075 return 0;
1076
1077 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
1078 if ((pdpte[i] & PT_PRESENT_MASK) &&
1079 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
1080 return 0;
1081 }
1082 }
1083
1084 /*
1085 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
1086 * Shadow page roots need to be reconstructed instead.
1087 */
1088 if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
1089 kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
1090
1091 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
1092 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
1093 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
1094 vcpu->arch.pdptrs_from_userspace = false;
1095
1096 return 1;
1097 }
1098 EXPORT_SYMBOL_FOR_KVM_INTERNAL(load_pdptrs);
1099
kvm_is_valid_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1100 static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1101 {
1102 #ifdef CONFIG_X86_64
1103 if (cr0 & 0xffffffff00000000UL)
1104 return false;
1105 #endif
1106
1107 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
1108 return false;
1109
1110 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
1111 return false;
1112
1113 return kvm_x86_call(is_valid_cr0)(vcpu, cr0);
1114 }
1115
kvm_post_set_cr0(struct kvm_vcpu * vcpu,unsigned long old_cr0,unsigned long cr0)1116 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
1117 {
1118 /*
1119 * CR0.WP is incorporated into the MMU role, but only for non-nested,
1120 * indirect shadow MMUs. If paging is disabled, no updates are needed
1121 * as there are no permission bits to emulate. If TDP is enabled, the
1122 * MMU's metadata needs to be updated, e.g. so that emulating guest
1123 * translations does the right thing, but there's no need to unload the
1124 * root as CR0.WP doesn't affect SPTEs.
1125 */
1126 if ((cr0 ^ old_cr0) == X86_CR0_WP) {
1127 if (!(cr0 & X86_CR0_PG))
1128 return;
1129
1130 if (tdp_enabled) {
1131 kvm_init_mmu(vcpu);
1132 return;
1133 }
1134 }
1135
1136 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
1137 /*
1138 * Clearing CR0.PG is defined to flush the TLB from the guest's
1139 * perspective.
1140 */
1141 if (!(cr0 & X86_CR0_PG))
1142 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1143 /*
1144 * Check for async #PF completion events when enabling paging,
1145 * as the vCPU may have previously encountered async #PFs (it's
1146 * entirely legal for the guest to toggle paging on/off without
1147 * waiting for the async #PF queue to drain).
1148 */
1149 else if (kvm_pv_async_pf_enabled(vcpu))
1150 kvm_make_request(KVM_REQ_APF_READY, vcpu);
1151 }
1152
1153 if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
1154 kvm_mmu_reset_context(vcpu);
1155 }
1156 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_post_set_cr0);
1157
kvm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1158 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1159 {
1160 unsigned long old_cr0 = kvm_read_cr0(vcpu);
1161
1162 if (!kvm_is_valid_cr0(vcpu, cr0))
1163 return 1;
1164
1165 cr0 |= X86_CR0_ET;
1166
1167 /* Write to CR0 reserved bits are ignored, even on Intel. */
1168 cr0 &= ~CR0_RESERVED_BITS;
1169
1170 #ifdef CONFIG_X86_64
1171 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
1172 (cr0 & X86_CR0_PG)) {
1173 int cs_db, cs_l;
1174
1175 if (!is_pae(vcpu))
1176 return 1;
1177 kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
1178 if (cs_l)
1179 return 1;
1180 }
1181 #endif
1182 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
1183 is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
1184 !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1185 return 1;
1186
1187 if (!(cr0 & X86_CR0_PG) &&
1188 (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
1189 return 1;
1190
1191 if (!(cr0 & X86_CR0_WP) && kvm_is_cr4_bit_set(vcpu, X86_CR4_CET))
1192 return 1;
1193
1194 kvm_x86_call(set_cr0)(vcpu, cr0);
1195
1196 kvm_post_set_cr0(vcpu, old_cr0, cr0);
1197
1198 return 0;
1199 }
1200 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr0);
1201
kvm_lmsw(struct kvm_vcpu * vcpu,unsigned long msw)1202 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
1203 {
1204 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
1205 }
1206 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_lmsw);
1207
kvm_load_xfeatures(struct kvm_vcpu * vcpu,bool load_guest)1208 static void kvm_load_xfeatures(struct kvm_vcpu *vcpu, bool load_guest)
1209 {
1210 if (vcpu->arch.guest_state_protected)
1211 return;
1212
1213 if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE))
1214 return;
1215
1216 if (vcpu->arch.xcr0 != kvm_host.xcr0)
1217 xsetbv(XCR_XFEATURE_ENABLED_MASK,
1218 load_guest ? vcpu->arch.xcr0 : kvm_host.xcr0);
1219
1220 if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1221 vcpu->arch.ia32_xss != kvm_host.xss)
1222 wrmsrq(MSR_IA32_XSS, load_guest ? vcpu->arch.ia32_xss : kvm_host.xss);
1223 }
1224
kvm_load_guest_pkru(struct kvm_vcpu * vcpu)1225 static void kvm_load_guest_pkru(struct kvm_vcpu *vcpu)
1226 {
1227 if (vcpu->arch.guest_state_protected)
1228 return;
1229
1230 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1231 vcpu->arch.pkru != vcpu->arch.host_pkru &&
1232 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1233 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
1234 wrpkru(vcpu->arch.pkru);
1235 }
1236
kvm_load_host_pkru(struct kvm_vcpu * vcpu)1237 static void kvm_load_host_pkru(struct kvm_vcpu *vcpu)
1238 {
1239 if (vcpu->arch.guest_state_protected)
1240 return;
1241
1242 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1243 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1244 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
1245 vcpu->arch.pkru = rdpkru();
1246 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1247 wrpkru(vcpu->arch.host_pkru);
1248 }
1249 }
1250
1251 #ifdef CONFIG_X86_64
kvm_guest_supported_xfd(struct kvm_vcpu * vcpu)1252 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1253 {
1254 return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
1255 }
1256 #endif
1257
__kvm_set_xcr(struct kvm_vcpu * vcpu,u32 index,u64 xcr)1258 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1259 {
1260 u64 xcr0 = xcr;
1261 u64 old_xcr0 = vcpu->arch.xcr0;
1262 u64 valid_bits;
1263
1264 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
1265 if (index != XCR_XFEATURE_ENABLED_MASK)
1266 return 1;
1267 if (!(xcr0 & XFEATURE_MASK_FP))
1268 return 1;
1269 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1270 return 1;
1271
1272 /*
1273 * Do not allow the guest to set bits that we do not support
1274 * saving. However, xcr0 bit 0 is always set, even if the
1275 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1276 */
1277 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
1278 if (xcr0 & ~valid_bits)
1279 return 1;
1280
1281 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1282 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1283 return 1;
1284
1285 if (xcr0 & XFEATURE_MASK_AVX512) {
1286 if (!(xcr0 & XFEATURE_MASK_YMM))
1287 return 1;
1288 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1289 return 1;
1290 }
1291
1292 if ((xcr0 & XFEATURE_MASK_XTILE) &&
1293 ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1294 return 1;
1295
1296 vcpu->arch.xcr0 = xcr0;
1297
1298 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1299 vcpu->arch.cpuid_dynamic_bits_dirty = true;
1300 return 0;
1301 }
1302 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_set_xcr);
1303
kvm_emulate_xsetbv(struct kvm_vcpu * vcpu)1304 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1305 {
1306 /* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
1307 if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
1308 __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1309 kvm_inject_gp(vcpu, 0);
1310 return 1;
1311 }
1312
1313 return kvm_skip_emulated_instruction(vcpu);
1314 }
1315 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_xsetbv);
1316
kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1317 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1318 {
1319 return __kvm_is_valid_cr4(vcpu, cr4) &&
1320 kvm_x86_call(is_valid_cr4)(vcpu, cr4);
1321 }
1322
kvm_post_set_cr4(struct kvm_vcpu * vcpu,unsigned long old_cr4,unsigned long cr4)1323 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1324 {
1325 if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1326 kvm_mmu_reset_context(vcpu);
1327
1328 /*
1329 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1330 * according to the SDM; however, stale prev_roots could be reused
1331 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1332 * free them all. This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1333 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1334 * so fall through.
1335 */
1336 if (!tdp_enabled &&
1337 (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1338 kvm_mmu_unload(vcpu);
1339
1340 /*
1341 * The TLB has to be flushed for all PCIDs if any of the following
1342 * (architecturally required) changes happen:
1343 * - CR4.PCIDE is changed from 1 to 0
1344 * - CR4.PGE is toggled
1345 *
1346 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1347 */
1348 if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1349 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1350 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1351
1352 /*
1353 * The TLB has to be flushed for the current PCID if any of the
1354 * following (architecturally required) changes happen:
1355 * - CR4.SMEP is changed from 0 to 1
1356 * - CR4.PAE is toggled
1357 */
1358 else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1359 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1360 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1361
1362 }
1363 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_post_set_cr4);
1364
kvm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1365 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1366 {
1367 unsigned long old_cr4 = kvm_read_cr4(vcpu);
1368
1369 if (!kvm_is_valid_cr4(vcpu, cr4))
1370 return 1;
1371
1372 if (is_long_mode(vcpu)) {
1373 if (!(cr4 & X86_CR4_PAE))
1374 return 1;
1375 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1376 return 1;
1377 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1378 && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1379 && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1380 return 1;
1381
1382 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1383 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1384 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1385 return 1;
1386 }
1387
1388 if ((cr4 & X86_CR4_CET) && !kvm_is_cr0_bit_set(vcpu, X86_CR0_WP))
1389 return 1;
1390
1391 kvm_x86_call(set_cr4)(vcpu, cr4);
1392
1393 kvm_post_set_cr4(vcpu, old_cr4, cr4);
1394
1395 return 0;
1396 }
1397 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr4);
1398
kvm_invalidate_pcid(struct kvm_vcpu * vcpu,unsigned long pcid)1399 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1400 {
1401 struct kvm_mmu *mmu = vcpu->arch.mmu;
1402 unsigned long roots_to_free = 0;
1403 int i;
1404
1405 /*
1406 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1407 * this is reachable when running EPT=1 and unrestricted_guest=0, and
1408 * also via the emulator. KVM's TDP page tables are not in the scope of
1409 * the invalidation, but the guest's TLB entries need to be flushed as
1410 * the CPU may have cached entries in its TLB for the target PCID.
1411 */
1412 if (unlikely(tdp_enabled)) {
1413 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1414 return;
1415 }
1416
1417 /*
1418 * If neither the current CR3 nor any of the prev_roots use the given
1419 * PCID, then nothing needs to be done here because a resync will
1420 * happen anyway before switching to any other CR3.
1421 */
1422 if (kvm_get_active_pcid(vcpu) == pcid) {
1423 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1424 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1425 }
1426
1427 /*
1428 * If PCID is disabled, there is no need to free prev_roots even if the
1429 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1430 * with PCIDE=0.
1431 */
1432 if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
1433 return;
1434
1435 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1436 if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1437 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1438
1439 kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1440 }
1441
kvm_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)1442 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1443 {
1444 bool skip_tlb_flush = false;
1445 unsigned long pcid = 0;
1446 #ifdef CONFIG_X86_64
1447 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)) {
1448 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1449 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1450 pcid = cr3 & X86_CR3_PCID_MASK;
1451 }
1452 #endif
1453
1454 /* PDPTRs are always reloaded for PAE paging. */
1455 if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1456 goto handle_tlb_flush;
1457
1458 /*
1459 * Do not condition the GPA check on long mode, this helper is used to
1460 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1461 * the current vCPU mode is accurate.
1462 */
1463 if (!kvm_vcpu_is_legal_cr3(vcpu, cr3))
1464 return 1;
1465
1466 if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1467 return 1;
1468
1469 if (cr3 != kvm_read_cr3(vcpu))
1470 kvm_mmu_new_pgd(vcpu, cr3);
1471
1472 vcpu->arch.cr3 = cr3;
1473 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1474 /* Do not call post_set_cr3, we do not get here for confidential guests. */
1475
1476 handle_tlb_flush:
1477 /*
1478 * A load of CR3 that flushes the TLB flushes only the current PCID,
1479 * even if PCID is disabled, in which case PCID=0 is flushed. It's a
1480 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1481 * and it's impossible to use a non-zero PCID when PCID is disabled,
1482 * i.e. only PCID=0 can be relevant.
1483 */
1484 if (!skip_tlb_flush)
1485 kvm_invalidate_pcid(vcpu, pcid);
1486
1487 return 0;
1488 }
1489 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr3);
1490
kvm_set_cr8(struct kvm_vcpu * vcpu,unsigned long cr8)1491 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1492 {
1493 if (cr8 & CR8_RESERVED_BITS)
1494 return 1;
1495 if (lapic_in_kernel(vcpu))
1496 kvm_lapic_set_tpr(vcpu, cr8);
1497 else
1498 vcpu->arch.cr8 = cr8;
1499 return 0;
1500 }
1501 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr8);
1502
kvm_get_cr8(struct kvm_vcpu * vcpu)1503 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1504 {
1505 if (lapic_in_kernel(vcpu))
1506 return kvm_lapic_get_cr8(vcpu);
1507 else
1508 return vcpu->arch.cr8;
1509 }
1510 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_cr8);
1511
kvm_update_dr0123(struct kvm_vcpu * vcpu)1512 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1513 {
1514 int i;
1515
1516 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1517 for (i = 0; i < KVM_NR_DB_REGS; i++)
1518 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1519 }
1520 }
1521
kvm_update_dr7(struct kvm_vcpu * vcpu)1522 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1523 {
1524 unsigned long dr7;
1525
1526 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1527 dr7 = vcpu->arch.guest_debug_dr7;
1528 else
1529 dr7 = vcpu->arch.dr7;
1530 kvm_x86_call(set_dr7)(vcpu, dr7);
1531 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1532 if (dr7 & DR7_BP_EN_MASK)
1533 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1534 }
1535 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_update_dr7);
1536
kvm_dr6_fixed(struct kvm_vcpu * vcpu)1537 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1538 {
1539 u64 fixed = DR6_FIXED_1;
1540
1541 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_RTM))
1542 fixed |= DR6_RTM;
1543
1544 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1545 fixed |= DR6_BUS_LOCK;
1546 return fixed;
1547 }
1548
kvm_set_dr(struct kvm_vcpu * vcpu,int dr,unsigned long val)1549 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1550 {
1551 size_t size = ARRAY_SIZE(vcpu->arch.db);
1552
1553 switch (dr) {
1554 case 0 ... 3:
1555 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1556 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1557 vcpu->arch.eff_db[dr] = val;
1558 break;
1559 case 4:
1560 case 6:
1561 if (!kvm_dr6_valid(val))
1562 return 1; /* #GP */
1563 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1564 break;
1565 case 5:
1566 default: /* 7 */
1567 if (!kvm_dr7_valid(val))
1568 return 1; /* #GP */
1569 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1570 kvm_update_dr7(vcpu);
1571 break;
1572 }
1573
1574 return 0;
1575 }
1576 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_dr);
1577
kvm_get_dr(struct kvm_vcpu * vcpu,int dr)1578 unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr)
1579 {
1580 size_t size = ARRAY_SIZE(vcpu->arch.db);
1581
1582 switch (dr) {
1583 case 0 ... 3:
1584 return vcpu->arch.db[array_index_nospec(dr, size)];
1585 case 4:
1586 case 6:
1587 return vcpu->arch.dr6;
1588 case 5:
1589 default: /* 7 */
1590 return vcpu->arch.dr7;
1591 }
1592 }
1593 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_dr);
1594
kvm_emulate_rdpmc(struct kvm_vcpu * vcpu)1595 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1596 {
1597 u32 pmc = kvm_rcx_read(vcpu);
1598 u64 data;
1599
1600 if (kvm_pmu_rdpmc(vcpu, pmc, &data)) {
1601 kvm_inject_gp(vcpu, 0);
1602 return 1;
1603 }
1604
1605 kvm_rax_write(vcpu, (u32)data);
1606 kvm_rdx_write(vcpu, data >> 32);
1607 return kvm_skip_emulated_instruction(vcpu);
1608 }
1609 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdpmc);
1610
1611 /*
1612 * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1613 * does not yet virtualize. These include:
1614 * 10 - MISC_PACKAGE_CTRLS
1615 * 11 - ENERGY_FILTERING_CTL
1616 * 12 - DOITM
1617 * 18 - FB_CLEAR_CTRL
1618 * 21 - XAPIC_DISABLE_STATUS
1619 * 23 - OVERCLOCKING_STATUS
1620 */
1621
1622 #define KVM_SUPPORTED_ARCH_CAP \
1623 (ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1624 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1625 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1626 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1627 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
1628 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO | ARCH_CAP_ITS_NO)
1629
kvm_get_arch_capabilities(void)1630 static u64 kvm_get_arch_capabilities(void)
1631 {
1632 u64 data = kvm_host.arch_capabilities & KVM_SUPPORTED_ARCH_CAP;
1633
1634 /*
1635 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1636 * the nested hypervisor runs with NX huge pages. If it is not,
1637 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1638 * L1 guests, so it need not worry about its own (L2) guests.
1639 */
1640 data |= ARCH_CAP_PSCHANGE_MC_NO;
1641
1642 /*
1643 * If we're doing cache flushes (either "always" or "cond")
1644 * we will do one whenever the guest does a vmlaunch/vmresume.
1645 * If an outer hypervisor is doing the cache flush for us
1646 * (ARCH_CAP_SKIP_VMENTRY_L1DFLUSH), we can safely pass that
1647 * capability to the guest too, and if EPT is disabled we're not
1648 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1649 * require a nested hypervisor to do a flush of its own.
1650 */
1651 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1652 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1653
1654 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1655 data |= ARCH_CAP_RDCL_NO;
1656 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1657 data |= ARCH_CAP_SSB_NO;
1658 if (!boot_cpu_has_bug(X86_BUG_MDS))
1659 data |= ARCH_CAP_MDS_NO;
1660 if (!boot_cpu_has_bug(X86_BUG_RFDS))
1661 data |= ARCH_CAP_RFDS_NO;
1662 if (!boot_cpu_has_bug(X86_BUG_ITS))
1663 data |= ARCH_CAP_ITS_NO;
1664
1665 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1666 /*
1667 * If RTM=0 because the kernel has disabled TSX, the host might
1668 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1669 * and therefore knows that there cannot be TAA) but keep
1670 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1671 * and we want to allow migrating those guests to tsx=off hosts.
1672 */
1673 data &= ~ARCH_CAP_TAA_NO;
1674 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1675 data |= ARCH_CAP_TAA_NO;
1676 } else {
1677 /*
1678 * Nothing to do here; we emulate TSX_CTRL if present on the
1679 * host so the guest can choose between disabling TSX or
1680 * using VERW to clear CPU buffers.
1681 */
1682 }
1683
1684 if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1685 data |= ARCH_CAP_GDS_NO;
1686
1687 return data;
1688 }
1689
kvm_get_feature_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1690 static int kvm_get_feature_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1691 bool host_initiated)
1692 {
1693 WARN_ON_ONCE(!host_initiated);
1694
1695 switch (index) {
1696 case MSR_IA32_ARCH_CAPABILITIES:
1697 *data = kvm_get_arch_capabilities();
1698 break;
1699 case MSR_IA32_PERF_CAPABILITIES:
1700 *data = kvm_caps.supported_perf_cap;
1701 break;
1702 case MSR_PLATFORM_INFO:
1703 *data = MSR_PLATFORM_INFO_CPUID_FAULT;
1704 break;
1705 case MSR_IA32_UCODE_REV:
1706 rdmsrq_safe(index, data);
1707 break;
1708 default:
1709 return kvm_x86_call(get_feature_msr)(index, data);
1710 }
1711 return 0;
1712 }
1713
do_get_feature_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)1714 static int do_get_feature_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1715 {
1716 return kvm_do_msr_access(vcpu, index, data, true, MSR_TYPE_R,
1717 kvm_get_feature_msr);
1718 }
1719
__kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1720 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1721 {
1722 if (efer & EFER_AUTOIBRS && !guest_cpu_cap_has(vcpu, X86_FEATURE_AUTOIBRS))
1723 return false;
1724
1725 if (efer & EFER_FFXSR && !guest_cpu_cap_has(vcpu, X86_FEATURE_FXSR_OPT))
1726 return false;
1727
1728 if (efer & EFER_SVME && !guest_cpu_cap_has(vcpu, X86_FEATURE_SVM))
1729 return false;
1730
1731 if (efer & (EFER_LME | EFER_LMA) &&
1732 !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1733 return false;
1734
1735 if (efer & EFER_NX && !guest_cpu_cap_has(vcpu, X86_FEATURE_NX))
1736 return false;
1737
1738 return true;
1739
1740 }
kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1741 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1742 {
1743 if (efer & efer_reserved_bits)
1744 return false;
1745
1746 return __kvm_valid_efer(vcpu, efer);
1747 }
1748 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_valid_efer);
1749
set_efer(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1750 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1751 {
1752 u64 old_efer = vcpu->arch.efer;
1753 u64 efer = msr_info->data;
1754 int r;
1755
1756 if (efer & efer_reserved_bits)
1757 return 1;
1758
1759 if (!msr_info->host_initiated) {
1760 if (!__kvm_valid_efer(vcpu, efer))
1761 return 1;
1762
1763 if (is_paging(vcpu) &&
1764 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1765 return 1;
1766 }
1767
1768 efer &= ~EFER_LMA;
1769 efer |= vcpu->arch.efer & EFER_LMA;
1770
1771 r = kvm_x86_call(set_efer)(vcpu, efer);
1772 if (r) {
1773 WARN_ON(r > 0);
1774 return r;
1775 }
1776
1777 if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1778 kvm_mmu_reset_context(vcpu);
1779
1780 if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1781 (efer & EFER_SVME))
1782 kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1783
1784 return 0;
1785 }
1786
kvm_enable_efer_bits(u64 mask)1787 void kvm_enable_efer_bits(u64 mask)
1788 {
1789 efer_reserved_bits &= ~mask;
1790 }
1791 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_enable_efer_bits);
1792
kvm_msr_allowed(struct kvm_vcpu * vcpu,u32 index,u32 type)1793 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1794 {
1795 struct kvm_x86_msr_filter *msr_filter;
1796 struct msr_bitmap_range *ranges;
1797 struct kvm *kvm = vcpu->kvm;
1798 bool allowed;
1799 int idx;
1800 u32 i;
1801
1802 /* x2APIC MSRs do not support filtering. */
1803 if (index >= 0x800 && index <= 0x8ff)
1804 return true;
1805
1806 idx = srcu_read_lock(&kvm->srcu);
1807
1808 msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1809 if (!msr_filter) {
1810 allowed = true;
1811 goto out;
1812 }
1813
1814 allowed = msr_filter->default_allow;
1815 ranges = msr_filter->ranges;
1816
1817 for (i = 0; i < msr_filter->count; i++) {
1818 u32 start = ranges[i].base;
1819 u32 end = start + ranges[i].nmsrs;
1820 u32 flags = ranges[i].flags;
1821 unsigned long *bitmap = ranges[i].bitmap;
1822
1823 if ((index >= start) && (index < end) && (flags & type)) {
1824 allowed = test_bit(index - start, bitmap);
1825 break;
1826 }
1827 }
1828
1829 out:
1830 srcu_read_unlock(&kvm->srcu, idx);
1831
1832 return allowed;
1833 }
1834 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_msr_allowed);
1835
1836 /*
1837 * Write @data into the MSR specified by @index. Select MSR specific fault
1838 * checks are bypassed if @host_initiated is %true.
1839 * Returns 0 on success, non-0 otherwise.
1840 * Assumes vcpu_load() was already called.
1841 */
__kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1842 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1843 bool host_initiated)
1844 {
1845 struct msr_data msr;
1846
1847 switch (index) {
1848 case MSR_FS_BASE:
1849 case MSR_GS_BASE:
1850 case MSR_KERNEL_GS_BASE:
1851 case MSR_CSTAR:
1852 case MSR_LSTAR:
1853 if (is_noncanonical_msr_address(data, vcpu))
1854 return 1;
1855 break;
1856 case MSR_IA32_SYSENTER_EIP:
1857 case MSR_IA32_SYSENTER_ESP:
1858 /*
1859 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1860 * non-canonical address is written on Intel but not on
1861 * AMD (which ignores the top 32-bits, because it does
1862 * not implement 64-bit SYSENTER).
1863 *
1864 * 64-bit code should hence be able to write a non-canonical
1865 * value on AMD. Making the address canonical ensures that
1866 * vmentry does not fail on Intel after writing a non-canonical
1867 * value, and that something deterministic happens if the guest
1868 * invokes 64-bit SYSENTER.
1869 */
1870 data = __canonical_address(data, max_host_virt_addr_bits());
1871 break;
1872 case MSR_TSC_AUX:
1873 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1874 return 1;
1875
1876 if (!host_initiated &&
1877 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1878 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1879 return 1;
1880
1881 /*
1882 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1883 * incomplete and conflicting architectural behavior. Current
1884 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1885 * reserved and always read as zeros. Enforce Intel's reserved
1886 * bits check if the guest CPU is Intel compatible, otherwise
1887 * clear the bits. This ensures cross-vendor migration will
1888 * provide consistent behavior for the guest.
1889 */
1890 if (guest_cpuid_is_intel_compatible(vcpu) && (data >> 32) != 0)
1891 return 1;
1892
1893 data = (u32)data;
1894 break;
1895 case MSR_IA32_U_CET:
1896 case MSR_IA32_S_CET:
1897 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
1898 !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT))
1899 return KVM_MSR_RET_UNSUPPORTED;
1900 if (!kvm_is_valid_u_s_cet(vcpu, data))
1901 return 1;
1902 break;
1903 case MSR_KVM_INTERNAL_GUEST_SSP:
1904 if (!host_initiated)
1905 return 1;
1906 fallthrough;
1907 /*
1908 * Note that the MSR emulation here is flawed when a vCPU
1909 * doesn't support the Intel 64 architecture. The expected
1910 * architectural behavior in this case is that the upper 32
1911 * bits do not exist and should always read '0'. However,
1912 * because the actual hardware on which the virtual CPU is
1913 * running does support Intel 64, XRSTORS/XSAVES in the
1914 * guest could observe behavior that violates the
1915 * architecture. Intercepting XRSTORS/XSAVES for this
1916 * special case isn't deemed worthwhile.
1917 */
1918 case MSR_IA32_PL0_SSP ... MSR_IA32_INT_SSP_TAB:
1919 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
1920 return KVM_MSR_RET_UNSUPPORTED;
1921 /*
1922 * MSR_IA32_INT_SSP_TAB is not present on processors that do
1923 * not support Intel 64 architecture.
1924 */
1925 if (index == MSR_IA32_INT_SSP_TAB && !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1926 return KVM_MSR_RET_UNSUPPORTED;
1927 if (is_noncanonical_msr_address(data, vcpu))
1928 return 1;
1929 /* All SSP MSRs except MSR_IA32_INT_SSP_TAB must be 4-byte aligned */
1930 if (index != MSR_IA32_INT_SSP_TAB && !IS_ALIGNED(data, 4))
1931 return 1;
1932 break;
1933 }
1934
1935 msr.data = data;
1936 msr.index = index;
1937 msr.host_initiated = host_initiated;
1938
1939 return kvm_x86_call(set_msr)(vcpu, &msr);
1940 }
1941
_kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1942 static int _kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1943 bool host_initiated)
1944 {
1945 return __kvm_set_msr(vcpu, index, *data, host_initiated);
1946 }
1947
kvm_set_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1948 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1949 u32 index, u64 data, bool host_initiated)
1950 {
1951 return kvm_do_msr_access(vcpu, index, &data, host_initiated, MSR_TYPE_W,
1952 _kvm_set_msr);
1953 }
1954
1955 /*
1956 * Read the MSR specified by @index into @data. Select MSR specific fault
1957 * checks are bypassed if @host_initiated is %true.
1958 * Returns 0 on success, non-0 otherwise.
1959 * Assumes vcpu_load() was already called.
1960 */
__kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1961 static int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1962 bool host_initiated)
1963 {
1964 struct msr_data msr;
1965 int ret;
1966
1967 switch (index) {
1968 case MSR_TSC_AUX:
1969 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1970 return 1;
1971
1972 if (!host_initiated &&
1973 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1974 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1975 return 1;
1976 break;
1977 case MSR_IA32_U_CET:
1978 case MSR_IA32_S_CET:
1979 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
1980 !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT))
1981 return KVM_MSR_RET_UNSUPPORTED;
1982 break;
1983 case MSR_KVM_INTERNAL_GUEST_SSP:
1984 if (!host_initiated)
1985 return 1;
1986 fallthrough;
1987 case MSR_IA32_PL0_SSP ... MSR_IA32_INT_SSP_TAB:
1988 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
1989 return KVM_MSR_RET_UNSUPPORTED;
1990 break;
1991 }
1992
1993 msr.index = index;
1994 msr.host_initiated = host_initiated;
1995
1996 ret = kvm_x86_call(get_msr)(vcpu, &msr);
1997 if (!ret)
1998 *data = msr.data;
1999 return ret;
2000 }
2001
kvm_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2002 int kvm_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2003 {
2004 return __kvm_set_msr(vcpu, index, data, true);
2005 }
2006
kvm_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2007 int kvm_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2008 {
2009 return __kvm_get_msr(vcpu, index, data, true);
2010 }
2011
kvm_get_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)2012 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
2013 u32 index, u64 *data, bool host_initiated)
2014 {
2015 return kvm_do_msr_access(vcpu, index, data, host_initiated, MSR_TYPE_R,
2016 __kvm_get_msr);
2017 }
2018
__kvm_emulate_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2019 int __kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2020 {
2021 return kvm_get_msr_ignored_check(vcpu, index, data, false);
2022 }
2023 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_emulate_msr_read);
2024
__kvm_emulate_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2025 int __kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2026 {
2027 return kvm_set_msr_ignored_check(vcpu, index, data, false);
2028 }
2029 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_emulate_msr_write);
2030
kvm_emulate_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2031 int kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2032 {
2033 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
2034 return KVM_MSR_RET_FILTERED;
2035
2036 return __kvm_emulate_msr_read(vcpu, index, data);
2037 }
2038 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_read);
2039
kvm_emulate_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2040 int kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2041 {
2042 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
2043 return KVM_MSR_RET_FILTERED;
2044
2045 return __kvm_emulate_msr_write(vcpu, index, data);
2046 }
2047 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_write);
2048
2049
complete_userspace_rdmsr(struct kvm_vcpu * vcpu)2050 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
2051 {
2052 if (!vcpu->run->msr.error) {
2053 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
2054 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
2055 }
2056 }
2057
complete_emulated_msr_access(struct kvm_vcpu * vcpu)2058 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
2059 {
2060 return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
2061 }
2062
complete_emulated_rdmsr(struct kvm_vcpu * vcpu)2063 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
2064 {
2065 complete_userspace_rdmsr(vcpu);
2066 return complete_emulated_msr_access(vcpu);
2067 }
2068
complete_fast_msr_access(struct kvm_vcpu * vcpu)2069 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
2070 {
2071 return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
2072 }
2073
complete_fast_rdmsr(struct kvm_vcpu * vcpu)2074 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
2075 {
2076 complete_userspace_rdmsr(vcpu);
2077 return complete_fast_msr_access(vcpu);
2078 }
2079
complete_fast_rdmsr_imm(struct kvm_vcpu * vcpu)2080 static int complete_fast_rdmsr_imm(struct kvm_vcpu *vcpu)
2081 {
2082 if (!vcpu->run->msr.error)
2083 kvm_register_write(vcpu, vcpu->arch.cui_rdmsr_imm_reg,
2084 vcpu->run->msr.data);
2085
2086 return complete_fast_msr_access(vcpu);
2087 }
2088
kvm_msr_reason(int r)2089 static u64 kvm_msr_reason(int r)
2090 {
2091 switch (r) {
2092 case KVM_MSR_RET_UNSUPPORTED:
2093 return KVM_MSR_EXIT_REASON_UNKNOWN;
2094 case KVM_MSR_RET_FILTERED:
2095 return KVM_MSR_EXIT_REASON_FILTER;
2096 default:
2097 return KVM_MSR_EXIT_REASON_INVAL;
2098 }
2099 }
2100
kvm_msr_user_space(struct kvm_vcpu * vcpu,u32 index,u32 exit_reason,u64 data,int (* completion)(struct kvm_vcpu * vcpu),int r)2101 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
2102 u32 exit_reason, u64 data,
2103 int (*completion)(struct kvm_vcpu *vcpu),
2104 int r)
2105 {
2106 u64 msr_reason = kvm_msr_reason(r);
2107
2108 /* Check if the user wanted to know about this MSR fault */
2109 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2110 return 0;
2111
2112 vcpu->run->exit_reason = exit_reason;
2113 vcpu->run->msr.error = 0;
2114 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2115 vcpu->run->msr.reason = msr_reason;
2116 vcpu->run->msr.index = index;
2117 vcpu->run->msr.data = data;
2118 vcpu->arch.complete_userspace_io = completion;
2119
2120 return 1;
2121 }
2122
__kvm_emulate_rdmsr(struct kvm_vcpu * vcpu,u32 msr,int reg,int (* complete_rdmsr)(struct kvm_vcpu *))2123 static int __kvm_emulate_rdmsr(struct kvm_vcpu *vcpu, u32 msr, int reg,
2124 int (*complete_rdmsr)(struct kvm_vcpu *))
2125 {
2126 u64 data;
2127 int r;
2128
2129 r = kvm_emulate_msr_read(vcpu, msr, &data);
2130
2131 if (!r) {
2132 trace_kvm_msr_read(msr, data);
2133
2134 if (reg < 0) {
2135 kvm_rax_write(vcpu, data & -1u);
2136 kvm_rdx_write(vcpu, (data >> 32) & -1u);
2137 } else {
2138 kvm_register_write(vcpu, reg, data);
2139 }
2140 } else {
2141 /* MSR read failed? See if we should ask user space */
2142 if (kvm_msr_user_space(vcpu, msr, KVM_EXIT_X86_RDMSR, 0,
2143 complete_rdmsr, r))
2144 return 0;
2145 trace_kvm_msr_read_ex(msr);
2146 }
2147
2148 return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2149 }
2150
kvm_emulate_rdmsr(struct kvm_vcpu * vcpu)2151 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2152 {
2153 return __kvm_emulate_rdmsr(vcpu, kvm_rcx_read(vcpu), -1,
2154 complete_fast_rdmsr);
2155 }
2156 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdmsr);
2157
kvm_emulate_rdmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2158 int kvm_emulate_rdmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2159 {
2160 vcpu->arch.cui_rdmsr_imm_reg = reg;
2161
2162 return __kvm_emulate_rdmsr(vcpu, msr, reg, complete_fast_rdmsr_imm);
2163 }
2164 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdmsr_imm);
2165
__kvm_emulate_wrmsr(struct kvm_vcpu * vcpu,u32 msr,u64 data)2166 static int __kvm_emulate_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2167 {
2168 int r;
2169
2170 r = kvm_emulate_msr_write(vcpu, msr, data);
2171 if (!r) {
2172 trace_kvm_msr_write(msr, data);
2173 } else {
2174 /* MSR write failed? See if we should ask user space */
2175 if (kvm_msr_user_space(vcpu, msr, KVM_EXIT_X86_WRMSR, data,
2176 complete_fast_msr_access, r))
2177 return 0;
2178 /* Signal all other negative errors to userspace */
2179 if (r < 0)
2180 return r;
2181 trace_kvm_msr_write_ex(msr, data);
2182 }
2183
2184 return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2185 }
2186
kvm_emulate_wrmsr(struct kvm_vcpu * vcpu)2187 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2188 {
2189 return __kvm_emulate_wrmsr(vcpu, kvm_rcx_read(vcpu),
2190 kvm_read_edx_eax(vcpu));
2191 }
2192 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wrmsr);
2193
kvm_emulate_wrmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2194 int kvm_emulate_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2195 {
2196 return __kvm_emulate_wrmsr(vcpu, msr, kvm_register_read(vcpu, reg));
2197 }
2198 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wrmsr_imm);
2199
kvm_emulate_as_nop(struct kvm_vcpu * vcpu)2200 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2201 {
2202 return kvm_skip_emulated_instruction(vcpu);
2203 }
2204
kvm_emulate_invd(struct kvm_vcpu * vcpu)2205 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2206 {
2207 /* Treat an INVD instruction as a NOP and just skip it. */
2208 return kvm_emulate_as_nop(vcpu);
2209 }
2210 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_invd);
2211
handle_fastpath_invd(struct kvm_vcpu * vcpu)2212 fastpath_t handle_fastpath_invd(struct kvm_vcpu *vcpu)
2213 {
2214 if (!kvm_emulate_invd(vcpu))
2215 return EXIT_FASTPATH_EXIT_USERSPACE;
2216
2217 return EXIT_FASTPATH_REENTER_GUEST;
2218 }
2219 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_invd);
2220
kvm_handle_invalid_op(struct kvm_vcpu * vcpu)2221 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2222 {
2223 kvm_queue_exception(vcpu, UD_VECTOR);
2224 return 1;
2225 }
2226 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invalid_op);
2227
2228
kvm_emulate_monitor_mwait(struct kvm_vcpu * vcpu,const char * insn)2229 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2230 {
2231 bool enabled;
2232
2233 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS))
2234 goto emulate_as_nop;
2235
2236 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
2237 enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_MWAIT);
2238 else
2239 enabled = vcpu->arch.ia32_misc_enable_msr & MSR_IA32_MISC_ENABLE_MWAIT;
2240
2241 if (!enabled)
2242 return kvm_handle_invalid_op(vcpu);
2243
2244 emulate_as_nop:
2245 pr_warn_once("%s instruction emulated as NOP!\n", insn);
2246 return kvm_emulate_as_nop(vcpu);
2247 }
kvm_emulate_mwait(struct kvm_vcpu * vcpu)2248 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2249 {
2250 return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2251 }
2252 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_mwait);
2253
kvm_emulate_monitor(struct kvm_vcpu * vcpu)2254 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2255 {
2256 return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2257 }
2258 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_monitor);
2259
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu)2260 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2261 {
2262 xfer_to_guest_mode_prepare();
2263
2264 return READ_ONCE(vcpu->mode) == EXITING_GUEST_MODE ||
2265 kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending();
2266 }
2267
__handle_fastpath_wrmsr(struct kvm_vcpu * vcpu,u32 msr,u64 data)2268 static fastpath_t __handle_fastpath_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2269 {
2270 switch (msr) {
2271 case APIC_BASE_MSR + (APIC_ICR >> 4):
2272 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic) ||
2273 kvm_x2apic_icr_write_fast(vcpu->arch.apic, data))
2274 return EXIT_FASTPATH_NONE;
2275 break;
2276 case MSR_IA32_TSC_DEADLINE:
2277 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2278 break;
2279 default:
2280 return EXIT_FASTPATH_NONE;
2281 }
2282
2283 trace_kvm_msr_write(msr, data);
2284
2285 if (!kvm_skip_emulated_instruction(vcpu))
2286 return EXIT_FASTPATH_EXIT_USERSPACE;
2287
2288 return EXIT_FASTPATH_REENTER_GUEST;
2289 }
2290
handle_fastpath_wrmsr(struct kvm_vcpu * vcpu)2291 fastpath_t handle_fastpath_wrmsr(struct kvm_vcpu *vcpu)
2292 {
2293 return __handle_fastpath_wrmsr(vcpu, kvm_rcx_read(vcpu),
2294 kvm_read_edx_eax(vcpu));
2295 }
2296 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr);
2297
handle_fastpath_wrmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2298 fastpath_t handle_fastpath_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2299 {
2300 return __handle_fastpath_wrmsr(vcpu, msr, kvm_register_read(vcpu, reg));
2301 }
2302 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr_imm);
2303
2304 /*
2305 * Adapt set_msr() to msr_io()'s calling convention
2306 */
do_get_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2307 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2308 {
2309 return kvm_get_msr_ignored_check(vcpu, index, data, true);
2310 }
2311
do_set_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2312 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2313 {
2314 u64 val;
2315
2316 /*
2317 * Disallow writes to immutable feature MSRs after KVM_RUN. KVM does
2318 * not support modifying the guest vCPU model on the fly, e.g. changing
2319 * the nVMX capabilities while L2 is running is nonsensical. Allow
2320 * writes of the same value, e.g. to allow userspace to blindly stuff
2321 * all MSRs when emulating RESET.
2322 */
2323 if (kvm_vcpu_has_run(vcpu) && kvm_is_immutable_feature_msr(index) &&
2324 (do_get_msr(vcpu, index, &val) || *data != val))
2325 return -EINVAL;
2326
2327 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2328 }
2329
2330 #ifdef CONFIG_X86_64
2331 struct pvclock_clock {
2332 int vclock_mode;
2333 u64 cycle_last;
2334 u64 mask;
2335 u32 mult;
2336 u32 shift;
2337 u64 base_cycles;
2338 u64 offset;
2339 };
2340
2341 struct pvclock_gtod_data {
2342 seqcount_t seq;
2343
2344 struct pvclock_clock clock; /* extract of a clocksource struct */
2345 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2346
2347 ktime_t offs_boot;
2348 u64 wall_time_sec;
2349 };
2350
2351 static struct pvclock_gtod_data pvclock_gtod_data;
2352
update_pvclock_gtod(struct timekeeper * tk)2353 static void update_pvclock_gtod(struct timekeeper *tk)
2354 {
2355 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2356
2357 write_seqcount_begin(&vdata->seq);
2358
2359 /* copy pvclock gtod data */
2360 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
2361 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
2362 vdata->clock.mask = tk->tkr_mono.mask;
2363 vdata->clock.mult = tk->tkr_mono.mult;
2364 vdata->clock.shift = tk->tkr_mono.shift;
2365 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
2366 vdata->clock.offset = tk->tkr_mono.base;
2367
2368 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
2369 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
2370 vdata->raw_clock.mask = tk->tkr_raw.mask;
2371 vdata->raw_clock.mult = tk->tkr_raw.mult;
2372 vdata->raw_clock.shift = tk->tkr_raw.shift;
2373 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
2374 vdata->raw_clock.offset = tk->tkr_raw.base;
2375
2376 vdata->wall_time_sec = tk->xtime_sec;
2377
2378 vdata->offs_boot = tk->offs_boot;
2379
2380 write_seqcount_end(&vdata->seq);
2381 }
2382
get_kvmclock_base_ns(void)2383 static s64 get_kvmclock_base_ns(void)
2384 {
2385 /* Count up from boot time, but with the frequency of the raw clock. */
2386 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2387 }
2388 #else
get_kvmclock_base_ns(void)2389 static s64 get_kvmclock_base_ns(void)
2390 {
2391 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
2392 return ktime_get_boottime_ns();
2393 }
2394 #endif
2395
kvm_write_wall_clock(struct kvm * kvm,gpa_t wall_clock,int sec_hi_ofs)2396 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2397 {
2398 int version;
2399 int r;
2400 struct pvclock_wall_clock wc;
2401 u32 wc_sec_hi;
2402 u64 wall_nsec;
2403
2404 if (!wall_clock)
2405 return;
2406
2407 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2408 if (r)
2409 return;
2410
2411 if (version & 1)
2412 ++version; /* first time write, random junk */
2413
2414 ++version;
2415
2416 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2417 return;
2418
2419 wall_nsec = kvm_get_wall_clock_epoch(kvm);
2420
2421 wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
2422 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2423 wc.version = version;
2424
2425 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2426
2427 if (sec_hi_ofs) {
2428 wc_sec_hi = wall_nsec >> 32;
2429 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2430 &wc_sec_hi, sizeof(wc_sec_hi));
2431 }
2432
2433 version++;
2434 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2435 }
2436
kvm_write_system_time(struct kvm_vcpu * vcpu,gpa_t system_time,bool old_msr,bool host_initiated)2437 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2438 bool old_msr, bool host_initiated)
2439 {
2440 struct kvm_arch *ka = &vcpu->kvm->arch;
2441
2442 if (vcpu->vcpu_id == 0 && !host_initiated) {
2443 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2444 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2445
2446 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2447 }
2448
2449 vcpu->arch.time = system_time;
2450 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2451
2452 /* we verify if the enable bit is set... */
2453 if (system_time & 1)
2454 kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
2455 sizeof(struct pvclock_vcpu_time_info));
2456 else
2457 kvm_gpc_deactivate(&vcpu->arch.pv_time);
2458
2459 return;
2460 }
2461
div_frac(uint32_t dividend,uint32_t divisor)2462 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2463 {
2464 do_shl32_div32(dividend, divisor);
2465 return dividend;
2466 }
2467
kvm_get_time_scale(uint64_t scaled_hz,uint64_t base_hz,s8 * pshift,u32 * pmultiplier)2468 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2469 s8 *pshift, u32 *pmultiplier)
2470 {
2471 uint64_t scaled64;
2472 int32_t shift = 0;
2473 uint64_t tps64;
2474 uint32_t tps32;
2475
2476 tps64 = base_hz;
2477 scaled64 = scaled_hz;
2478 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2479 tps64 >>= 1;
2480 shift--;
2481 }
2482
2483 tps32 = (uint32_t)tps64;
2484 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2485 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2486 scaled64 >>= 1;
2487 else
2488 tps32 <<= 1;
2489 shift++;
2490 }
2491
2492 *pshift = shift;
2493 *pmultiplier = div_frac(scaled64, tps32);
2494 }
2495
2496 #ifdef CONFIG_X86_64
2497 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2498 #endif
2499
2500 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2501 static unsigned long max_tsc_khz;
2502
adjust_tsc_khz(u32 khz,s32 ppm)2503 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2504 {
2505 u64 v = (u64)khz * (1000000 + ppm);
2506 do_div(v, 1000000);
2507 return v;
2508 }
2509
2510 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2511
set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz,bool scale)2512 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2513 {
2514 u64 ratio;
2515
2516 /* Guest TSC same frequency as host TSC? */
2517 if (!scale) {
2518 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2519 return 0;
2520 }
2521
2522 /* TSC scaling supported? */
2523 if (!kvm_caps.has_tsc_control) {
2524 if (user_tsc_khz > tsc_khz) {
2525 vcpu->arch.tsc_catchup = 1;
2526 vcpu->arch.tsc_always_catchup = 1;
2527 return 0;
2528 } else {
2529 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2530 return -1;
2531 }
2532 }
2533
2534 /* TSC scaling required - calculate ratio */
2535 ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2536 user_tsc_khz, tsc_khz);
2537
2538 if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2539 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2540 user_tsc_khz);
2541 return -1;
2542 }
2543
2544 kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2545 return 0;
2546 }
2547
kvm_set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz)2548 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2549 {
2550 u32 thresh_lo, thresh_hi;
2551 int use_scaling = 0;
2552
2553 /* tsc_khz can be zero if TSC calibration fails */
2554 if (user_tsc_khz == 0) {
2555 /* set tsc_scaling_ratio to a safe value */
2556 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2557 return -1;
2558 }
2559
2560 /* Compute a scale to convert nanoseconds in TSC cycles */
2561 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2562 &vcpu->arch.virtual_tsc_shift,
2563 &vcpu->arch.virtual_tsc_mult);
2564 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2565
2566 /*
2567 * Compute the variation in TSC rate which is acceptable
2568 * within the range of tolerance and decide if the
2569 * rate being applied is within that bounds of the hardware
2570 * rate. If so, no scaling or compensation need be done.
2571 */
2572 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2573 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2574 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2575 pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2576 user_tsc_khz, thresh_lo, thresh_hi);
2577 use_scaling = 1;
2578 }
2579 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2580 }
2581
compute_guest_tsc(struct kvm_vcpu * vcpu,s64 kernel_ns)2582 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2583 {
2584 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2585 vcpu->arch.virtual_tsc_mult,
2586 vcpu->arch.virtual_tsc_shift);
2587 tsc += vcpu->arch.this_tsc_write;
2588 return tsc;
2589 }
2590
2591 #ifdef CONFIG_X86_64
gtod_is_based_on_tsc(int mode)2592 static inline bool gtod_is_based_on_tsc(int mode)
2593 {
2594 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2595 }
2596 #endif
2597
kvm_track_tsc_matching(struct kvm_vcpu * vcpu,bool new_generation)2598 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
2599 {
2600 #ifdef CONFIG_X86_64
2601 struct kvm_arch *ka = &vcpu->kvm->arch;
2602 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2603
2604 /*
2605 * To use the masterclock, the host clocksource must be based on TSC
2606 * and all vCPUs must have matching TSCs. Note, the count for matching
2607 * vCPUs doesn't include the reference vCPU, hence "+1".
2608 */
2609 bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2610 atomic_read(&vcpu->kvm->online_vcpus)) &&
2611 gtod_is_based_on_tsc(gtod->clock.vclock_mode);
2612
2613 /*
2614 * Request a masterclock update if the masterclock needs to be toggled
2615 * on/off, or when starting a new generation and the masterclock is
2616 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2617 * taken _after_ the new generation is created).
2618 */
2619 if ((ka->use_master_clock && new_generation) ||
2620 (ka->use_master_clock != use_master_clock))
2621 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2622
2623 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2624 atomic_read(&vcpu->kvm->online_vcpus),
2625 ka->use_master_clock, gtod->clock.vclock_mode);
2626 #endif
2627 }
2628
2629 /*
2630 * Multiply tsc by a fixed point number represented by ratio.
2631 *
2632 * The most significant 64-N bits (mult) of ratio represent the
2633 * integral part of the fixed point number; the remaining N bits
2634 * (frac) represent the fractional part, ie. ratio represents a fixed
2635 * point number (mult + frac * 2^(-N)).
2636 *
2637 * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2638 */
__scale_tsc(u64 ratio,u64 tsc)2639 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2640 {
2641 return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2642 }
2643
kvm_scale_tsc(u64 tsc,u64 ratio)2644 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2645 {
2646 u64 _tsc = tsc;
2647
2648 if (ratio != kvm_caps.default_tsc_scaling_ratio)
2649 _tsc = __scale_tsc(ratio, tsc);
2650
2651 return _tsc;
2652 }
2653
kvm_compute_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 target_tsc)2654 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2655 {
2656 u64 tsc;
2657
2658 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2659
2660 return target_tsc - tsc;
2661 }
2662
kvm_read_l1_tsc(struct kvm_vcpu * vcpu,u64 host_tsc)2663 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2664 {
2665 return vcpu->arch.l1_tsc_offset +
2666 kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2667 }
2668 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_l1_tsc);
2669
kvm_calc_nested_tsc_offset(u64 l1_offset,u64 l2_offset,u64 l2_multiplier)2670 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2671 {
2672 u64 nested_offset;
2673
2674 if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2675 nested_offset = l1_offset;
2676 else
2677 nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2678 kvm_caps.tsc_scaling_ratio_frac_bits);
2679
2680 nested_offset += l2_offset;
2681 return nested_offset;
2682 }
2683 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_offset);
2684
kvm_calc_nested_tsc_multiplier(u64 l1_multiplier,u64 l2_multiplier)2685 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2686 {
2687 if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2688 return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2689 kvm_caps.tsc_scaling_ratio_frac_bits);
2690
2691 return l1_multiplier;
2692 }
2693 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_multiplier);
2694
kvm_vcpu_write_tsc_offset(struct kvm_vcpu * vcpu,u64 l1_offset)2695 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2696 {
2697 if (vcpu->arch.guest_tsc_protected)
2698 return;
2699
2700 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2701 vcpu->arch.l1_tsc_offset,
2702 l1_offset);
2703
2704 vcpu->arch.l1_tsc_offset = l1_offset;
2705
2706 /*
2707 * If we are here because L1 chose not to trap WRMSR to TSC then
2708 * according to the spec this should set L1's TSC (as opposed to
2709 * setting L1's offset for L2).
2710 */
2711 if (is_guest_mode(vcpu))
2712 vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2713 l1_offset,
2714 kvm_x86_call(get_l2_tsc_offset)(vcpu),
2715 kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2716 else
2717 vcpu->arch.tsc_offset = l1_offset;
2718
2719 kvm_x86_call(write_tsc_offset)(vcpu);
2720 }
2721
kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu * vcpu,u64 l1_multiplier)2722 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2723 {
2724 vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2725
2726 /* Userspace is changing the multiplier while L2 is active */
2727 if (is_guest_mode(vcpu))
2728 vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2729 l1_multiplier,
2730 kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2731 else
2732 vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2733
2734 if (kvm_caps.has_tsc_control)
2735 kvm_x86_call(write_tsc_multiplier)(vcpu);
2736 }
2737
kvm_check_tsc_unstable(void)2738 static inline bool kvm_check_tsc_unstable(void)
2739 {
2740 #ifdef CONFIG_X86_64
2741 /*
2742 * TSC is marked unstable when we're running on Hyper-V,
2743 * 'TSC page' clocksource is good.
2744 */
2745 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2746 return false;
2747 #endif
2748 return check_tsc_unstable();
2749 }
2750
2751 /*
2752 * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2753 * offset for the vcpu and tracks the TSC matching generation that the vcpu
2754 * participates in.
2755 */
__kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 offset,u64 tsc,u64 ns,bool matched,bool user_set_tsc)2756 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2757 u64 ns, bool matched, bool user_set_tsc)
2758 {
2759 struct kvm *kvm = vcpu->kvm;
2760
2761 lockdep_assert_held(&kvm->arch.tsc_write_lock);
2762
2763 if (vcpu->arch.guest_tsc_protected)
2764 return;
2765
2766 if (user_set_tsc)
2767 vcpu->kvm->arch.user_set_tsc = true;
2768
2769 /*
2770 * We also track th most recent recorded KHZ, write and time to
2771 * allow the matching interval to be extended at each write.
2772 */
2773 kvm->arch.last_tsc_nsec = ns;
2774 kvm->arch.last_tsc_write = tsc;
2775 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2776 kvm->arch.last_tsc_offset = offset;
2777
2778 vcpu->arch.last_guest_tsc = tsc;
2779
2780 kvm_vcpu_write_tsc_offset(vcpu, offset);
2781
2782 if (!matched) {
2783 /*
2784 * We split periods of matched TSC writes into generations.
2785 * For each generation, we track the original measured
2786 * nanosecond time, offset, and write, so if TSCs are in
2787 * sync, we can match exact offset, and if not, we can match
2788 * exact software computation in compute_guest_tsc()
2789 *
2790 * These values are tracked in kvm->arch.cur_xxx variables.
2791 */
2792 kvm->arch.cur_tsc_generation++;
2793 kvm->arch.cur_tsc_nsec = ns;
2794 kvm->arch.cur_tsc_write = tsc;
2795 kvm->arch.cur_tsc_offset = offset;
2796 kvm->arch.nr_vcpus_matched_tsc = 0;
2797 } else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2798 kvm->arch.nr_vcpus_matched_tsc++;
2799 }
2800
2801 /* Keep track of which generation this VCPU has synchronized to */
2802 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2803 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2804 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2805
2806 kvm_track_tsc_matching(vcpu, !matched);
2807 }
2808
kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 * user_value)2809 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
2810 {
2811 u64 data = user_value ? *user_value : 0;
2812 struct kvm *kvm = vcpu->kvm;
2813 u64 offset, ns, elapsed;
2814 unsigned long flags;
2815 bool matched = false;
2816 bool synchronizing = false;
2817
2818 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2819 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2820 ns = get_kvmclock_base_ns();
2821 elapsed = ns - kvm->arch.last_tsc_nsec;
2822
2823 if (vcpu->arch.virtual_tsc_khz) {
2824 if (data == 0) {
2825 /*
2826 * Force synchronization when creating a vCPU, or when
2827 * userspace explicitly writes a zero value.
2828 */
2829 synchronizing = true;
2830 } else if (kvm->arch.user_set_tsc) {
2831 u64 tsc_exp = kvm->arch.last_tsc_write +
2832 nsec_to_cycles(vcpu, elapsed);
2833 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2834 /*
2835 * Here lies UAPI baggage: when a user-initiated TSC write has
2836 * a small delta (1 second) of virtual cycle time against the
2837 * previously set vCPU, we assume that they were intended to be
2838 * in sync and the delta was only due to the racy nature of the
2839 * legacy API.
2840 *
2841 * This trick falls down when restoring a guest which genuinely
2842 * has been running for less time than the 1 second of imprecision
2843 * which we allow for in the legacy API. In this case, the first
2844 * value written by userspace (on any vCPU) should not be subject
2845 * to this 'correction' to make it sync up with values that only
2846 * come from the kernel's default vCPU creation. Make the 1-second
2847 * slop hack only trigger if the user_set_tsc flag is already set.
2848 */
2849 synchronizing = data < tsc_exp + tsc_hz &&
2850 data + tsc_hz > tsc_exp;
2851 }
2852 }
2853
2854
2855 /*
2856 * For a reliable TSC, we can match TSC offsets, and for an unstable
2857 * TSC, we add elapsed time in this computation. We could let the
2858 * compensation code attempt to catch up if we fall behind, but
2859 * it's better to try to match offsets from the beginning.
2860 */
2861 if (synchronizing &&
2862 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2863 if (!kvm_check_tsc_unstable()) {
2864 offset = kvm->arch.cur_tsc_offset;
2865 } else {
2866 u64 delta = nsec_to_cycles(vcpu, elapsed);
2867 data += delta;
2868 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2869 }
2870 matched = true;
2871 }
2872
2873 __kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value);
2874 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2875 }
2876
adjust_tsc_offset_guest(struct kvm_vcpu * vcpu,s64 adjustment)2877 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2878 s64 adjustment)
2879 {
2880 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2881 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2882 }
2883
adjust_tsc_offset_host(struct kvm_vcpu * vcpu,s64 adjustment)2884 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2885 {
2886 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2887 WARN_ON(adjustment < 0);
2888 adjustment = kvm_scale_tsc((u64) adjustment,
2889 vcpu->arch.l1_tsc_scaling_ratio);
2890 adjust_tsc_offset_guest(vcpu, adjustment);
2891 }
2892
2893 #ifdef CONFIG_X86_64
2894
read_tsc(void)2895 static u64 read_tsc(void)
2896 {
2897 u64 ret = (u64)rdtsc_ordered();
2898 u64 last = pvclock_gtod_data.clock.cycle_last;
2899
2900 if (likely(ret >= last))
2901 return ret;
2902
2903 /*
2904 * GCC likes to generate cmov here, but this branch is extremely
2905 * predictable (it's just a function of time and the likely is
2906 * very likely) and there's a data dependence, so force GCC
2907 * to generate a branch instead. I don't barrier() because
2908 * we don't actually need a barrier, and if this function
2909 * ever gets inlined it will generate worse code.
2910 */
2911 asm volatile ("");
2912 return last;
2913 }
2914
vgettsc(struct pvclock_clock * clock,u64 * tsc_timestamp,int * mode)2915 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2916 int *mode)
2917 {
2918 u64 tsc_pg_val;
2919 long v;
2920
2921 switch (clock->vclock_mode) {
2922 case VDSO_CLOCKMODE_HVCLOCK:
2923 if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2924 tsc_timestamp, &tsc_pg_val)) {
2925 /* TSC page valid */
2926 *mode = VDSO_CLOCKMODE_HVCLOCK;
2927 v = (tsc_pg_val - clock->cycle_last) &
2928 clock->mask;
2929 } else {
2930 /* TSC page invalid */
2931 *mode = VDSO_CLOCKMODE_NONE;
2932 }
2933 break;
2934 case VDSO_CLOCKMODE_TSC:
2935 *mode = VDSO_CLOCKMODE_TSC;
2936 *tsc_timestamp = read_tsc();
2937 v = (*tsc_timestamp - clock->cycle_last) &
2938 clock->mask;
2939 break;
2940 default:
2941 *mode = VDSO_CLOCKMODE_NONE;
2942 }
2943
2944 if (*mode == VDSO_CLOCKMODE_NONE)
2945 *tsc_timestamp = v = 0;
2946
2947 return v * clock->mult;
2948 }
2949
2950 /*
2951 * As with get_kvmclock_base_ns(), this counts from boot time, at the
2952 * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2953 */
do_kvmclock_base(s64 * t,u64 * tsc_timestamp)2954 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
2955 {
2956 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2957 unsigned long seq;
2958 int mode;
2959 u64 ns;
2960
2961 do {
2962 seq = read_seqcount_begin(>od->seq);
2963 ns = gtod->raw_clock.base_cycles;
2964 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2965 ns >>= gtod->raw_clock.shift;
2966 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2967 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2968 *t = ns;
2969
2970 return mode;
2971 }
2972
2973 /*
2974 * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2975 * no boot time offset.
2976 */
do_monotonic(s64 * t,u64 * tsc_timestamp)2977 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2978 {
2979 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2980 unsigned long seq;
2981 int mode;
2982 u64 ns;
2983
2984 do {
2985 seq = read_seqcount_begin(>od->seq);
2986 ns = gtod->clock.base_cycles;
2987 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2988 ns >>= gtod->clock.shift;
2989 ns += ktime_to_ns(gtod->clock.offset);
2990 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2991 *t = ns;
2992
2993 return mode;
2994 }
2995
do_realtime(struct timespec64 * ts,u64 * tsc_timestamp)2996 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2997 {
2998 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2999 unsigned long seq;
3000 int mode;
3001 u64 ns;
3002
3003 do {
3004 seq = read_seqcount_begin(>od->seq);
3005 ts->tv_sec = gtod->wall_time_sec;
3006 ns = gtod->clock.base_cycles;
3007 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
3008 ns >>= gtod->clock.shift;
3009 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
3010
3011 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
3012 ts->tv_nsec = ns;
3013
3014 return mode;
3015 }
3016
3017 /*
3018 * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
3019 * reports the TSC value from which it do so. Returns true if host is
3020 * using TSC based clocksource.
3021 */
kvm_get_time_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)3022 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
3023 {
3024 /* checked again under seqlock below */
3025 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3026 return false;
3027
3028 return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
3029 tsc_timestamp));
3030 }
3031
3032 /*
3033 * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
3034 * so. Returns true if host is using TSC based clocksource.
3035 */
kvm_get_monotonic_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)3036 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
3037 {
3038 /* checked again under seqlock below */
3039 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3040 return false;
3041
3042 return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
3043 tsc_timestamp));
3044 }
3045
3046 /*
3047 * Calculates CLOCK_REALTIME and reports the TSC value from which it did
3048 * so. Returns true if host is using TSC based clocksource.
3049 *
3050 * DO NOT USE this for anything related to migration. You want CLOCK_TAI
3051 * for that.
3052 */
kvm_get_walltime_and_clockread(struct timespec64 * ts,u64 * tsc_timestamp)3053 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
3054 u64 *tsc_timestamp)
3055 {
3056 /* checked again under seqlock below */
3057 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3058 return false;
3059
3060 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
3061 }
3062 #endif
3063
3064 /*
3065 *
3066 * Assuming a stable TSC across physical CPUS, and a stable TSC
3067 * across virtual CPUs, the following condition is possible.
3068 * Each numbered line represents an event visible to both
3069 * CPUs at the next numbered event.
3070 *
3071 * "timespecX" represents host monotonic time. "tscX" represents
3072 * RDTSC value.
3073 *
3074 * VCPU0 on CPU0 | VCPU1 on CPU1
3075 *
3076 * 1. read timespec0,tsc0
3077 * 2. | timespec1 = timespec0 + N
3078 * | tsc1 = tsc0 + M
3079 * 3. transition to guest | transition to guest
3080 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
3081 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
3082 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
3083 *
3084 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
3085 *
3086 * - ret0 < ret1
3087 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
3088 * ...
3089 * - 0 < N - M => M < N
3090 *
3091 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
3092 * always the case (the difference between two distinct xtime instances
3093 * might be smaller then the difference between corresponding TSC reads,
3094 * when updating guest vcpus pvclock areas).
3095 *
3096 * To avoid that problem, do not allow visibility of distinct
3097 * system_timestamp/tsc_timestamp values simultaneously: use a master
3098 * copy of host monotonic time values. Update that master copy
3099 * in lockstep.
3100 *
3101 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
3102 *
3103 */
3104
pvclock_update_vm_gtod_copy(struct kvm * kvm)3105 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
3106 {
3107 #ifdef CONFIG_X86_64
3108 struct kvm_arch *ka = &kvm->arch;
3109 int vclock_mode;
3110 bool host_tsc_clocksource, vcpus_matched;
3111
3112 lockdep_assert_held(&kvm->arch.tsc_write_lock);
3113 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
3114 atomic_read(&kvm->online_vcpus));
3115
3116 /*
3117 * If the host uses TSC clock, then passthrough TSC as stable
3118 * to the guest.
3119 */
3120 host_tsc_clocksource = kvm_get_time_and_clockread(
3121 &ka->master_kernel_ns,
3122 &ka->master_cycle_now);
3123
3124 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
3125 && !ka->backwards_tsc_observed
3126 && !ka->boot_vcpu_runs_old_kvmclock;
3127
3128 if (ka->use_master_clock)
3129 atomic_set(&kvm_guest_has_master_clock, 1);
3130
3131 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
3132 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3133 vcpus_matched);
3134 #endif
3135 }
3136
kvm_make_mclock_inprogress_request(struct kvm * kvm)3137 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
3138 {
3139 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3140 }
3141
__kvm_start_pvclock_update(struct kvm * kvm)3142 static void __kvm_start_pvclock_update(struct kvm *kvm)
3143 {
3144 raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3145 write_seqcount_begin(&kvm->arch.pvclock_sc);
3146 }
3147
kvm_start_pvclock_update(struct kvm * kvm)3148 static void kvm_start_pvclock_update(struct kvm *kvm)
3149 {
3150 kvm_make_mclock_inprogress_request(kvm);
3151
3152 /* no guest entries from this point */
3153 __kvm_start_pvclock_update(kvm);
3154 }
3155
kvm_end_pvclock_update(struct kvm * kvm)3156 static void kvm_end_pvclock_update(struct kvm *kvm)
3157 {
3158 struct kvm_arch *ka = &kvm->arch;
3159 struct kvm_vcpu *vcpu;
3160 unsigned long i;
3161
3162 write_seqcount_end(&ka->pvclock_sc);
3163 raw_spin_unlock_irq(&ka->tsc_write_lock);
3164 kvm_for_each_vcpu(i, vcpu, kvm)
3165 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3166
3167 /* guest entries allowed */
3168 kvm_for_each_vcpu(i, vcpu, kvm)
3169 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
3170 }
3171
kvm_update_masterclock(struct kvm * kvm)3172 static void kvm_update_masterclock(struct kvm *kvm)
3173 {
3174 kvm_hv_request_tsc_page_update(kvm);
3175 kvm_start_pvclock_update(kvm);
3176 pvclock_update_vm_gtod_copy(kvm);
3177 kvm_end_pvclock_update(kvm);
3178 }
3179
3180 /*
3181 * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3182 * per-CPU value (which may be zero if a CPU is going offline). Note, tsc_khz
3183 * can change during boot even if the TSC is constant, as it's possible for KVM
3184 * to be loaded before TSC calibration completes. Ideally, KVM would get a
3185 * notification when calibration completes, but practically speaking calibration
3186 * will complete before userspace is alive enough to create VMs.
3187 */
get_cpu_tsc_khz(void)3188 static unsigned long get_cpu_tsc_khz(void)
3189 {
3190 if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3191 return tsc_khz;
3192 else
3193 return __this_cpu_read(cpu_tsc_khz);
3194 }
3195
3196 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc. */
__get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3197 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3198 {
3199 struct kvm_arch *ka = &kvm->arch;
3200 struct pvclock_vcpu_time_info hv_clock;
3201
3202 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
3203 get_cpu();
3204
3205 data->flags = 0;
3206 if (ka->use_master_clock &&
3207 (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
3208 #ifdef CONFIG_X86_64
3209 struct timespec64 ts;
3210
3211 if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3212 data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3213 data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3214 } else
3215 #endif
3216 data->host_tsc = rdtsc();
3217
3218 data->flags |= KVM_CLOCK_TSC_STABLE;
3219 hv_clock.tsc_timestamp = ka->master_cycle_now;
3220 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3221 kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
3222 &hv_clock.tsc_shift,
3223 &hv_clock.tsc_to_system_mul);
3224 data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3225 } else {
3226 data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3227 }
3228
3229 put_cpu();
3230 }
3231
get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3232 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3233 {
3234 struct kvm_arch *ka = &kvm->arch;
3235 unsigned seq;
3236
3237 do {
3238 seq = read_seqcount_begin(&ka->pvclock_sc);
3239 __get_kvmclock(kvm, data);
3240 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3241 }
3242
get_kvmclock_ns(struct kvm * kvm)3243 u64 get_kvmclock_ns(struct kvm *kvm)
3244 {
3245 struct kvm_clock_data data;
3246
3247 get_kvmclock(kvm, &data);
3248 return data.clock;
3249 }
3250
kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info * ref_hv_clock,struct kvm_vcpu * vcpu,struct gfn_to_pfn_cache * gpc,unsigned int offset)3251 static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
3252 struct kvm_vcpu *vcpu,
3253 struct gfn_to_pfn_cache *gpc,
3254 unsigned int offset)
3255 {
3256 struct pvclock_vcpu_time_info *guest_hv_clock;
3257 struct pvclock_vcpu_time_info hv_clock;
3258 unsigned long flags;
3259
3260 memcpy(&hv_clock, ref_hv_clock, sizeof(hv_clock));
3261
3262 read_lock_irqsave(&gpc->lock, flags);
3263 while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
3264 read_unlock_irqrestore(&gpc->lock, flags);
3265
3266 if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
3267 return;
3268
3269 read_lock_irqsave(&gpc->lock, flags);
3270 }
3271
3272 guest_hv_clock = (void *)(gpc->khva + offset);
3273
3274 /*
3275 * This VCPU is paused, but it's legal for a guest to read another
3276 * VCPU's kvmclock, so we really have to follow the specification where
3277 * it says that version is odd if data is being modified, and even after
3278 * it is consistent.
3279 */
3280
3281 guest_hv_clock->version = hv_clock.version = (guest_hv_clock->version + 1) | 1;
3282 smp_wmb();
3283
3284 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3285 hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3286
3287 memcpy(guest_hv_clock, &hv_clock, sizeof(*guest_hv_clock));
3288
3289 smp_wmb();
3290
3291 guest_hv_clock->version = ++hv_clock.version;
3292
3293 kvm_gpc_mark_dirty_in_slot(gpc);
3294 read_unlock_irqrestore(&gpc->lock, flags);
3295
3296 trace_kvm_pvclock_update(vcpu->vcpu_id, &hv_clock);
3297 }
3298
kvm_guest_time_update(struct kvm_vcpu * v)3299 int kvm_guest_time_update(struct kvm_vcpu *v)
3300 {
3301 struct pvclock_vcpu_time_info hv_clock = {};
3302 unsigned long flags, tgt_tsc_khz;
3303 unsigned seq;
3304 struct kvm_vcpu_arch *vcpu = &v->arch;
3305 struct kvm_arch *ka = &v->kvm->arch;
3306 s64 kernel_ns;
3307 u64 tsc_timestamp, host_tsc;
3308 bool use_master_clock;
3309
3310 kernel_ns = 0;
3311 host_tsc = 0;
3312
3313 /*
3314 * If the host uses TSC clock, then passthrough TSC as stable
3315 * to the guest.
3316 */
3317 do {
3318 seq = read_seqcount_begin(&ka->pvclock_sc);
3319 use_master_clock = ka->use_master_clock;
3320 if (use_master_clock) {
3321 host_tsc = ka->master_cycle_now;
3322 kernel_ns = ka->master_kernel_ns;
3323 }
3324 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3325
3326 /* Keep irq disabled to prevent changes to the clock */
3327 local_irq_save(flags);
3328 tgt_tsc_khz = get_cpu_tsc_khz();
3329 if (unlikely(tgt_tsc_khz == 0)) {
3330 local_irq_restore(flags);
3331 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3332 return 1;
3333 }
3334 if (!use_master_clock) {
3335 host_tsc = rdtsc();
3336 kernel_ns = get_kvmclock_base_ns();
3337 }
3338
3339 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3340
3341 /*
3342 * We may have to catch up the TSC to match elapsed wall clock
3343 * time for two reasons, even if kvmclock is used.
3344 * 1) CPU could have been running below the maximum TSC rate
3345 * 2) Broken TSC compensation resets the base at each VCPU
3346 * entry to avoid unknown leaps of TSC even when running
3347 * again on the same CPU. This may cause apparent elapsed
3348 * time to disappear, and the guest to stand still or run
3349 * very slowly.
3350 */
3351 if (vcpu->tsc_catchup) {
3352 u64 tsc = compute_guest_tsc(v, kernel_ns);
3353 if (tsc > tsc_timestamp) {
3354 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3355 tsc_timestamp = tsc;
3356 }
3357 }
3358
3359 local_irq_restore(flags);
3360
3361 /* With all the info we got, fill in the values */
3362
3363 if (kvm_caps.has_tsc_control) {
3364 tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3365 v->arch.l1_tsc_scaling_ratio);
3366 tgt_tsc_khz = tgt_tsc_khz ? : 1;
3367 }
3368
3369 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3370 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3371 &vcpu->pvclock_tsc_shift,
3372 &vcpu->pvclock_tsc_mul);
3373 vcpu->hw_tsc_khz = tgt_tsc_khz;
3374 }
3375
3376 hv_clock.tsc_shift = vcpu->pvclock_tsc_shift;
3377 hv_clock.tsc_to_system_mul = vcpu->pvclock_tsc_mul;
3378 hv_clock.tsc_timestamp = tsc_timestamp;
3379 hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3380 vcpu->last_guest_tsc = tsc_timestamp;
3381
3382 /* If the host uses TSC clocksource, then it is stable */
3383 hv_clock.flags = 0;
3384 if (use_master_clock)
3385 hv_clock.flags |= PVCLOCK_TSC_STABLE_BIT;
3386
3387 if (vcpu->pv_time.active) {
3388 /*
3389 * GUEST_STOPPED is only supported by kvmclock, and KVM's
3390 * historic behavior is to only process the request if kvmclock
3391 * is active/enabled.
3392 */
3393 if (vcpu->pvclock_set_guest_stopped_request) {
3394 hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3395 vcpu->pvclock_set_guest_stopped_request = false;
3396 }
3397 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->pv_time, 0);
3398
3399 hv_clock.flags &= ~PVCLOCK_GUEST_STOPPED;
3400 }
3401
3402 kvm_hv_setup_tsc_page(v->kvm, &hv_clock);
3403
3404 #ifdef CONFIG_KVM_XEN
3405 /*
3406 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3407 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3408 * This default behaviour led to bugs in some guest kernels which cause
3409 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3410 *
3411 * Note! Clear TSC_STABLE only for Xen clocks, i.e. the order matters!
3412 */
3413 if (ka->xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
3414 hv_clock.flags &= ~PVCLOCK_TSC_STABLE_BIT;
3415
3416 if (vcpu->xen.vcpu_info_cache.active)
3417 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_info_cache,
3418 offsetof(struct compat_vcpu_info, time));
3419 if (vcpu->xen.vcpu_time_info_cache.active)
3420 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_time_info_cache, 0);
3421 #endif
3422 return 0;
3423 }
3424
3425 /*
3426 * The pvclock_wall_clock ABI tells the guest the wall clock time at
3427 * which it started (i.e. its epoch, when its kvmclock was zero).
3428 *
3429 * In fact those clocks are subtly different; wall clock frequency is
3430 * adjusted by NTP and has leap seconds, while the kvmclock is a
3431 * simple function of the TSC without any such adjustment.
3432 *
3433 * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3434 * that and kvmclock, but even that would be subject to change over
3435 * time.
3436 *
3437 * Attempt to calculate the epoch at a given moment using the *same*
3438 * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3439 * wallclock and kvmclock times, and subtracting one from the other.
3440 *
3441 * Fall back to using their values at slightly different moments by
3442 * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3443 */
kvm_get_wall_clock_epoch(struct kvm * kvm)3444 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3445 {
3446 #ifdef CONFIG_X86_64
3447 struct pvclock_vcpu_time_info hv_clock;
3448 struct kvm_arch *ka = &kvm->arch;
3449 unsigned long seq, local_tsc_khz;
3450 struct timespec64 ts;
3451 uint64_t host_tsc;
3452
3453 do {
3454 seq = read_seqcount_begin(&ka->pvclock_sc);
3455
3456 local_tsc_khz = 0;
3457 if (!ka->use_master_clock)
3458 break;
3459
3460 /*
3461 * The TSC read and the call to get_cpu_tsc_khz() must happen
3462 * on the same CPU.
3463 */
3464 get_cpu();
3465
3466 local_tsc_khz = get_cpu_tsc_khz();
3467
3468 if (local_tsc_khz &&
3469 !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3470 local_tsc_khz = 0; /* Fall back to old method */
3471
3472 put_cpu();
3473
3474 /*
3475 * These values must be snapshotted within the seqcount loop.
3476 * After that, it's just mathematics which can happen on any
3477 * CPU at any time.
3478 */
3479 hv_clock.tsc_timestamp = ka->master_cycle_now;
3480 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3481
3482 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3483
3484 /*
3485 * If the conditions were right, and obtaining the wallclock+TSC was
3486 * successful, calculate the KVM clock at the corresponding time and
3487 * subtract one from the other to get the guest's epoch in nanoseconds
3488 * since 1970-01-01.
3489 */
3490 if (local_tsc_khz) {
3491 kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3492 &hv_clock.tsc_shift,
3493 &hv_clock.tsc_to_system_mul);
3494 return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3495 __pvclock_read_cycles(&hv_clock, host_tsc);
3496 }
3497 #endif
3498 return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3499 }
3500
3501 /*
3502 * kvmclock updates which are isolated to a given vcpu, such as
3503 * vcpu->cpu migration, should not allow system_timestamp from
3504 * the rest of the vcpus to remain static.
3505 *
3506 * So in those cases, request a kvmclock update for all vcpus.
3507 * The worst case for a remote vcpu to update its kvmclock
3508 * is then bounded by maximum nohz sleep latency.
3509 */
kvm_gen_kvmclock_update(struct kvm_vcpu * v)3510 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3511 {
3512 unsigned long i;
3513 struct kvm_vcpu *vcpu;
3514 struct kvm *kvm = v->kvm;
3515
3516 kvm_for_each_vcpu(i, vcpu, kvm) {
3517 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3518 kvm_vcpu_kick(vcpu);
3519 }
3520 }
3521
3522 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
is_mci_control_msr(u32 msr)3523 static bool is_mci_control_msr(u32 msr)
3524 {
3525 return (msr & 3) == 0;
3526 }
is_mci_status_msr(u32 msr)3527 static bool is_mci_status_msr(u32 msr)
3528 {
3529 return (msr & 3) == 1;
3530 }
3531
3532 /*
3533 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3534 */
can_set_mci_status(struct kvm_vcpu * vcpu)3535 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3536 {
3537 /* McStatusWrEn enabled? */
3538 if (guest_cpuid_is_amd_compatible(vcpu))
3539 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3540
3541 return false;
3542 }
3543
set_msr_mce(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3544 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3545 {
3546 u64 mcg_cap = vcpu->arch.mcg_cap;
3547 unsigned bank_num = mcg_cap & 0xff;
3548 u32 msr = msr_info->index;
3549 u64 data = msr_info->data;
3550 u32 offset, last_msr;
3551
3552 switch (msr) {
3553 case MSR_IA32_MCG_STATUS:
3554 vcpu->arch.mcg_status = data;
3555 break;
3556 case MSR_IA32_MCG_CTL:
3557 if (!(mcg_cap & MCG_CTL_P) &&
3558 (data || !msr_info->host_initiated))
3559 return 1;
3560 if (data != 0 && data != ~(u64)0)
3561 return 1;
3562 vcpu->arch.mcg_ctl = data;
3563 break;
3564 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3565 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3566 if (msr > last_msr)
3567 return 1;
3568
3569 if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3570 return 1;
3571 /* An attempt to write a 1 to a reserved bit raises #GP */
3572 if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3573 return 1;
3574 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3575 last_msr + 1 - MSR_IA32_MC0_CTL2);
3576 vcpu->arch.mci_ctl2_banks[offset] = data;
3577 break;
3578 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3579 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3580 if (msr > last_msr)
3581 return 1;
3582
3583 /*
3584 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3585 * values are architecturally undefined. But, some Linux
3586 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3587 * issue on AMD K8s, allow bit 10 to be clear when setting all
3588 * other bits in order to avoid an uncaught #GP in the guest.
3589 *
3590 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3591 * single-bit ECC data errors.
3592 */
3593 if (is_mci_control_msr(msr) &&
3594 data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3595 return 1;
3596
3597 /*
3598 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3599 * AMD-based CPUs allow non-zero values, but if and only if
3600 * HWCR[McStatusWrEn] is set.
3601 */
3602 if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3603 data != 0 && !can_set_mci_status(vcpu))
3604 return 1;
3605
3606 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3607 last_msr + 1 - MSR_IA32_MC0_CTL);
3608 vcpu->arch.mce_banks[offset] = data;
3609 break;
3610 default:
3611 return 1;
3612 }
3613 return 0;
3614 }
3615
kvm_pv_enable_async_pf(struct kvm_vcpu * vcpu,u64 data)3616 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3617 {
3618 gpa_t gpa = data & ~0x3f;
3619
3620 /* Bits 4:5 are reserved, Should be zero */
3621 if (data & 0x30)
3622 return 1;
3623
3624 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3625 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3626 return 1;
3627
3628 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3629 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3630 return 1;
3631
3632 if (!lapic_in_kernel(vcpu))
3633 return data ? 1 : 0;
3634
3635 vcpu->arch.apf.msr_en_val = data;
3636
3637 if (!kvm_pv_async_pf_enabled(vcpu)) {
3638 kvm_clear_async_pf_completion_queue(vcpu);
3639 kvm_async_pf_hash_reset(vcpu);
3640 return 0;
3641 }
3642
3643 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3644 sizeof(u64)))
3645 return 1;
3646
3647 vcpu->arch.apf.send_always = (data & KVM_ASYNC_PF_SEND_ALWAYS);
3648 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3649
3650 kvm_async_pf_wakeup_all(vcpu);
3651
3652 return 0;
3653 }
3654
kvm_pv_enable_async_pf_int(struct kvm_vcpu * vcpu,u64 data)3655 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3656 {
3657 /* Bits 8-63 are reserved */
3658 if (data >> 8)
3659 return 1;
3660
3661 if (!lapic_in_kernel(vcpu))
3662 return 1;
3663
3664 vcpu->arch.apf.msr_int_val = data;
3665
3666 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3667
3668 return 0;
3669 }
3670
kvmclock_reset(struct kvm_vcpu * vcpu)3671 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3672 {
3673 kvm_gpc_deactivate(&vcpu->arch.pv_time);
3674 vcpu->arch.time = 0;
3675 }
3676
kvm_vcpu_flush_tlb_all(struct kvm_vcpu * vcpu)3677 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3678 {
3679 ++vcpu->stat.tlb_flush;
3680 kvm_x86_call(flush_tlb_all)(vcpu);
3681
3682 /* Flushing all ASIDs flushes the current ASID... */
3683 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3684 }
3685
kvm_vcpu_flush_tlb_guest(struct kvm_vcpu * vcpu)3686 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3687 {
3688 ++vcpu->stat.tlb_flush;
3689
3690 if (!tdp_enabled) {
3691 /*
3692 * A TLB flush on behalf of the guest is equivalent to
3693 * INVPCID(all), toggling CR4.PGE, etc., which requires
3694 * a forced sync of the shadow page tables. Ensure all the
3695 * roots are synced and the guest TLB in hardware is clean.
3696 */
3697 kvm_mmu_sync_roots(vcpu);
3698 kvm_mmu_sync_prev_roots(vcpu);
3699 }
3700
3701 kvm_x86_call(flush_tlb_guest)(vcpu);
3702
3703 /*
3704 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3705 * grained flushing.
3706 */
3707 kvm_hv_vcpu_purge_flush_tlb(vcpu);
3708 }
3709
3710
kvm_vcpu_flush_tlb_current(struct kvm_vcpu * vcpu)3711 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3712 {
3713 ++vcpu->stat.tlb_flush;
3714 kvm_x86_call(flush_tlb_current)(vcpu);
3715 }
3716
3717 /*
3718 * Service "local" TLB flush requests, which are specific to the current MMU
3719 * context. In addition to the generic event handling in vcpu_enter_guest(),
3720 * TLB flushes that are targeted at an MMU context also need to be serviced
3721 * prior before nested VM-Enter/VM-Exit.
3722 */
kvm_service_local_tlb_flush_requests(struct kvm_vcpu * vcpu)3723 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3724 {
3725 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3726 kvm_vcpu_flush_tlb_current(vcpu);
3727
3728 if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3729 kvm_vcpu_flush_tlb_guest(vcpu);
3730 }
3731 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_service_local_tlb_flush_requests);
3732
record_steal_time(struct kvm_vcpu * vcpu)3733 static void record_steal_time(struct kvm_vcpu *vcpu)
3734 {
3735 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3736 struct kvm_steal_time __user *st;
3737 struct kvm_memslots *slots;
3738 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3739 u64 steal;
3740 u32 version;
3741
3742 if (kvm_xen_msr_enabled(vcpu->kvm)) {
3743 kvm_xen_runstate_set_running(vcpu);
3744 return;
3745 }
3746
3747 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3748 return;
3749
3750 if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3751 return;
3752
3753 slots = kvm_memslots(vcpu->kvm);
3754
3755 if (unlikely(slots->generation != ghc->generation ||
3756 gpa != ghc->gpa ||
3757 kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3758 /* We rely on the fact that it fits in a single page. */
3759 BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3760
3761 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3762 kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3763 return;
3764 }
3765
3766 st = (struct kvm_steal_time __user *)ghc->hva;
3767 /*
3768 * Doing a TLB flush here, on the guest's behalf, can avoid
3769 * expensive IPIs.
3770 */
3771 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3772 u8 st_preempted = 0;
3773 int err = -EFAULT;
3774
3775 if (!user_access_begin(st, sizeof(*st)))
3776 return;
3777
3778 asm volatile("1: xchgb %0, %2\n"
3779 "xor %1, %1\n"
3780 "2:\n"
3781 _ASM_EXTABLE_UA(1b, 2b)
3782 : "+q" (st_preempted),
3783 "+&r" (err),
3784 "+m" (st->preempted));
3785 if (err)
3786 goto out;
3787
3788 user_access_end();
3789
3790 vcpu->arch.st.preempted = 0;
3791
3792 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3793 st_preempted & KVM_VCPU_FLUSH_TLB);
3794 if (st_preempted & KVM_VCPU_FLUSH_TLB)
3795 kvm_vcpu_flush_tlb_guest(vcpu);
3796
3797 if (!user_access_begin(st, sizeof(*st)))
3798 goto dirty;
3799 } else {
3800 if (!user_access_begin(st, sizeof(*st)))
3801 return;
3802
3803 unsafe_put_user(0, &st->preempted, out);
3804 vcpu->arch.st.preempted = 0;
3805 }
3806
3807 unsafe_get_user(version, &st->version, out);
3808 if (version & 1)
3809 version += 1; /* first time write, random junk */
3810
3811 version += 1;
3812 unsafe_put_user(version, &st->version, out);
3813
3814 smp_wmb();
3815
3816 unsafe_get_user(steal, &st->steal, out);
3817 steal += current->sched_info.run_delay -
3818 vcpu->arch.st.last_steal;
3819 vcpu->arch.st.last_steal = current->sched_info.run_delay;
3820 unsafe_put_user(steal, &st->steal, out);
3821
3822 version += 1;
3823 unsafe_put_user(version, &st->version, out);
3824
3825 out:
3826 user_access_end();
3827 dirty:
3828 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3829 }
3830
3831 /*
3832 * Returns true if the MSR in question is managed via XSTATE, i.e. is context
3833 * switched with the rest of guest FPU state.
3834 *
3835 * Note, S_CET is _not_ saved/restored via XSAVES/XRSTORS.
3836 */
is_xstate_managed_msr(struct kvm_vcpu * vcpu,u32 msr)3837 static bool is_xstate_managed_msr(struct kvm_vcpu *vcpu, u32 msr)
3838 {
3839 if (!vcpu)
3840 return false;
3841
3842 switch (msr) {
3843 case MSR_IA32_U_CET:
3844 return guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) ||
3845 guest_cpu_cap_has(vcpu, X86_FEATURE_IBT);
3846 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
3847 return guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK);
3848 default:
3849 return false;
3850 }
3851 }
3852
3853 /*
3854 * Lock (and if necessary, re-load) the guest FPU, i.e. XSTATE, and access an
3855 * MSR that is managed via XSTATE. Note, the caller is responsible for doing
3856 * the initial FPU load, this helper only ensures that guest state is resident
3857 * in hardware (the kernel can load its FPU state in IRQ context).
3858 *
3859 * Note, loading guest values for U_CET and PL[0-3]_SSP while executing in the
3860 * kernel is safe, as U_CET is specific to userspace, and PL[0-3]_SSP are only
3861 * consumed when transitioning to lower privilege levels, i.e. are effectively
3862 * only consumed by userspace as well.
3863 */
kvm_access_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info,int access)3864 static __always_inline void kvm_access_xstate_msr(struct kvm_vcpu *vcpu,
3865 struct msr_data *msr_info,
3866 int access)
3867 {
3868 BUILD_BUG_ON(access != MSR_TYPE_R && access != MSR_TYPE_W);
3869
3870 KVM_BUG_ON(!is_xstate_managed_msr(vcpu, msr_info->index), vcpu->kvm);
3871 KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm);
3872
3873 kvm_fpu_get();
3874 if (access == MSR_TYPE_R)
3875 rdmsrq(msr_info->index, msr_info->data);
3876 else
3877 wrmsrq(msr_info->index, msr_info->data);
3878 kvm_fpu_put();
3879 }
3880
kvm_set_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3881 static void kvm_set_xstate_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3882 {
3883 kvm_access_xstate_msr(vcpu, msr_info, MSR_TYPE_W);
3884 }
3885
kvm_get_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3886 static void kvm_get_xstate_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3887 {
3888 kvm_access_xstate_msr(vcpu, msr_info, MSR_TYPE_R);
3889 }
3890
kvm_set_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3891 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3892 {
3893 u32 msr = msr_info->index;
3894 u64 data = msr_info->data;
3895
3896 /*
3897 * Do not allow host-initiated writes to trigger the Xen hypercall
3898 * page setup; it could incur locking paths which are not expected
3899 * if userspace sets the MSR in an unusual location.
3900 */
3901 if (kvm_xen_is_hypercall_page_msr(vcpu->kvm, msr) &&
3902 !msr_info->host_initiated)
3903 return kvm_xen_write_hypercall_page(vcpu, data);
3904
3905 switch (msr) {
3906 case MSR_AMD64_NB_CFG:
3907 case MSR_IA32_UCODE_WRITE:
3908 case MSR_VM_HSAVE_PA:
3909 case MSR_AMD64_PATCH_LOADER:
3910 case MSR_AMD64_BU_CFG2:
3911 case MSR_AMD64_DC_CFG:
3912 case MSR_AMD64_TW_CFG:
3913 case MSR_F15H_EX_CFG:
3914 break;
3915
3916 case MSR_IA32_UCODE_REV:
3917 if (msr_info->host_initiated)
3918 vcpu->arch.microcode_version = data;
3919 break;
3920 case MSR_IA32_ARCH_CAPABILITIES:
3921 if (!msr_info->host_initiated ||
3922 !guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3923 return KVM_MSR_RET_UNSUPPORTED;
3924 vcpu->arch.arch_capabilities = data;
3925 break;
3926 case MSR_IA32_PERF_CAPABILITIES:
3927 if (!msr_info->host_initiated ||
3928 !guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
3929 return KVM_MSR_RET_UNSUPPORTED;
3930
3931 if (data & ~kvm_caps.supported_perf_cap)
3932 return 1;
3933
3934 /*
3935 * Note, this is not just a performance optimization! KVM
3936 * disallows changing feature MSRs after the vCPU has run; PMU
3937 * refresh will bug the VM if called after the vCPU has run.
3938 */
3939 if (vcpu->arch.perf_capabilities == data)
3940 break;
3941
3942 vcpu->arch.perf_capabilities = data;
3943 kvm_pmu_refresh(vcpu);
3944 break;
3945 case MSR_IA32_PRED_CMD: {
3946 u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3947
3948 if (!msr_info->host_initiated) {
3949 if ((!guest_has_pred_cmd_msr(vcpu)))
3950 return 1;
3951
3952 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3953 !guest_cpu_cap_has(vcpu, X86_FEATURE_AMD_IBPB))
3954 reserved_bits |= PRED_CMD_IBPB;
3955
3956 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SBPB))
3957 reserved_bits |= PRED_CMD_SBPB;
3958 }
3959
3960 if (!boot_cpu_has(X86_FEATURE_IBPB))
3961 reserved_bits |= PRED_CMD_IBPB;
3962
3963 if (!boot_cpu_has(X86_FEATURE_SBPB))
3964 reserved_bits |= PRED_CMD_SBPB;
3965
3966 if (data & reserved_bits)
3967 return 1;
3968
3969 if (!data)
3970 break;
3971
3972 wrmsrq(MSR_IA32_PRED_CMD, data);
3973 break;
3974 }
3975 case MSR_IA32_FLUSH_CMD:
3976 if (!msr_info->host_initiated &&
3977 !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D))
3978 return 1;
3979
3980 if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
3981 return 1;
3982 if (!data)
3983 break;
3984
3985 wrmsrq(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
3986 break;
3987 case MSR_EFER:
3988 return set_efer(vcpu, msr_info);
3989 case MSR_K7_HWCR:
3990 data &= ~(u64)0x40; /* ignore flush filter disable */
3991 data &= ~(u64)0x100; /* ignore ignne emulation enable */
3992 data &= ~(u64)0x8; /* ignore TLB cache disable */
3993
3994 /*
3995 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
3996 * through at least v6.6 whine if TscFreqSel is clear,
3997 * depending on F/M/S.
3998 */
3999 if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
4000 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4001 return 1;
4002 }
4003 vcpu->arch.msr_hwcr = data;
4004 break;
4005 case MSR_FAM10H_MMIO_CONF_BASE:
4006 if (data != 0) {
4007 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4008 return 1;
4009 }
4010 break;
4011 case MSR_IA32_CR_PAT:
4012 if (!kvm_pat_valid(data))
4013 return 1;
4014
4015 vcpu->arch.pat = data;
4016 break;
4017 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4018 case MSR_MTRRdefType:
4019 return kvm_mtrr_set_msr(vcpu, msr, data);
4020 case MSR_IA32_APICBASE:
4021 return kvm_apic_set_base(vcpu, data, msr_info->host_initiated);
4022 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4023 return kvm_x2apic_msr_write(vcpu, msr, data);
4024 case MSR_IA32_TSC_DEADLINE:
4025 kvm_set_lapic_tscdeadline_msr(vcpu, data);
4026 break;
4027 case MSR_IA32_TSC_ADJUST:
4028 if (guest_cpu_cap_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
4029 if (!msr_info->host_initiated) {
4030 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
4031 adjust_tsc_offset_guest(vcpu, adj);
4032 /* Before back to guest, tsc_timestamp must be adjusted
4033 * as well, otherwise guest's percpu pvclock time could jump.
4034 */
4035 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4036 }
4037 vcpu->arch.ia32_tsc_adjust_msr = data;
4038 }
4039 break;
4040 case MSR_IA32_MISC_ENABLE: {
4041 u64 old_val = vcpu->arch.ia32_misc_enable_msr;
4042
4043 if (!msr_info->host_initiated) {
4044 /* RO bits */
4045 if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
4046 return 1;
4047
4048 /* R bits, i.e. writes are ignored, but don't fault. */
4049 data = data & ~MSR_IA32_MISC_ENABLE_EMON;
4050 data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
4051 }
4052
4053 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
4054 ((old_val ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
4055 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_XMM3))
4056 return 1;
4057 vcpu->arch.ia32_misc_enable_msr = data;
4058 vcpu->arch.cpuid_dynamic_bits_dirty = true;
4059 } else {
4060 vcpu->arch.ia32_misc_enable_msr = data;
4061 }
4062 break;
4063 }
4064 case MSR_IA32_SMBASE:
4065 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4066 return 1;
4067 vcpu->arch.smbase = data;
4068 break;
4069 case MSR_IA32_POWER_CTL:
4070 vcpu->arch.msr_ia32_power_ctl = data;
4071 break;
4072 case MSR_IA32_TSC:
4073 if (msr_info->host_initiated) {
4074 kvm_synchronize_tsc(vcpu, &data);
4075 } else if (!vcpu->arch.guest_tsc_protected) {
4076 u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
4077 adjust_tsc_offset_guest(vcpu, adj);
4078 vcpu->arch.ia32_tsc_adjust_msr += adj;
4079 }
4080 break;
4081 case MSR_IA32_XSS:
4082 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4083 return KVM_MSR_RET_UNSUPPORTED;
4084
4085 if (data & ~vcpu->arch.guest_supported_xss)
4086 return 1;
4087 if (vcpu->arch.ia32_xss == data)
4088 break;
4089 vcpu->arch.ia32_xss = data;
4090 vcpu->arch.cpuid_dynamic_bits_dirty = true;
4091 break;
4092 case MSR_SMI_COUNT:
4093 if (!msr_info->host_initiated)
4094 return 1;
4095 vcpu->arch.smi_count = data;
4096 break;
4097 case MSR_KVM_WALL_CLOCK_NEW:
4098 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4099 return 1;
4100
4101 vcpu->kvm->arch.wall_clock = data;
4102 kvm_write_wall_clock(vcpu->kvm, data, 0);
4103 break;
4104 case MSR_KVM_WALL_CLOCK:
4105 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4106 return 1;
4107
4108 vcpu->kvm->arch.wall_clock = data;
4109 kvm_write_wall_clock(vcpu->kvm, data, 0);
4110 break;
4111 case MSR_KVM_SYSTEM_TIME_NEW:
4112 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4113 return 1;
4114
4115 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
4116 break;
4117 case MSR_KVM_SYSTEM_TIME:
4118 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4119 return 1;
4120
4121 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
4122 break;
4123 case MSR_KVM_ASYNC_PF_EN:
4124 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4125 return 1;
4126
4127 if (kvm_pv_enable_async_pf(vcpu, data))
4128 return 1;
4129 break;
4130 case MSR_KVM_ASYNC_PF_INT:
4131 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4132 return 1;
4133
4134 if (kvm_pv_enable_async_pf_int(vcpu, data))
4135 return 1;
4136 break;
4137 case MSR_KVM_ASYNC_PF_ACK:
4138 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4139 return 1;
4140 if (data & 0x1) {
4141 /*
4142 * Pairs with the smp_mb__after_atomic() in
4143 * kvm_arch_async_page_present_queued().
4144 */
4145 smp_store_mb(vcpu->arch.apf.pageready_pending, false);
4146
4147 kvm_check_async_pf_completion(vcpu);
4148 }
4149 break;
4150 case MSR_KVM_STEAL_TIME:
4151 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4152 return 1;
4153
4154 if (unlikely(!sched_info_on()))
4155 return 1;
4156
4157 if (data & KVM_STEAL_RESERVED_MASK)
4158 return 1;
4159
4160 vcpu->arch.st.msr_val = data;
4161
4162 if (!(data & KVM_MSR_ENABLED))
4163 break;
4164
4165 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4166
4167 break;
4168 case MSR_KVM_PV_EOI_EN:
4169 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4170 return 1;
4171
4172 if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
4173 return 1;
4174 break;
4175
4176 case MSR_KVM_POLL_CONTROL:
4177 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4178 return 1;
4179
4180 /* only enable bit supported */
4181 if (data & (-1ULL << 1))
4182 return 1;
4183
4184 vcpu->arch.msr_kvm_poll_control = data;
4185 break;
4186
4187 case MSR_IA32_MCG_CTL:
4188 case MSR_IA32_MCG_STATUS:
4189 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4190 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4191 return set_msr_mce(vcpu, msr_info);
4192
4193 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4194 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4195 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4196 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4197 if (kvm_pmu_is_valid_msr(vcpu, msr))
4198 return kvm_pmu_set_msr(vcpu, msr_info);
4199
4200 if (data)
4201 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4202 break;
4203 case MSR_K7_CLK_CTL:
4204 /*
4205 * Ignore all writes to this no longer documented MSR.
4206 * Writes are only relevant for old K7 processors,
4207 * all pre-dating SVM, but a recommended workaround from
4208 * AMD for these chips. It is possible to specify the
4209 * affected processor models on the command line, hence
4210 * the need to ignore the workaround.
4211 */
4212 break;
4213 #ifdef CONFIG_KVM_HYPERV
4214 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4215 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4216 case HV_X64_MSR_SYNDBG_OPTIONS:
4217 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4218 case HV_X64_MSR_CRASH_CTL:
4219 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4220 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4221 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4222 case HV_X64_MSR_TSC_EMULATION_STATUS:
4223 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4224 return kvm_hv_set_msr_common(vcpu, msr, data,
4225 msr_info->host_initiated);
4226 #endif
4227 case MSR_IA32_BBL_CR_CTL3:
4228 /* Drop writes to this legacy MSR -- see rdmsr
4229 * counterpart for further detail.
4230 */
4231 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4232 break;
4233 case MSR_AMD64_OSVW_ID_LENGTH:
4234 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4235 return 1;
4236 vcpu->arch.osvw.length = data;
4237 break;
4238 case MSR_AMD64_OSVW_STATUS:
4239 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4240 return 1;
4241 vcpu->arch.osvw.status = data;
4242 break;
4243 case MSR_PLATFORM_INFO:
4244 if (!msr_info->host_initiated)
4245 return 1;
4246 vcpu->arch.msr_platform_info = data;
4247 break;
4248 case MSR_MISC_FEATURES_ENABLES:
4249 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4250 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4251 !supports_cpuid_fault(vcpu)))
4252 return 1;
4253 vcpu->arch.msr_misc_features_enables = data;
4254 break;
4255 #ifdef CONFIG_X86_64
4256 case MSR_IA32_XFD:
4257 if (!msr_info->host_initiated &&
4258 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4259 return 1;
4260
4261 if (data & ~kvm_guest_supported_xfd(vcpu))
4262 return 1;
4263
4264 fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4265 break;
4266 case MSR_IA32_XFD_ERR:
4267 if (!msr_info->host_initiated &&
4268 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4269 return 1;
4270
4271 if (data & ~kvm_guest_supported_xfd(vcpu))
4272 return 1;
4273
4274 vcpu->arch.guest_fpu.xfd_err = data;
4275 break;
4276 #endif
4277 case MSR_IA32_U_CET:
4278 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
4279 kvm_set_xstate_msr(vcpu, msr_info);
4280 break;
4281 default:
4282 if (kvm_pmu_is_valid_msr(vcpu, msr))
4283 return kvm_pmu_set_msr(vcpu, msr_info);
4284
4285 return KVM_MSR_RET_UNSUPPORTED;
4286 }
4287 return 0;
4288 }
4289 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_msr_common);
4290
get_msr_mce(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)4291 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
4292 {
4293 u64 data;
4294 u64 mcg_cap = vcpu->arch.mcg_cap;
4295 unsigned bank_num = mcg_cap & 0xff;
4296 u32 offset, last_msr;
4297
4298 switch (msr) {
4299 case MSR_IA32_P5_MC_ADDR:
4300 case MSR_IA32_P5_MC_TYPE:
4301 data = 0;
4302 break;
4303 case MSR_IA32_MCG_CAP:
4304 data = vcpu->arch.mcg_cap;
4305 break;
4306 case MSR_IA32_MCG_CTL:
4307 if (!(mcg_cap & MCG_CTL_P) && !host)
4308 return 1;
4309 data = vcpu->arch.mcg_ctl;
4310 break;
4311 case MSR_IA32_MCG_STATUS:
4312 data = vcpu->arch.mcg_status;
4313 break;
4314 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4315 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4316 if (msr > last_msr)
4317 return 1;
4318
4319 if (!(mcg_cap & MCG_CMCI_P) && !host)
4320 return 1;
4321 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4322 last_msr + 1 - MSR_IA32_MC0_CTL2);
4323 data = vcpu->arch.mci_ctl2_banks[offset];
4324 break;
4325 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4326 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4327 if (msr > last_msr)
4328 return 1;
4329
4330 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4331 last_msr + 1 - MSR_IA32_MC0_CTL);
4332 data = vcpu->arch.mce_banks[offset];
4333 break;
4334 default:
4335 return 1;
4336 }
4337 *pdata = data;
4338 return 0;
4339 }
4340
kvm_get_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4341 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4342 {
4343 switch (msr_info->index) {
4344 case MSR_IA32_PLATFORM_ID:
4345 case MSR_IA32_EBL_CR_POWERON:
4346 case MSR_IA32_LASTBRANCHFROMIP:
4347 case MSR_IA32_LASTBRANCHTOIP:
4348 case MSR_IA32_LASTINTFROMIP:
4349 case MSR_IA32_LASTINTTOIP:
4350 case MSR_AMD64_SYSCFG:
4351 case MSR_K8_TSEG_ADDR:
4352 case MSR_K8_TSEG_MASK:
4353 case MSR_VM_HSAVE_PA:
4354 case MSR_K8_INT_PENDING_MSG:
4355 case MSR_AMD64_NB_CFG:
4356 case MSR_FAM10H_MMIO_CONF_BASE:
4357 case MSR_AMD64_BU_CFG2:
4358 case MSR_IA32_PERF_CTL:
4359 case MSR_AMD64_DC_CFG:
4360 case MSR_AMD64_TW_CFG:
4361 case MSR_F15H_EX_CFG:
4362 /*
4363 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4364 * limit) MSRs. Just return 0, as we do not want to expose the host
4365 * data here. Do not conditionalize this on CPUID, as KVM does not do
4366 * so for existing CPU-specific MSRs.
4367 */
4368 case MSR_RAPL_POWER_UNIT:
4369 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
4370 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
4371 case MSR_PKG_ENERGY_STATUS: /* Total package */
4372 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
4373 msr_info->data = 0;
4374 break;
4375 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4376 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4377 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4378 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4379 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4380 return kvm_pmu_get_msr(vcpu, msr_info);
4381 msr_info->data = 0;
4382 break;
4383 case MSR_IA32_UCODE_REV:
4384 msr_info->data = vcpu->arch.microcode_version;
4385 break;
4386 case MSR_IA32_ARCH_CAPABILITIES:
4387 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4388 return KVM_MSR_RET_UNSUPPORTED;
4389 msr_info->data = vcpu->arch.arch_capabilities;
4390 break;
4391 case MSR_IA32_PERF_CAPABILITIES:
4392 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
4393 return KVM_MSR_RET_UNSUPPORTED;
4394 msr_info->data = vcpu->arch.perf_capabilities;
4395 break;
4396 case MSR_IA32_POWER_CTL:
4397 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4398 break;
4399 case MSR_IA32_TSC: {
4400 /*
4401 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4402 * even when not intercepted. AMD manual doesn't explicitly
4403 * state this but appears to behave the same.
4404 *
4405 * On userspace reads and writes, however, we unconditionally
4406 * return L1's TSC value to ensure backwards-compatible
4407 * behavior for migration.
4408 */
4409 u64 offset, ratio;
4410
4411 if (msr_info->host_initiated) {
4412 offset = vcpu->arch.l1_tsc_offset;
4413 ratio = vcpu->arch.l1_tsc_scaling_ratio;
4414 } else {
4415 offset = vcpu->arch.tsc_offset;
4416 ratio = vcpu->arch.tsc_scaling_ratio;
4417 }
4418
4419 msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4420 break;
4421 }
4422 case MSR_IA32_CR_PAT:
4423 msr_info->data = vcpu->arch.pat;
4424 break;
4425 case MSR_MTRRcap:
4426 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4427 case MSR_MTRRdefType:
4428 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4429 case 0xcd: /* fsb frequency */
4430 msr_info->data = 3;
4431 break;
4432 /*
4433 * MSR_EBC_FREQUENCY_ID
4434 * Conservative value valid for even the basic CPU models.
4435 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4436 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4437 * and 266MHz for model 3, or 4. Set Core Clock
4438 * Frequency to System Bus Frequency Ratio to 1 (bits
4439 * 31:24) even though these are only valid for CPU
4440 * models > 2, however guests may end up dividing or
4441 * multiplying by zero otherwise.
4442 */
4443 case MSR_EBC_FREQUENCY_ID:
4444 msr_info->data = 1 << 24;
4445 break;
4446 case MSR_IA32_APICBASE:
4447 msr_info->data = vcpu->arch.apic_base;
4448 break;
4449 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4450 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4451 case MSR_IA32_TSC_DEADLINE:
4452 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4453 break;
4454 case MSR_IA32_TSC_ADJUST:
4455 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4456 break;
4457 case MSR_IA32_MISC_ENABLE:
4458 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4459 break;
4460 case MSR_IA32_SMBASE:
4461 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4462 return 1;
4463 msr_info->data = vcpu->arch.smbase;
4464 break;
4465 case MSR_SMI_COUNT:
4466 msr_info->data = vcpu->arch.smi_count;
4467 break;
4468 case MSR_IA32_PERF_STATUS:
4469 /* TSC increment by tick */
4470 msr_info->data = 1000ULL;
4471 /* CPU multiplier */
4472 msr_info->data |= (((uint64_t)4ULL) << 40);
4473 break;
4474 case MSR_EFER:
4475 msr_info->data = vcpu->arch.efer;
4476 break;
4477 case MSR_KVM_WALL_CLOCK:
4478 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4479 return 1;
4480
4481 msr_info->data = vcpu->kvm->arch.wall_clock;
4482 break;
4483 case MSR_KVM_WALL_CLOCK_NEW:
4484 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4485 return 1;
4486
4487 msr_info->data = vcpu->kvm->arch.wall_clock;
4488 break;
4489 case MSR_KVM_SYSTEM_TIME:
4490 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4491 return 1;
4492
4493 msr_info->data = vcpu->arch.time;
4494 break;
4495 case MSR_KVM_SYSTEM_TIME_NEW:
4496 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4497 return 1;
4498
4499 msr_info->data = vcpu->arch.time;
4500 break;
4501 case MSR_KVM_ASYNC_PF_EN:
4502 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4503 return 1;
4504
4505 msr_info->data = vcpu->arch.apf.msr_en_val;
4506 break;
4507 case MSR_KVM_ASYNC_PF_INT:
4508 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4509 return 1;
4510
4511 msr_info->data = vcpu->arch.apf.msr_int_val;
4512 break;
4513 case MSR_KVM_ASYNC_PF_ACK:
4514 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4515 return 1;
4516
4517 msr_info->data = 0;
4518 break;
4519 case MSR_KVM_STEAL_TIME:
4520 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4521 return 1;
4522
4523 msr_info->data = vcpu->arch.st.msr_val;
4524 break;
4525 case MSR_KVM_PV_EOI_EN:
4526 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4527 return 1;
4528
4529 msr_info->data = vcpu->arch.pv_eoi.msr_val;
4530 break;
4531 case MSR_KVM_POLL_CONTROL:
4532 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4533 return 1;
4534
4535 msr_info->data = vcpu->arch.msr_kvm_poll_control;
4536 break;
4537 case MSR_IA32_P5_MC_ADDR:
4538 case MSR_IA32_P5_MC_TYPE:
4539 case MSR_IA32_MCG_CAP:
4540 case MSR_IA32_MCG_CTL:
4541 case MSR_IA32_MCG_STATUS:
4542 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4543 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4544 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4545 msr_info->host_initiated);
4546 case MSR_IA32_XSS:
4547 if (!msr_info->host_initiated &&
4548 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4549 return 1;
4550 msr_info->data = vcpu->arch.ia32_xss;
4551 break;
4552 case MSR_K7_CLK_CTL:
4553 /*
4554 * Provide expected ramp-up count for K7. All other
4555 * are set to zero, indicating minimum divisors for
4556 * every field.
4557 *
4558 * This prevents guest kernels on AMD host with CPU
4559 * type 6, model 8 and higher from exploding due to
4560 * the rdmsr failing.
4561 */
4562 msr_info->data = 0x20000000;
4563 break;
4564 #ifdef CONFIG_KVM_HYPERV
4565 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4566 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4567 case HV_X64_MSR_SYNDBG_OPTIONS:
4568 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4569 case HV_X64_MSR_CRASH_CTL:
4570 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4571 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4572 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4573 case HV_X64_MSR_TSC_EMULATION_STATUS:
4574 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4575 return kvm_hv_get_msr_common(vcpu,
4576 msr_info->index, &msr_info->data,
4577 msr_info->host_initiated);
4578 #endif
4579 case MSR_IA32_BBL_CR_CTL3:
4580 /* This legacy MSR exists but isn't fully documented in current
4581 * silicon. It is however accessed by winxp in very narrow
4582 * scenarios where it sets bit #19, itself documented as
4583 * a "reserved" bit. Best effort attempt to source coherent
4584 * read data here should the balance of the register be
4585 * interpreted by the guest:
4586 *
4587 * L2 cache control register 3: 64GB range, 256KB size,
4588 * enabled, latency 0x1, configured
4589 */
4590 msr_info->data = 0xbe702111;
4591 break;
4592 case MSR_AMD64_OSVW_ID_LENGTH:
4593 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4594 return 1;
4595 msr_info->data = vcpu->arch.osvw.length;
4596 break;
4597 case MSR_AMD64_OSVW_STATUS:
4598 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4599 return 1;
4600 msr_info->data = vcpu->arch.osvw.status;
4601 break;
4602 case MSR_PLATFORM_INFO:
4603 if (!msr_info->host_initiated &&
4604 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4605 return 1;
4606 msr_info->data = vcpu->arch.msr_platform_info;
4607 break;
4608 case MSR_MISC_FEATURES_ENABLES:
4609 msr_info->data = vcpu->arch.msr_misc_features_enables;
4610 break;
4611 case MSR_K7_HWCR:
4612 msr_info->data = vcpu->arch.msr_hwcr;
4613 break;
4614 #ifdef CONFIG_X86_64
4615 case MSR_IA32_XFD:
4616 if (!msr_info->host_initiated &&
4617 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4618 return 1;
4619
4620 msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4621 break;
4622 case MSR_IA32_XFD_ERR:
4623 if (!msr_info->host_initiated &&
4624 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4625 return 1;
4626
4627 msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4628 break;
4629 #endif
4630 case MSR_IA32_U_CET:
4631 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
4632 kvm_get_xstate_msr(vcpu, msr_info);
4633 break;
4634 default:
4635 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4636 return kvm_pmu_get_msr(vcpu, msr_info);
4637
4638 return KVM_MSR_RET_UNSUPPORTED;
4639 }
4640 return 0;
4641 }
4642 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_msr_common);
4643
4644 /*
4645 * Read or write a bunch of msrs. All parameters are kernel addresses.
4646 *
4647 * @return number of msrs set successfully.
4648 */
__msr_io(struct kvm_vcpu * vcpu,struct kvm_msrs * msrs,struct kvm_msr_entry * entries,int (* do_msr)(struct kvm_vcpu * vcpu,unsigned index,u64 * data))4649 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4650 struct kvm_msr_entry *entries,
4651 int (*do_msr)(struct kvm_vcpu *vcpu,
4652 unsigned index, u64 *data))
4653 {
4654 bool fpu_loaded = false;
4655 int i;
4656
4657 for (i = 0; i < msrs->nmsrs; ++i) {
4658 /*
4659 * If userspace is accessing one or more XSTATE-managed MSRs,
4660 * temporarily load the guest's FPU state so that the guest's
4661 * MSR value(s) is resident in hardware and thus can be accessed
4662 * via RDMSR/WRMSR.
4663 */
4664 if (!fpu_loaded && is_xstate_managed_msr(vcpu, entries[i].index)) {
4665 kvm_load_guest_fpu(vcpu);
4666 fpu_loaded = true;
4667 }
4668 if (do_msr(vcpu, entries[i].index, &entries[i].data))
4669 break;
4670 }
4671 if (fpu_loaded)
4672 kvm_put_guest_fpu(vcpu);
4673
4674 return i;
4675 }
4676
4677 /*
4678 * Read or write a bunch of msrs. Parameters are user addresses.
4679 *
4680 * @return number of msrs set successfully.
4681 */
msr_io(struct kvm_vcpu * vcpu,struct kvm_msrs __user * user_msrs,int (* do_msr)(struct kvm_vcpu * vcpu,unsigned index,u64 * data),int writeback)4682 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4683 int (*do_msr)(struct kvm_vcpu *vcpu,
4684 unsigned index, u64 *data),
4685 int writeback)
4686 {
4687 struct kvm_msrs msrs;
4688 struct kvm_msr_entry *entries;
4689 unsigned size;
4690 int r;
4691
4692 r = -EFAULT;
4693 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4694 goto out;
4695
4696 r = -E2BIG;
4697 if (msrs.nmsrs >= MAX_IO_MSRS)
4698 goto out;
4699
4700 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4701 entries = memdup_user(user_msrs->entries, size);
4702 if (IS_ERR(entries)) {
4703 r = PTR_ERR(entries);
4704 goto out;
4705 }
4706
4707 r = __msr_io(vcpu, &msrs, entries, do_msr);
4708
4709 if (writeback && copy_to_user(user_msrs->entries, entries, size))
4710 r = -EFAULT;
4711
4712 kfree(entries);
4713 out:
4714 return r;
4715 }
4716
kvm_can_mwait_in_guest(void)4717 static inline bool kvm_can_mwait_in_guest(void)
4718 {
4719 return boot_cpu_has(X86_FEATURE_MWAIT) &&
4720 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
4721 boot_cpu_has(X86_FEATURE_ARAT);
4722 }
4723
kvm_get_allowed_disable_exits(void)4724 static u64 kvm_get_allowed_disable_exits(void)
4725 {
4726 u64 r = KVM_X86_DISABLE_EXITS_PAUSE;
4727
4728 if (boot_cpu_has(X86_FEATURE_APERFMPERF))
4729 r |= KVM_X86_DISABLE_EXITS_APERFMPERF;
4730
4731 if (!mitigate_smt_rsb) {
4732 r |= KVM_X86_DISABLE_EXITS_HLT |
4733 KVM_X86_DISABLE_EXITS_CSTATE;
4734
4735 if (kvm_can_mwait_in_guest())
4736 r |= KVM_X86_DISABLE_EXITS_MWAIT;
4737 }
4738 return r;
4739 }
4740
4741 #ifdef CONFIG_KVM_HYPERV
kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 __user * cpuid_arg)4742 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4743 struct kvm_cpuid2 __user *cpuid_arg)
4744 {
4745 struct kvm_cpuid2 cpuid;
4746 int r;
4747
4748 r = -EFAULT;
4749 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4750 return r;
4751
4752 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4753 if (r)
4754 return r;
4755
4756 r = -EFAULT;
4757 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4758 return r;
4759
4760 return 0;
4761 }
4762 #endif
4763
kvm_is_vm_type_supported(unsigned long type)4764 static bool kvm_is_vm_type_supported(unsigned long type)
4765 {
4766 return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
4767 }
4768
kvm_sync_valid_fields(struct kvm * kvm)4769 static inline u64 kvm_sync_valid_fields(struct kvm *kvm)
4770 {
4771 return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
4772 }
4773
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)4774 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4775 {
4776 int r = 0;
4777
4778 switch (ext) {
4779 case KVM_CAP_IRQCHIP:
4780 case KVM_CAP_HLT:
4781 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4782 case KVM_CAP_SET_TSS_ADDR:
4783 case KVM_CAP_EXT_CPUID:
4784 case KVM_CAP_EXT_EMUL_CPUID:
4785 case KVM_CAP_CLOCKSOURCE:
4786 #ifdef CONFIG_KVM_IOAPIC
4787 case KVM_CAP_PIT:
4788 case KVM_CAP_PIT2:
4789 case KVM_CAP_PIT_STATE2:
4790 case KVM_CAP_REINJECT_CONTROL:
4791 #endif
4792 case KVM_CAP_NOP_IO_DELAY:
4793 case KVM_CAP_MP_STATE:
4794 case KVM_CAP_SYNC_MMU:
4795 case KVM_CAP_USER_NMI:
4796 case KVM_CAP_IRQ_INJECT_STATUS:
4797 case KVM_CAP_IOEVENTFD:
4798 case KVM_CAP_IOEVENTFD_NO_LENGTH:
4799
4800 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4801 case KVM_CAP_VCPU_EVENTS:
4802 #ifdef CONFIG_KVM_HYPERV
4803 case KVM_CAP_HYPERV:
4804 case KVM_CAP_HYPERV_VAPIC:
4805 case KVM_CAP_HYPERV_SPIN:
4806 case KVM_CAP_HYPERV_TIME:
4807 case KVM_CAP_HYPERV_SYNIC:
4808 case KVM_CAP_HYPERV_SYNIC2:
4809 case KVM_CAP_HYPERV_VP_INDEX:
4810 case KVM_CAP_HYPERV_EVENTFD:
4811 case KVM_CAP_HYPERV_TLBFLUSH:
4812 case KVM_CAP_HYPERV_SEND_IPI:
4813 case KVM_CAP_HYPERV_CPUID:
4814 case KVM_CAP_HYPERV_ENFORCE_CPUID:
4815 case KVM_CAP_SYS_HYPERV_CPUID:
4816 #endif
4817 case KVM_CAP_PCI_SEGMENT:
4818 case KVM_CAP_DEBUGREGS:
4819 case KVM_CAP_X86_ROBUST_SINGLESTEP:
4820 case KVM_CAP_XSAVE:
4821 case KVM_CAP_ASYNC_PF:
4822 case KVM_CAP_ASYNC_PF_INT:
4823 case KVM_CAP_GET_TSC_KHZ:
4824 case KVM_CAP_KVMCLOCK_CTRL:
4825 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4826 case KVM_CAP_TSC_DEADLINE_TIMER:
4827 case KVM_CAP_DISABLE_QUIRKS:
4828 case KVM_CAP_SET_BOOT_CPU_ID:
4829 case KVM_CAP_SPLIT_IRQCHIP:
4830 case KVM_CAP_IMMEDIATE_EXIT:
4831 case KVM_CAP_PMU_EVENT_FILTER:
4832 case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
4833 case KVM_CAP_GET_MSR_FEATURES:
4834 case KVM_CAP_MSR_PLATFORM_INFO:
4835 case KVM_CAP_EXCEPTION_PAYLOAD:
4836 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4837 case KVM_CAP_SET_GUEST_DEBUG:
4838 case KVM_CAP_LAST_CPU:
4839 case KVM_CAP_X86_USER_SPACE_MSR:
4840 case KVM_CAP_X86_MSR_FILTER:
4841 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4842 #ifdef CONFIG_X86_SGX_KVM
4843 case KVM_CAP_SGX_ATTRIBUTE:
4844 #endif
4845 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4846 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4847 case KVM_CAP_SREGS2:
4848 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4849 case KVM_CAP_VCPU_ATTRIBUTES:
4850 case KVM_CAP_SYS_ATTRIBUTES:
4851 case KVM_CAP_VAPIC:
4852 case KVM_CAP_ENABLE_CAP:
4853 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4854 case KVM_CAP_IRQFD_RESAMPLE:
4855 case KVM_CAP_MEMORY_FAULT_INFO:
4856 case KVM_CAP_X86_GUEST_MODE:
4857 case KVM_CAP_ONE_REG:
4858 r = 1;
4859 break;
4860 case KVM_CAP_PRE_FAULT_MEMORY:
4861 r = tdp_enabled;
4862 break;
4863 case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
4864 r = APIC_BUS_CYCLE_NS_DEFAULT;
4865 break;
4866 case KVM_CAP_EXIT_HYPERCALL:
4867 r = KVM_EXIT_HYPERCALL_VALID_MASK;
4868 break;
4869 case KVM_CAP_SET_GUEST_DEBUG2:
4870 return KVM_GUESTDBG_VALID_MASK;
4871 #ifdef CONFIG_KVM_XEN
4872 case KVM_CAP_XEN_HVM:
4873 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4874 KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4875 KVM_XEN_HVM_CONFIG_SHARED_INFO |
4876 KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4877 KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
4878 KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4879 KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
4880 if (sched_info_on())
4881 r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4882 KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
4883 break;
4884 #endif
4885 case KVM_CAP_SYNC_REGS:
4886 r = kvm_sync_valid_fields(kvm);
4887 break;
4888 case KVM_CAP_ADJUST_CLOCK:
4889 r = KVM_CLOCK_VALID_FLAGS;
4890 break;
4891 case KVM_CAP_X86_DISABLE_EXITS:
4892 r = kvm_get_allowed_disable_exits();
4893 break;
4894 case KVM_CAP_X86_SMM:
4895 if (!IS_ENABLED(CONFIG_KVM_SMM))
4896 break;
4897
4898 /* SMBASE is usually relocated above 1M on modern chipsets,
4899 * and SMM handlers might indeed rely on 4G segment limits,
4900 * so do not report SMM to be available if real mode is
4901 * emulated via vm86 mode. Still, do not go to great lengths
4902 * to avoid userspace's usage of the feature, because it is a
4903 * fringe case that is not enabled except via specific settings
4904 * of the module parameters.
4905 */
4906 r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4907 break;
4908 case KVM_CAP_NR_VCPUS:
4909 r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4910 break;
4911 case KVM_CAP_MAX_VCPUS:
4912 r = KVM_MAX_VCPUS;
4913 if (kvm)
4914 r = kvm->max_vcpus;
4915 break;
4916 case KVM_CAP_MAX_VCPU_ID:
4917 r = KVM_MAX_VCPU_IDS;
4918 break;
4919 case KVM_CAP_PV_MMU: /* obsolete */
4920 r = 0;
4921 break;
4922 case KVM_CAP_MCE:
4923 r = KVM_MAX_MCE_BANKS;
4924 break;
4925 case KVM_CAP_XCRS:
4926 r = boot_cpu_has(X86_FEATURE_XSAVE);
4927 break;
4928 case KVM_CAP_TSC_CONTROL:
4929 case KVM_CAP_VM_TSC_CONTROL:
4930 r = kvm_caps.has_tsc_control;
4931 break;
4932 case KVM_CAP_X2APIC_API:
4933 r = KVM_X2APIC_API_VALID_FLAGS;
4934 break;
4935 case KVM_CAP_NESTED_STATE:
4936 r = kvm_x86_ops.nested_ops->get_state ?
4937 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4938 break;
4939 #ifdef CONFIG_KVM_HYPERV
4940 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4941 r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
4942 break;
4943 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4944 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4945 break;
4946 #endif
4947 case KVM_CAP_SMALLER_MAXPHYADDR:
4948 r = (int) allow_smaller_maxphyaddr;
4949 break;
4950 case KVM_CAP_STEAL_TIME:
4951 r = sched_info_on();
4952 break;
4953 case KVM_CAP_X86_BUS_LOCK_EXIT:
4954 if (kvm_caps.has_bus_lock_exit)
4955 r = KVM_BUS_LOCK_DETECTION_OFF |
4956 KVM_BUS_LOCK_DETECTION_EXIT;
4957 else
4958 r = 0;
4959 break;
4960 case KVM_CAP_XSAVE2: {
4961 r = xstate_required_size(kvm_get_filtered_xcr0(), false);
4962 if (r < sizeof(struct kvm_xsave))
4963 r = sizeof(struct kvm_xsave);
4964 break;
4965 }
4966 case KVM_CAP_PMU_CAPABILITY:
4967 r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4968 break;
4969 case KVM_CAP_DISABLE_QUIRKS2:
4970 r = kvm_caps.supported_quirks;
4971 break;
4972 case KVM_CAP_X86_NOTIFY_VMEXIT:
4973 r = kvm_caps.has_notify_vmexit;
4974 break;
4975 case KVM_CAP_VM_TYPES:
4976 r = kvm_caps.supported_vm_types;
4977 break;
4978 case KVM_CAP_READONLY_MEM:
4979 r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
4980 break;
4981 default:
4982 break;
4983 }
4984 return r;
4985 }
4986
__kvm_x86_dev_get_attr(struct kvm_device_attr * attr,u64 * val)4987 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
4988 {
4989 if (attr->group) {
4990 if (kvm_x86_ops.dev_get_attr)
4991 return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
4992 return -ENXIO;
4993 }
4994
4995 switch (attr->attr) {
4996 case KVM_X86_XCOMP_GUEST_SUPP:
4997 *val = kvm_caps.supported_xcr0;
4998 return 0;
4999 default:
5000 return -ENXIO;
5001 }
5002 }
5003
kvm_x86_dev_get_attr(struct kvm_device_attr * attr)5004 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
5005 {
5006 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5007 int r;
5008 u64 val;
5009
5010 r = __kvm_x86_dev_get_attr(attr, &val);
5011 if (r < 0)
5012 return r;
5013
5014 if (put_user(val, uaddr))
5015 return -EFAULT;
5016
5017 return 0;
5018 }
5019
kvm_x86_dev_has_attr(struct kvm_device_attr * attr)5020 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
5021 {
5022 u64 val;
5023
5024 return __kvm_x86_dev_get_attr(attr, &val);
5025 }
5026
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5027 long kvm_arch_dev_ioctl(struct file *filp,
5028 unsigned int ioctl, unsigned long arg)
5029 {
5030 void __user *argp = (void __user *)arg;
5031 long r;
5032
5033 switch (ioctl) {
5034 case KVM_GET_MSR_INDEX_LIST: {
5035 struct kvm_msr_list __user *user_msr_list = argp;
5036 struct kvm_msr_list msr_list;
5037 unsigned n;
5038
5039 r = -EFAULT;
5040 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
5041 goto out;
5042 n = msr_list.nmsrs;
5043 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
5044 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
5045 goto out;
5046 r = -E2BIG;
5047 if (n < msr_list.nmsrs)
5048 goto out;
5049 r = -EFAULT;
5050 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
5051 num_msrs_to_save * sizeof(u32)))
5052 goto out;
5053 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
5054 &emulated_msrs,
5055 num_emulated_msrs * sizeof(u32)))
5056 goto out;
5057 r = 0;
5058 break;
5059 }
5060 case KVM_GET_SUPPORTED_CPUID:
5061 case KVM_GET_EMULATED_CPUID: {
5062 struct kvm_cpuid2 __user *cpuid_arg = argp;
5063 struct kvm_cpuid2 cpuid;
5064
5065 r = -EFAULT;
5066 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5067 goto out;
5068
5069 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
5070 ioctl);
5071 if (r)
5072 goto out;
5073
5074 r = -EFAULT;
5075 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5076 goto out;
5077 r = 0;
5078 break;
5079 }
5080 case KVM_X86_GET_MCE_CAP_SUPPORTED:
5081 r = -EFAULT;
5082 if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
5083 sizeof(kvm_caps.supported_mce_cap)))
5084 goto out;
5085 r = 0;
5086 break;
5087 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
5088 struct kvm_msr_list __user *user_msr_list = argp;
5089 struct kvm_msr_list msr_list;
5090 unsigned int n;
5091
5092 r = -EFAULT;
5093 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
5094 goto out;
5095 n = msr_list.nmsrs;
5096 msr_list.nmsrs = num_msr_based_features;
5097 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
5098 goto out;
5099 r = -E2BIG;
5100 if (n < msr_list.nmsrs)
5101 goto out;
5102 r = -EFAULT;
5103 if (copy_to_user(user_msr_list->indices, &msr_based_features,
5104 num_msr_based_features * sizeof(u32)))
5105 goto out;
5106 r = 0;
5107 break;
5108 }
5109 case KVM_GET_MSRS:
5110 r = msr_io(NULL, argp, do_get_feature_msr, 1);
5111 break;
5112 #ifdef CONFIG_KVM_HYPERV
5113 case KVM_GET_SUPPORTED_HV_CPUID:
5114 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
5115 break;
5116 #endif
5117 case KVM_GET_DEVICE_ATTR: {
5118 struct kvm_device_attr attr;
5119 r = -EFAULT;
5120 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
5121 break;
5122 r = kvm_x86_dev_get_attr(&attr);
5123 break;
5124 }
5125 case KVM_HAS_DEVICE_ATTR: {
5126 struct kvm_device_attr attr;
5127 r = -EFAULT;
5128 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
5129 break;
5130 r = kvm_x86_dev_has_attr(&attr);
5131 break;
5132 }
5133 default:
5134 r = -EINVAL;
5135 break;
5136 }
5137 out:
5138 return r;
5139 }
5140
need_emulate_wbinvd(struct kvm_vcpu * vcpu)5141 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
5142 {
5143 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
5144 }
5145
5146 static DEFINE_PER_CPU(struct kvm_vcpu *, last_vcpu);
5147
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)5148 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
5149 {
5150 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
5151
5152 kvm_request_l1tf_flush_l1d();
5153
5154 if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
5155 pmu->need_cleanup = true;
5156 kvm_make_request(KVM_REQ_PMU, vcpu);
5157 }
5158
5159 /* Address WBINVD may be executed by guest */
5160 if (need_emulate_wbinvd(vcpu)) {
5161 if (kvm_x86_call(has_wbinvd_exit)())
5162 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5163 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
5164 wbinvd_on_cpu(vcpu->cpu);
5165 }
5166
5167 kvm_x86_call(vcpu_load)(vcpu, cpu);
5168
5169 if (vcpu != per_cpu(last_vcpu, cpu)) {
5170 /*
5171 * Flush the branch predictor when switching vCPUs on the same
5172 * physical CPU, as each vCPU needs its own branch prediction
5173 * domain. No IBPB is needed when switching between L1 and L2
5174 * on the same vCPU unless IBRS is advertised to the vCPU; that
5175 * is handled on the nested VM-Exit path.
5176 */
5177 if (static_branch_likely(&switch_vcpu_ibpb))
5178 indirect_branch_prediction_barrier();
5179 per_cpu(last_vcpu, cpu) = vcpu;
5180 }
5181
5182 /* Save host pkru register if supported */
5183 vcpu->arch.host_pkru = read_pkru();
5184
5185 /* Apply any externally detected TSC adjustments (due to suspend) */
5186 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5187 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5188 vcpu->arch.tsc_offset_adjustment = 0;
5189 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5190 }
5191
5192 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
5193 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
5194 rdtsc() - vcpu->arch.last_host_tsc;
5195 if (tsc_delta < 0)
5196 mark_tsc_unstable("KVM discovered backwards TSC");
5197
5198 if (kvm_check_tsc_unstable()) {
5199 u64 offset = kvm_compute_l1_tsc_offset(vcpu,
5200 vcpu->arch.last_guest_tsc);
5201 kvm_vcpu_write_tsc_offset(vcpu, offset);
5202 if (!vcpu->arch.guest_tsc_protected)
5203 vcpu->arch.tsc_catchup = 1;
5204 }
5205
5206 if (kvm_lapic_hv_timer_in_use(vcpu))
5207 kvm_lapic_restart_hv_timer(vcpu);
5208
5209 /*
5210 * On a host with synchronized TSC, there is no need to update
5211 * kvmclock on vcpu->cpu migration
5212 */
5213 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
5214 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
5215 if (vcpu->cpu != cpu)
5216 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
5217 vcpu->cpu = cpu;
5218 }
5219
5220 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
5221 }
5222
kvm_steal_time_set_preempted(struct kvm_vcpu * vcpu)5223 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
5224 {
5225 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
5226 struct kvm_steal_time __user *st;
5227 struct kvm_memslots *slots;
5228 static const u8 preempted = KVM_VCPU_PREEMPTED;
5229 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
5230
5231 /*
5232 * The vCPU can be marked preempted if and only if the VM-Exit was on
5233 * an instruction boundary and will not trigger guest emulation of any
5234 * kind (see vcpu_run). Vendor specific code controls (conservatively)
5235 * when this is true, for example allowing the vCPU to be marked
5236 * preempted if and only if the VM-Exit was due to a host interrupt.
5237 */
5238 if (!vcpu->arch.at_instruction_boundary) {
5239 vcpu->stat.preemption_other++;
5240 return;
5241 }
5242
5243 vcpu->stat.preemption_reported++;
5244 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
5245 return;
5246
5247 if (vcpu->arch.st.preempted)
5248 return;
5249
5250 /* This happens on process exit */
5251 if (unlikely(current->mm != vcpu->kvm->mm))
5252 return;
5253
5254 slots = kvm_memslots(vcpu->kvm);
5255
5256 if (unlikely(slots->generation != ghc->generation ||
5257 gpa != ghc->gpa ||
5258 kvm_is_error_hva(ghc->hva) || !ghc->memslot))
5259 return;
5260
5261 st = (struct kvm_steal_time __user *)ghc->hva;
5262 BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
5263
5264 if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
5265 vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
5266
5267 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
5268 }
5269
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)5270 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
5271 {
5272 int idx;
5273
5274 if (vcpu->preempted) {
5275 /*
5276 * Assume protected guests are in-kernel. Inefficient yielding
5277 * due to false positives is preferable to never yielding due
5278 * to false negatives.
5279 */
5280 vcpu->arch.preempted_in_kernel = vcpu->arch.guest_state_protected ||
5281 !kvm_x86_call(get_cpl_no_cache)(vcpu);
5282
5283 /*
5284 * Take the srcu lock as memslots will be accessed to check the gfn
5285 * cache generation against the memslots generation.
5286 */
5287 idx = srcu_read_lock(&vcpu->kvm->srcu);
5288 if (kvm_xen_msr_enabled(vcpu->kvm))
5289 kvm_xen_runstate_set_preempted(vcpu);
5290 else
5291 kvm_steal_time_set_preempted(vcpu);
5292 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5293 }
5294
5295 kvm_x86_call(vcpu_put)(vcpu);
5296 vcpu->arch.last_host_tsc = rdtsc();
5297 }
5298
kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5299 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5300 struct kvm_lapic_state *s)
5301 {
5302 if (vcpu->arch.apic->guest_apic_protected)
5303 return -EINVAL;
5304
5305 kvm_x86_call(sync_pir_to_irr)(vcpu);
5306
5307 return kvm_apic_get_state(vcpu, s);
5308 }
5309
kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5310 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5311 struct kvm_lapic_state *s)
5312 {
5313 int r;
5314
5315 if (vcpu->arch.apic->guest_apic_protected)
5316 return -EINVAL;
5317
5318 r = kvm_apic_set_state(vcpu, s);
5319 if (r)
5320 return r;
5321 update_cr8_intercept(vcpu);
5322
5323 return 0;
5324 }
5325
kvm_cpu_accept_dm_intr(struct kvm_vcpu * vcpu)5326 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5327 {
5328 /*
5329 * We can accept userspace's request for interrupt injection
5330 * as long as we have a place to store the interrupt number.
5331 * The actual injection will happen when the CPU is able to
5332 * deliver the interrupt.
5333 */
5334 if (kvm_cpu_has_extint(vcpu))
5335 return false;
5336
5337 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
5338 return (!lapic_in_kernel(vcpu) ||
5339 kvm_apic_accept_pic_intr(vcpu));
5340 }
5341
kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu * vcpu)5342 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5343 {
5344 /*
5345 * Do not cause an interrupt window exit if an exception
5346 * is pending or an event needs reinjection; userspace
5347 * might want to inject the interrupt manually using KVM_SET_REGS
5348 * or KVM_SET_SREGS. For that to work, we must be at an
5349 * instruction boundary and with no events half-injected.
5350 */
5351 return (kvm_arch_interrupt_allowed(vcpu) &&
5352 kvm_cpu_accept_dm_intr(vcpu) &&
5353 !kvm_event_needs_reinjection(vcpu) &&
5354 !kvm_is_exception_pending(vcpu));
5355 }
5356
kvm_vcpu_ioctl_interrupt(struct kvm_vcpu * vcpu,struct kvm_interrupt * irq)5357 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5358 struct kvm_interrupt *irq)
5359 {
5360 if (irq->irq >= KVM_NR_INTERRUPTS)
5361 return -EINVAL;
5362
5363 if (!irqchip_in_kernel(vcpu->kvm)) {
5364 kvm_queue_interrupt(vcpu, irq->irq, false);
5365 kvm_make_request(KVM_REQ_EVENT, vcpu);
5366 return 0;
5367 }
5368
5369 /*
5370 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5371 * fail for in-kernel 8259.
5372 */
5373 if (pic_in_kernel(vcpu->kvm))
5374 return -ENXIO;
5375
5376 if (vcpu->arch.pending_external_vector != -1)
5377 return -EEXIST;
5378
5379 vcpu->arch.pending_external_vector = irq->irq;
5380 kvm_make_request(KVM_REQ_EVENT, vcpu);
5381 return 0;
5382 }
5383
kvm_vcpu_ioctl_nmi(struct kvm_vcpu * vcpu)5384 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5385 {
5386 kvm_inject_nmi(vcpu);
5387
5388 return 0;
5389 }
5390
vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu * vcpu,struct kvm_tpr_access_ctl * tac)5391 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5392 struct kvm_tpr_access_ctl *tac)
5393 {
5394 if (tac->flags)
5395 return -EINVAL;
5396 vcpu->arch.tpr_access_reporting = !!tac->enabled;
5397 return 0;
5398 }
5399
kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu * vcpu,u64 mcg_cap)5400 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5401 u64 mcg_cap)
5402 {
5403 int r;
5404 unsigned bank_num = mcg_cap & 0xff, bank;
5405
5406 r = -EINVAL;
5407 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
5408 goto out;
5409 if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
5410 goto out;
5411 r = 0;
5412 vcpu->arch.mcg_cap = mcg_cap;
5413 /* Init IA32_MCG_CTL to all 1s */
5414 if (mcg_cap & MCG_CTL_P)
5415 vcpu->arch.mcg_ctl = ~(u64)0;
5416 /* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5417 for (bank = 0; bank < bank_num; bank++) {
5418 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
5419 if (mcg_cap & MCG_CMCI_P)
5420 vcpu->arch.mci_ctl2_banks[bank] = 0;
5421 }
5422
5423 kvm_apic_after_set_mcg_cap(vcpu);
5424
5425 kvm_x86_call(setup_mce)(vcpu);
5426 out:
5427 return r;
5428 }
5429
5430 /*
5431 * Validate this is an UCNA (uncorrectable no action) error by checking the
5432 * MCG_STATUS and MCi_STATUS registers:
5433 * - none of the bits for Machine Check Exceptions are set
5434 * - both the VAL (valid) and UC (uncorrectable) bits are set
5435 * MCI_STATUS_PCC - Processor Context Corrupted
5436 * MCI_STATUS_S - Signaled as a Machine Check Exception
5437 * MCI_STATUS_AR - Software recoverable Action Required
5438 */
is_ucna(struct kvm_x86_mce * mce)5439 static bool is_ucna(struct kvm_x86_mce *mce)
5440 {
5441 return !mce->mcg_status &&
5442 !(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5443 (mce->status & MCI_STATUS_VAL) &&
5444 (mce->status & MCI_STATUS_UC);
5445 }
5446
kvm_vcpu_x86_set_ucna(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce,u64 * banks)5447 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5448 {
5449 u64 mcg_cap = vcpu->arch.mcg_cap;
5450
5451 banks[1] = mce->status;
5452 banks[2] = mce->addr;
5453 banks[3] = mce->misc;
5454 vcpu->arch.mcg_status = mce->mcg_status;
5455
5456 if (!(mcg_cap & MCG_CMCI_P) ||
5457 !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5458 return 0;
5459
5460 if (lapic_in_kernel(vcpu))
5461 kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5462
5463 return 0;
5464 }
5465
kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce)5466 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5467 struct kvm_x86_mce *mce)
5468 {
5469 u64 mcg_cap = vcpu->arch.mcg_cap;
5470 unsigned bank_num = mcg_cap & 0xff;
5471 u64 *banks = vcpu->arch.mce_banks;
5472
5473 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5474 return -EINVAL;
5475
5476 banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5477
5478 if (is_ucna(mce))
5479 return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5480
5481 /*
5482 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5483 * reporting is disabled
5484 */
5485 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5486 vcpu->arch.mcg_ctl != ~(u64)0)
5487 return 0;
5488 /*
5489 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5490 * reporting is disabled for the bank
5491 */
5492 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5493 return 0;
5494 if (mce->status & MCI_STATUS_UC) {
5495 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5496 !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
5497 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5498 return 0;
5499 }
5500 if (banks[1] & MCI_STATUS_VAL)
5501 mce->status |= MCI_STATUS_OVER;
5502 banks[2] = mce->addr;
5503 banks[3] = mce->misc;
5504 vcpu->arch.mcg_status = mce->mcg_status;
5505 banks[1] = mce->status;
5506 kvm_queue_exception(vcpu, MC_VECTOR);
5507 } else if (!(banks[1] & MCI_STATUS_VAL)
5508 || !(banks[1] & MCI_STATUS_UC)) {
5509 if (banks[1] & MCI_STATUS_VAL)
5510 mce->status |= MCI_STATUS_OVER;
5511 banks[2] = mce->addr;
5512 banks[3] = mce->misc;
5513 banks[1] = mce->status;
5514 } else
5515 banks[1] |= MCI_STATUS_OVER;
5516 return 0;
5517 }
5518
kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5519 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5520 struct kvm_vcpu_events *events)
5521 {
5522 struct kvm_queued_exception *ex;
5523
5524 process_nmi(vcpu);
5525
5526 #ifdef CONFIG_KVM_SMM
5527 if (kvm_check_request(KVM_REQ_SMI, vcpu))
5528 process_smi(vcpu);
5529 #endif
5530
5531 /*
5532 * KVM's ABI only allows for one exception to be migrated. Luckily,
5533 * the only time there can be two queued exceptions is if there's a
5534 * non-exiting _injected_ exception, and a pending exiting exception.
5535 * In that case, ignore the VM-Exiting exception as it's an extension
5536 * of the injected exception.
5537 */
5538 if (vcpu->arch.exception_vmexit.pending &&
5539 !vcpu->arch.exception.pending &&
5540 !vcpu->arch.exception.injected)
5541 ex = &vcpu->arch.exception_vmexit;
5542 else
5543 ex = &vcpu->arch.exception;
5544
5545 /*
5546 * In guest mode, payload delivery should be deferred if the exception
5547 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5548 * intercepts #PF, ditto for DR6 and #DBs. If the per-VM capability,
5549 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5550 * propagate the payload and so it cannot be safely deferred. Deliver
5551 * the payload if the capability hasn't been requested.
5552 */
5553 if (!vcpu->kvm->arch.exception_payload_enabled &&
5554 ex->pending && ex->has_payload)
5555 kvm_deliver_exception_payload(vcpu, ex);
5556
5557 memset(events, 0, sizeof(*events));
5558
5559 /*
5560 * The API doesn't provide the instruction length for software
5561 * exceptions, so don't report them. As long as the guest RIP
5562 * isn't advanced, we should expect to encounter the exception
5563 * again.
5564 */
5565 if (!kvm_exception_is_soft(ex->vector)) {
5566 events->exception.injected = ex->injected;
5567 events->exception.pending = ex->pending;
5568 /*
5569 * For ABI compatibility, deliberately conflate
5570 * pending and injected exceptions when
5571 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5572 */
5573 if (!vcpu->kvm->arch.exception_payload_enabled)
5574 events->exception.injected |= ex->pending;
5575 }
5576 events->exception.nr = ex->vector;
5577 events->exception.has_error_code = ex->has_error_code;
5578 events->exception.error_code = ex->error_code;
5579 events->exception_has_payload = ex->has_payload;
5580 events->exception_payload = ex->payload;
5581
5582 events->interrupt.injected =
5583 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5584 events->interrupt.nr = vcpu->arch.interrupt.nr;
5585 events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
5586
5587 events->nmi.injected = vcpu->arch.nmi_injected;
5588 events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
5589 events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
5590
5591 /* events->sipi_vector is never valid when reporting to user space */
5592
5593 #ifdef CONFIG_KVM_SMM
5594 events->smi.smm = is_smm(vcpu);
5595 events->smi.pending = vcpu->arch.smi_pending;
5596 events->smi.smm_inside_nmi =
5597 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5598 #endif
5599 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5600
5601 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5602 | KVM_VCPUEVENT_VALID_SHADOW
5603 | KVM_VCPUEVENT_VALID_SMM);
5604 if (vcpu->kvm->arch.exception_payload_enabled)
5605 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5606 if (vcpu->kvm->arch.triple_fault_event) {
5607 events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5608 events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5609 }
5610 }
5611
kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5612 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5613 struct kvm_vcpu_events *events)
5614 {
5615 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5616 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5617 | KVM_VCPUEVENT_VALID_SHADOW
5618 | KVM_VCPUEVENT_VALID_SMM
5619 | KVM_VCPUEVENT_VALID_PAYLOAD
5620 | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5621 return -EINVAL;
5622
5623 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5624 if (!vcpu->kvm->arch.exception_payload_enabled)
5625 return -EINVAL;
5626 if (events->exception.pending)
5627 events->exception.injected = 0;
5628 else
5629 events->exception_has_payload = 0;
5630 } else {
5631 events->exception.pending = 0;
5632 events->exception_has_payload = 0;
5633 }
5634
5635 if ((events->exception.injected || events->exception.pending) &&
5636 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5637 return -EINVAL;
5638
5639 process_nmi(vcpu);
5640
5641 /*
5642 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5643 * morph the exception to a VM-Exit if appropriate. Do this only for
5644 * pending exceptions, already-injected exceptions are not subject to
5645 * intercpetion. Note, userspace that conflates pending and injected
5646 * is hosed, and will incorrectly convert an injected exception into a
5647 * pending exception, which in turn may cause a spurious VM-Exit.
5648 */
5649 vcpu->arch.exception_from_userspace = events->exception.pending;
5650
5651 vcpu->arch.exception_vmexit.pending = false;
5652
5653 vcpu->arch.exception.injected = events->exception.injected;
5654 vcpu->arch.exception.pending = events->exception.pending;
5655 vcpu->arch.exception.vector = events->exception.nr;
5656 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5657 vcpu->arch.exception.error_code = events->exception.error_code;
5658 vcpu->arch.exception.has_payload = events->exception_has_payload;
5659 vcpu->arch.exception.payload = events->exception_payload;
5660
5661 vcpu->arch.interrupt.injected = events->interrupt.injected;
5662 vcpu->arch.interrupt.nr = events->interrupt.nr;
5663 vcpu->arch.interrupt.soft = events->interrupt.soft;
5664 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5665 kvm_x86_call(set_interrupt_shadow)(vcpu,
5666 events->interrupt.shadow);
5667
5668 vcpu->arch.nmi_injected = events->nmi.injected;
5669 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
5670 vcpu->arch.nmi_pending = 0;
5671 atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
5672 if (events->nmi.pending)
5673 kvm_make_request(KVM_REQ_NMI, vcpu);
5674 }
5675 kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
5676
5677 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5678 lapic_in_kernel(vcpu))
5679 vcpu->arch.apic->sipi_vector = events->sipi_vector;
5680
5681 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5682 #ifdef CONFIG_KVM_SMM
5683 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5684 kvm_leave_nested(vcpu);
5685 kvm_smm_changed(vcpu, events->smi.smm);
5686 }
5687
5688 vcpu->arch.smi_pending = events->smi.pending;
5689
5690 if (events->smi.smm) {
5691 if (events->smi.smm_inside_nmi)
5692 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5693 else
5694 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5695 }
5696
5697 #else
5698 if (events->smi.smm || events->smi.pending ||
5699 events->smi.smm_inside_nmi)
5700 return -EINVAL;
5701 #endif
5702
5703 if (lapic_in_kernel(vcpu)) {
5704 if (events->smi.latched_init)
5705 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5706 else
5707 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5708 }
5709 }
5710
5711 if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5712 if (!vcpu->kvm->arch.triple_fault_event)
5713 return -EINVAL;
5714 if (events->triple_fault.pending)
5715 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5716 else
5717 kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5718 }
5719
5720 kvm_make_request(KVM_REQ_EVENT, vcpu);
5721
5722 return 0;
5723 }
5724
kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5725 static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5726 struct kvm_debugregs *dbgregs)
5727 {
5728 unsigned int i;
5729
5730 if (vcpu->kvm->arch.has_protected_state &&
5731 vcpu->arch.guest_state_protected)
5732 return -EINVAL;
5733
5734 memset(dbgregs, 0, sizeof(*dbgregs));
5735
5736 BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5737 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5738 dbgregs->db[i] = vcpu->arch.db[i];
5739
5740 dbgregs->dr6 = vcpu->arch.dr6;
5741 dbgregs->dr7 = vcpu->arch.dr7;
5742 return 0;
5743 }
5744
kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5745 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5746 struct kvm_debugregs *dbgregs)
5747 {
5748 unsigned int i;
5749
5750 if (vcpu->kvm->arch.has_protected_state &&
5751 vcpu->arch.guest_state_protected)
5752 return -EINVAL;
5753
5754 if (dbgregs->flags)
5755 return -EINVAL;
5756
5757 if (!kvm_dr6_valid(dbgregs->dr6))
5758 return -EINVAL;
5759 if (!kvm_dr7_valid(dbgregs->dr7))
5760 return -EINVAL;
5761
5762 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5763 vcpu->arch.db[i] = dbgregs->db[i];
5764
5765 kvm_update_dr0123(vcpu);
5766 vcpu->arch.dr6 = dbgregs->dr6;
5767 vcpu->arch.dr7 = dbgregs->dr7;
5768 kvm_update_dr7(vcpu);
5769
5770 return 0;
5771 }
5772
5773
kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu * vcpu,u8 * state,unsigned int size)5774 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5775 u8 *state, unsigned int size)
5776 {
5777 /*
5778 * Only copy state for features that are enabled for the guest. The
5779 * state itself isn't problematic, but setting bits in the header for
5780 * features that are supported in *this* host but not exposed to the
5781 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5782 * compatible host without the features that are NOT exposed to the
5783 * guest.
5784 *
5785 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5786 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5787 * supported by the host.
5788 */
5789 u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5790 XFEATURE_MASK_FPSSE;
5791
5792 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5793 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5794
5795 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5796 supported_xcr0, vcpu->arch.pkru);
5797 return 0;
5798 }
5799
kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5800 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5801 struct kvm_xsave *guest_xsave)
5802 {
5803 return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5804 sizeof(guest_xsave->region));
5805 }
5806
kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5807 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5808 struct kvm_xsave *guest_xsave)
5809 {
5810 union fpregs_state *xstate = (union fpregs_state *)guest_xsave->region;
5811
5812 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5813 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5814
5815 /*
5816 * For backwards compatibility, do not expect disabled features to be in
5817 * their initial state. XSTATE_BV[i] must still be cleared whenever
5818 * XFD[i]=1, or XRSTOR would cause a #NM.
5819 */
5820 xstate->xsave.header.xfeatures &= ~vcpu->arch.guest_fpu.fpstate->xfd;
5821
5822 return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5823 guest_xsave->region,
5824 kvm_caps.supported_xcr0,
5825 &vcpu->arch.pkru);
5826 }
5827
kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5828 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5829 struct kvm_xcrs *guest_xcrs)
5830 {
5831 if (vcpu->kvm->arch.has_protected_state &&
5832 vcpu->arch.guest_state_protected)
5833 return -EINVAL;
5834
5835 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5836 guest_xcrs->nr_xcrs = 0;
5837 return 0;
5838 }
5839
5840 guest_xcrs->nr_xcrs = 1;
5841 guest_xcrs->flags = 0;
5842 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5843 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5844 return 0;
5845 }
5846
kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5847 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5848 struct kvm_xcrs *guest_xcrs)
5849 {
5850 int i, r = 0;
5851
5852 if (vcpu->kvm->arch.has_protected_state &&
5853 vcpu->arch.guest_state_protected)
5854 return -EINVAL;
5855
5856 if (!boot_cpu_has(X86_FEATURE_XSAVE))
5857 return -EINVAL;
5858
5859 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5860 return -EINVAL;
5861
5862 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5863 /* Only support XCR0 currently */
5864 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5865 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5866 guest_xcrs->xcrs[i].value);
5867 break;
5868 }
5869 if (r)
5870 r = -EINVAL;
5871 return r;
5872 }
5873
5874 /*
5875 * kvm_set_guest_paused() indicates to the guest kernel that it has been
5876 * stopped by the hypervisor. This function will be called from the host only.
5877 * EINVAL is returned when the host attempts to set the flag for a guest that
5878 * does not support pv clocks.
5879 */
kvm_set_guest_paused(struct kvm_vcpu * vcpu)5880 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5881 {
5882 if (!vcpu->arch.pv_time.active)
5883 return -EINVAL;
5884 vcpu->arch.pvclock_set_guest_stopped_request = true;
5885 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5886 return 0;
5887 }
5888
kvm_arch_tsc_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5889 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5890 struct kvm_device_attr *attr)
5891 {
5892 int r;
5893
5894 switch (attr->attr) {
5895 case KVM_VCPU_TSC_OFFSET:
5896 r = 0;
5897 break;
5898 default:
5899 r = -ENXIO;
5900 }
5901
5902 return r;
5903 }
5904
kvm_arch_tsc_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5905 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5906 struct kvm_device_attr *attr)
5907 {
5908 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5909 int r;
5910
5911 switch (attr->attr) {
5912 case KVM_VCPU_TSC_OFFSET:
5913 r = -EFAULT;
5914 if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5915 break;
5916 r = 0;
5917 break;
5918 default:
5919 r = -ENXIO;
5920 }
5921
5922 return r;
5923 }
5924
kvm_arch_tsc_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5925 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5926 struct kvm_device_attr *attr)
5927 {
5928 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5929 struct kvm *kvm = vcpu->kvm;
5930 int r;
5931
5932 switch (attr->attr) {
5933 case KVM_VCPU_TSC_OFFSET: {
5934 u64 offset, tsc, ns;
5935 unsigned long flags;
5936 bool matched;
5937
5938 r = -EFAULT;
5939 if (get_user(offset, uaddr))
5940 break;
5941
5942 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5943
5944 matched = (vcpu->arch.virtual_tsc_khz &&
5945 kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5946 kvm->arch.last_tsc_offset == offset);
5947
5948 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5949 ns = get_kvmclock_base_ns();
5950
5951 __kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched, true);
5952 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5953
5954 r = 0;
5955 break;
5956 }
5957 default:
5958 r = -ENXIO;
5959 }
5960
5961 return r;
5962 }
5963
kvm_vcpu_ioctl_device_attr(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)5964 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5965 unsigned int ioctl,
5966 void __user *argp)
5967 {
5968 struct kvm_device_attr attr;
5969 int r;
5970
5971 if (copy_from_user(&attr, argp, sizeof(attr)))
5972 return -EFAULT;
5973
5974 if (attr.group != KVM_VCPU_TSC_CTRL)
5975 return -ENXIO;
5976
5977 switch (ioctl) {
5978 case KVM_HAS_DEVICE_ATTR:
5979 r = kvm_arch_tsc_has_attr(vcpu, &attr);
5980 break;
5981 case KVM_GET_DEVICE_ATTR:
5982 r = kvm_arch_tsc_get_attr(vcpu, &attr);
5983 break;
5984 case KVM_SET_DEVICE_ATTR:
5985 r = kvm_arch_tsc_set_attr(vcpu, &attr);
5986 break;
5987 }
5988
5989 return r;
5990 }
5991
kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu * vcpu,struct kvm_enable_cap * cap)5992 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5993 struct kvm_enable_cap *cap)
5994 {
5995 if (cap->flags)
5996 return -EINVAL;
5997
5998 switch (cap->cap) {
5999 #ifdef CONFIG_KVM_HYPERV
6000 case KVM_CAP_HYPERV_SYNIC2:
6001 if (cap->args[0])
6002 return -EINVAL;
6003 fallthrough;
6004
6005 case KVM_CAP_HYPERV_SYNIC:
6006 if (!irqchip_in_kernel(vcpu->kvm))
6007 return -EINVAL;
6008 return kvm_hv_activate_synic(vcpu, cap->cap ==
6009 KVM_CAP_HYPERV_SYNIC2);
6010 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
6011 {
6012 int r;
6013 uint16_t vmcs_version;
6014 void __user *user_ptr;
6015
6016 if (!kvm_x86_ops.nested_ops->enable_evmcs)
6017 return -ENOTTY;
6018 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
6019 if (!r) {
6020 user_ptr = (void __user *)(uintptr_t)cap->args[0];
6021 if (copy_to_user(user_ptr, &vmcs_version,
6022 sizeof(vmcs_version)))
6023 r = -EFAULT;
6024 }
6025 return r;
6026 }
6027 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
6028 if (!kvm_x86_ops.enable_l2_tlb_flush)
6029 return -ENOTTY;
6030
6031 return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
6032
6033 case KVM_CAP_HYPERV_ENFORCE_CPUID:
6034 return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
6035 #endif
6036
6037 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
6038 vcpu->arch.pv_cpuid.enforce = cap->args[0];
6039 return 0;
6040 default:
6041 return -EINVAL;
6042 }
6043 }
6044
6045 struct kvm_x86_reg_id {
6046 __u32 index;
6047 __u8 type;
6048 __u8 rsvd1;
6049 __u8 rsvd2:4;
6050 __u8 size:4;
6051 __u8 x86;
6052 };
6053
kvm_translate_kvm_reg(struct kvm_vcpu * vcpu,struct kvm_x86_reg_id * reg)6054 static int kvm_translate_kvm_reg(struct kvm_vcpu *vcpu,
6055 struct kvm_x86_reg_id *reg)
6056 {
6057 switch (reg->index) {
6058 case KVM_REG_GUEST_SSP:
6059 /*
6060 * FIXME: If host-initiated accesses are ever exempted from
6061 * ignore_msrs (in kvm_do_msr_access()), drop this manual check
6062 * and rely on KVM's standard checks to reject accesses to regs
6063 * that don't exist.
6064 */
6065 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
6066 return -EINVAL;
6067
6068 reg->type = KVM_X86_REG_TYPE_MSR;
6069 reg->index = MSR_KVM_INTERNAL_GUEST_SSP;
6070 break;
6071 default:
6072 return -EINVAL;
6073 }
6074 return 0;
6075 }
6076
kvm_get_one_msr(struct kvm_vcpu * vcpu,u32 msr,u64 __user * user_val)6077 static int kvm_get_one_msr(struct kvm_vcpu *vcpu, u32 msr, u64 __user *user_val)
6078 {
6079 u64 val;
6080
6081 if (do_get_msr(vcpu, msr, &val))
6082 return -EINVAL;
6083
6084 if (put_user(val, user_val))
6085 return -EFAULT;
6086
6087 return 0;
6088 }
6089
kvm_set_one_msr(struct kvm_vcpu * vcpu,u32 msr,u64 __user * user_val)6090 static int kvm_set_one_msr(struct kvm_vcpu *vcpu, u32 msr, u64 __user *user_val)
6091 {
6092 u64 val;
6093
6094 if (get_user(val, user_val))
6095 return -EFAULT;
6096
6097 if (do_set_msr(vcpu, msr, &val))
6098 return -EINVAL;
6099
6100 return 0;
6101 }
6102
kvm_get_set_one_reg(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)6103 static int kvm_get_set_one_reg(struct kvm_vcpu *vcpu, unsigned int ioctl,
6104 void __user *argp)
6105 {
6106 struct kvm_one_reg one_reg;
6107 struct kvm_x86_reg_id *reg;
6108 u64 __user *user_val;
6109 bool load_fpu;
6110 int r;
6111
6112 if (copy_from_user(&one_reg, argp, sizeof(one_reg)))
6113 return -EFAULT;
6114
6115 if ((one_reg.id & KVM_REG_ARCH_MASK) != KVM_REG_X86)
6116 return -EINVAL;
6117
6118 reg = (struct kvm_x86_reg_id *)&one_reg.id;
6119 if (reg->rsvd1 || reg->rsvd2)
6120 return -EINVAL;
6121
6122 if (reg->type == KVM_X86_REG_TYPE_KVM) {
6123 r = kvm_translate_kvm_reg(vcpu, reg);
6124 if (r)
6125 return r;
6126 }
6127
6128 if (reg->type != KVM_X86_REG_TYPE_MSR)
6129 return -EINVAL;
6130
6131 if ((one_reg.id & KVM_REG_SIZE_MASK) != KVM_REG_SIZE_U64)
6132 return -EINVAL;
6133
6134 guard(srcu)(&vcpu->kvm->srcu);
6135
6136 load_fpu = is_xstate_managed_msr(vcpu, reg->index);
6137 if (load_fpu)
6138 kvm_load_guest_fpu(vcpu);
6139
6140 user_val = u64_to_user_ptr(one_reg.addr);
6141 if (ioctl == KVM_GET_ONE_REG)
6142 r = kvm_get_one_msr(vcpu, reg->index, user_val);
6143 else
6144 r = kvm_set_one_msr(vcpu, reg->index, user_val);
6145
6146 if (load_fpu)
6147 kvm_put_guest_fpu(vcpu);
6148 return r;
6149 }
6150
kvm_get_reg_list(struct kvm_vcpu * vcpu,struct kvm_reg_list __user * user_list)6151 static int kvm_get_reg_list(struct kvm_vcpu *vcpu,
6152 struct kvm_reg_list __user *user_list)
6153 {
6154 u64 nr_regs = guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) ? 1 : 0;
6155 u64 user_nr_regs;
6156
6157 if (get_user(user_nr_regs, &user_list->n))
6158 return -EFAULT;
6159
6160 if (put_user(nr_regs, &user_list->n))
6161 return -EFAULT;
6162
6163 if (user_nr_regs < nr_regs)
6164 return -E2BIG;
6165
6166 if (nr_regs &&
6167 put_user(KVM_X86_REG_KVM(KVM_REG_GUEST_SSP), &user_list->reg[0]))
6168 return -EFAULT;
6169
6170 return 0;
6171 }
6172
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)6173 long kvm_arch_vcpu_ioctl(struct file *filp,
6174 unsigned int ioctl, unsigned long arg)
6175 {
6176 struct kvm_vcpu *vcpu = filp->private_data;
6177 void __user *argp = (void __user *)arg;
6178 int r;
6179 union {
6180 struct kvm_sregs2 *sregs2;
6181 struct kvm_lapic_state *lapic;
6182 struct kvm_xsave *xsave;
6183 struct kvm_xcrs *xcrs;
6184 void *buffer;
6185 } u;
6186
6187 vcpu_load(vcpu);
6188
6189 u.buffer = NULL;
6190 switch (ioctl) {
6191 case KVM_GET_LAPIC: {
6192 r = -EINVAL;
6193 if (!lapic_in_kernel(vcpu))
6194 goto out;
6195 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
6196
6197 r = -ENOMEM;
6198 if (!u.lapic)
6199 goto out;
6200 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
6201 if (r)
6202 goto out;
6203 r = -EFAULT;
6204 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
6205 goto out;
6206 r = 0;
6207 break;
6208 }
6209 case KVM_SET_LAPIC: {
6210 r = -EINVAL;
6211 if (!lapic_in_kernel(vcpu))
6212 goto out;
6213 u.lapic = memdup_user(argp, sizeof(*u.lapic));
6214 if (IS_ERR(u.lapic)) {
6215 r = PTR_ERR(u.lapic);
6216 goto out_nofree;
6217 }
6218
6219 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
6220 break;
6221 }
6222 case KVM_INTERRUPT: {
6223 struct kvm_interrupt irq;
6224
6225 r = -EFAULT;
6226 if (copy_from_user(&irq, argp, sizeof(irq)))
6227 goto out;
6228 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
6229 break;
6230 }
6231 case KVM_NMI: {
6232 r = kvm_vcpu_ioctl_nmi(vcpu);
6233 break;
6234 }
6235 case KVM_SMI: {
6236 r = kvm_inject_smi(vcpu);
6237 break;
6238 }
6239 case KVM_SET_CPUID: {
6240 struct kvm_cpuid __user *cpuid_arg = argp;
6241 struct kvm_cpuid cpuid;
6242
6243 r = -EFAULT;
6244 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6245 goto out;
6246 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
6247 break;
6248 }
6249 case KVM_SET_CPUID2: {
6250 struct kvm_cpuid2 __user *cpuid_arg = argp;
6251 struct kvm_cpuid2 cpuid;
6252
6253 r = -EFAULT;
6254 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6255 goto out;
6256 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
6257 cpuid_arg->entries);
6258 break;
6259 }
6260 case KVM_GET_CPUID2: {
6261 struct kvm_cpuid2 __user *cpuid_arg = argp;
6262 struct kvm_cpuid2 cpuid;
6263
6264 r = -EFAULT;
6265 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6266 goto out;
6267 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
6268 cpuid_arg->entries);
6269 if (r)
6270 goto out;
6271 r = -EFAULT;
6272 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
6273 goto out;
6274 r = 0;
6275 break;
6276 }
6277 case KVM_GET_MSRS: {
6278 int idx = srcu_read_lock(&vcpu->kvm->srcu);
6279 r = msr_io(vcpu, argp, do_get_msr, 1);
6280 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6281 break;
6282 }
6283 case KVM_SET_MSRS: {
6284 int idx = srcu_read_lock(&vcpu->kvm->srcu);
6285 r = msr_io(vcpu, argp, do_set_msr, 0);
6286 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6287 break;
6288 }
6289 case KVM_GET_ONE_REG:
6290 case KVM_SET_ONE_REG:
6291 r = kvm_get_set_one_reg(vcpu, ioctl, argp);
6292 break;
6293 case KVM_GET_REG_LIST:
6294 r = kvm_get_reg_list(vcpu, argp);
6295 break;
6296 case KVM_TPR_ACCESS_REPORTING: {
6297 struct kvm_tpr_access_ctl tac;
6298
6299 r = -EFAULT;
6300 if (copy_from_user(&tac, argp, sizeof(tac)))
6301 goto out;
6302 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
6303 if (r)
6304 goto out;
6305 r = -EFAULT;
6306 if (copy_to_user(argp, &tac, sizeof(tac)))
6307 goto out;
6308 r = 0;
6309 break;
6310 };
6311 case KVM_SET_VAPIC_ADDR: {
6312 struct kvm_vapic_addr va;
6313 int idx;
6314
6315 r = -EINVAL;
6316 if (!lapic_in_kernel(vcpu))
6317 goto out;
6318 r = -EFAULT;
6319 if (copy_from_user(&va, argp, sizeof(va)))
6320 goto out;
6321 idx = srcu_read_lock(&vcpu->kvm->srcu);
6322 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
6323 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6324 break;
6325 }
6326 case KVM_X86_SETUP_MCE: {
6327 u64 mcg_cap;
6328
6329 r = -EFAULT;
6330 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
6331 goto out;
6332 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6333 break;
6334 }
6335 case KVM_X86_SET_MCE: {
6336 struct kvm_x86_mce mce;
6337
6338 r = -EFAULT;
6339 if (copy_from_user(&mce, argp, sizeof(mce)))
6340 goto out;
6341 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6342 break;
6343 }
6344 case KVM_GET_VCPU_EVENTS: {
6345 struct kvm_vcpu_events events;
6346
6347 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6348
6349 r = -EFAULT;
6350 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6351 break;
6352 r = 0;
6353 break;
6354 }
6355 case KVM_SET_VCPU_EVENTS: {
6356 struct kvm_vcpu_events events;
6357
6358 r = -EFAULT;
6359 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6360 break;
6361
6362 kvm_vcpu_srcu_read_lock(vcpu);
6363 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
6364 kvm_vcpu_srcu_read_unlock(vcpu);
6365 break;
6366 }
6367 case KVM_GET_DEBUGREGS: {
6368 struct kvm_debugregs dbgregs;
6369
6370 r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6371 if (r < 0)
6372 break;
6373
6374 r = -EFAULT;
6375 if (copy_to_user(argp, &dbgregs,
6376 sizeof(struct kvm_debugregs)))
6377 break;
6378 r = 0;
6379 break;
6380 }
6381 case KVM_SET_DEBUGREGS: {
6382 struct kvm_debugregs dbgregs;
6383
6384 r = -EFAULT;
6385 if (copy_from_user(&dbgregs, argp,
6386 sizeof(struct kvm_debugregs)))
6387 break;
6388
6389 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6390 break;
6391 }
6392 case KVM_GET_XSAVE: {
6393 r = -EINVAL;
6394 if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6395 break;
6396
6397 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
6398 r = -ENOMEM;
6399 if (!u.xsave)
6400 break;
6401
6402 r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6403 if (r < 0)
6404 break;
6405
6406 r = -EFAULT;
6407 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
6408 break;
6409 r = 0;
6410 break;
6411 }
6412 case KVM_SET_XSAVE: {
6413 int size = vcpu->arch.guest_fpu.uabi_size;
6414
6415 u.xsave = memdup_user(argp, size);
6416 if (IS_ERR(u.xsave)) {
6417 r = PTR_ERR(u.xsave);
6418 goto out_nofree;
6419 }
6420
6421 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
6422 break;
6423 }
6424
6425 case KVM_GET_XSAVE2: {
6426 int size = vcpu->arch.guest_fpu.uabi_size;
6427
6428 u.xsave = kzalloc(size, GFP_KERNEL);
6429 r = -ENOMEM;
6430 if (!u.xsave)
6431 break;
6432
6433 r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6434 if (r < 0)
6435 break;
6436
6437 r = -EFAULT;
6438 if (copy_to_user(argp, u.xsave, size))
6439 break;
6440
6441 r = 0;
6442 break;
6443 }
6444
6445 case KVM_GET_XCRS: {
6446 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
6447 r = -ENOMEM;
6448 if (!u.xcrs)
6449 break;
6450
6451 r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6452 if (r < 0)
6453 break;
6454
6455 r = -EFAULT;
6456 if (copy_to_user(argp, u.xcrs,
6457 sizeof(struct kvm_xcrs)))
6458 break;
6459 r = 0;
6460 break;
6461 }
6462 case KVM_SET_XCRS: {
6463 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
6464 if (IS_ERR(u.xcrs)) {
6465 r = PTR_ERR(u.xcrs);
6466 goto out_nofree;
6467 }
6468
6469 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
6470 break;
6471 }
6472 case KVM_SET_TSC_KHZ: {
6473 u32 user_tsc_khz;
6474
6475 r = -EINVAL;
6476
6477 if (vcpu->arch.guest_tsc_protected)
6478 goto out;
6479
6480 user_tsc_khz = (u32)arg;
6481
6482 if (kvm_caps.has_tsc_control &&
6483 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6484 goto out;
6485
6486 if (user_tsc_khz == 0)
6487 user_tsc_khz = tsc_khz;
6488
6489 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6490 r = 0;
6491
6492 goto out;
6493 }
6494 case KVM_GET_TSC_KHZ: {
6495 r = vcpu->arch.virtual_tsc_khz;
6496 goto out;
6497 }
6498 case KVM_KVMCLOCK_CTRL: {
6499 r = kvm_set_guest_paused(vcpu);
6500 goto out;
6501 }
6502 case KVM_ENABLE_CAP: {
6503 struct kvm_enable_cap cap;
6504
6505 r = -EFAULT;
6506 if (copy_from_user(&cap, argp, sizeof(cap)))
6507 goto out;
6508 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6509 break;
6510 }
6511 case KVM_GET_NESTED_STATE: {
6512 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6513 u32 user_data_size;
6514
6515 r = -EINVAL;
6516 if (!kvm_x86_ops.nested_ops->get_state)
6517 break;
6518
6519 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
6520 r = -EFAULT;
6521 if (get_user(user_data_size, &user_kvm_nested_state->size))
6522 break;
6523
6524 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6525 user_data_size);
6526 if (r < 0)
6527 break;
6528
6529 if (r > user_data_size) {
6530 if (put_user(r, &user_kvm_nested_state->size))
6531 r = -EFAULT;
6532 else
6533 r = -E2BIG;
6534 break;
6535 }
6536
6537 r = 0;
6538 break;
6539 }
6540 case KVM_SET_NESTED_STATE: {
6541 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6542 struct kvm_nested_state kvm_state;
6543 int idx;
6544
6545 r = -EINVAL;
6546 if (!kvm_x86_ops.nested_ops->set_state)
6547 break;
6548
6549 r = -EFAULT;
6550 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
6551 break;
6552
6553 r = -EINVAL;
6554 if (kvm_state.size < sizeof(kvm_state))
6555 break;
6556
6557 if (kvm_state.flags &
6558 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
6559 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6560 | KVM_STATE_NESTED_GIF_SET))
6561 break;
6562
6563 /* nested_run_pending implies guest_mode. */
6564 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6565 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
6566 break;
6567
6568 idx = srcu_read_lock(&vcpu->kvm->srcu);
6569 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
6570 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6571 break;
6572 }
6573 #ifdef CONFIG_KVM_HYPERV
6574 case KVM_GET_SUPPORTED_HV_CPUID:
6575 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
6576 break;
6577 #endif
6578 #ifdef CONFIG_KVM_XEN
6579 case KVM_XEN_VCPU_GET_ATTR: {
6580 struct kvm_xen_vcpu_attr xva;
6581
6582 r = -EFAULT;
6583 if (copy_from_user(&xva, argp, sizeof(xva)))
6584 goto out;
6585 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6586 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6587 r = -EFAULT;
6588 break;
6589 }
6590 case KVM_XEN_VCPU_SET_ATTR: {
6591 struct kvm_xen_vcpu_attr xva;
6592
6593 r = -EFAULT;
6594 if (copy_from_user(&xva, argp, sizeof(xva)))
6595 goto out;
6596 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6597 break;
6598 }
6599 #endif
6600 case KVM_GET_SREGS2: {
6601 r = -EINVAL;
6602 if (vcpu->kvm->arch.has_protected_state &&
6603 vcpu->arch.guest_state_protected)
6604 goto out;
6605
6606 u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
6607 r = -ENOMEM;
6608 if (!u.sregs2)
6609 goto out;
6610 __get_sregs2(vcpu, u.sregs2);
6611 r = -EFAULT;
6612 if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6613 goto out;
6614 r = 0;
6615 break;
6616 }
6617 case KVM_SET_SREGS2: {
6618 r = -EINVAL;
6619 if (vcpu->kvm->arch.has_protected_state &&
6620 vcpu->arch.guest_state_protected)
6621 goto out;
6622
6623 u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6624 if (IS_ERR(u.sregs2)) {
6625 r = PTR_ERR(u.sregs2);
6626 u.sregs2 = NULL;
6627 goto out;
6628 }
6629 r = __set_sregs2(vcpu, u.sregs2);
6630 break;
6631 }
6632 case KVM_HAS_DEVICE_ATTR:
6633 case KVM_GET_DEVICE_ATTR:
6634 case KVM_SET_DEVICE_ATTR:
6635 r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6636 break;
6637 case KVM_MEMORY_ENCRYPT_OP:
6638 r = -ENOTTY;
6639 if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
6640 goto out;
6641 r = kvm_x86_ops.vcpu_mem_enc_ioctl(vcpu, argp);
6642 break;
6643 default:
6644 r = -EINVAL;
6645 }
6646 out:
6647 kfree(u.buffer);
6648 out_nofree:
6649 vcpu_put(vcpu);
6650 return r;
6651 }
6652
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)6653 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6654 {
6655 return VM_FAULT_SIGBUS;
6656 }
6657
kvm_vm_ioctl_set_tss_addr(struct kvm * kvm,unsigned long addr)6658 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6659 {
6660 int ret;
6661
6662 if (addr > (unsigned int)(-3 * PAGE_SIZE))
6663 return -EINVAL;
6664 ret = kvm_x86_call(set_tss_addr)(kvm, addr);
6665 return ret;
6666 }
6667
kvm_vm_ioctl_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)6668 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6669 u64 ident_addr)
6670 {
6671 return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
6672 }
6673
kvm_vm_ioctl_set_nr_mmu_pages(struct kvm * kvm,unsigned long kvm_nr_mmu_pages)6674 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6675 unsigned long kvm_nr_mmu_pages)
6676 {
6677 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6678 return -EINVAL;
6679
6680 mutex_lock(&kvm->slots_lock);
6681
6682 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6683 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6684
6685 mutex_unlock(&kvm->slots_lock);
6686 return 0;
6687 }
6688
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)6689 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6690 {
6691
6692 /*
6693 * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
6694 * before reporting dirty_bitmap to userspace. KVM flushes the buffers
6695 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6696 * VM-Exit.
6697 */
6698 struct kvm_vcpu *vcpu;
6699 unsigned long i;
6700
6701 if (!kvm->arch.cpu_dirty_log_size)
6702 return;
6703
6704 kvm_for_each_vcpu(i, vcpu, kvm)
6705 kvm_vcpu_kick(vcpu);
6706 }
6707
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)6708 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6709 struct kvm_enable_cap *cap)
6710 {
6711 int r;
6712
6713 if (cap->flags)
6714 return -EINVAL;
6715
6716 switch (cap->cap) {
6717 case KVM_CAP_DISABLE_QUIRKS2:
6718 r = -EINVAL;
6719 if (cap->args[0] & ~kvm_caps.supported_quirks)
6720 break;
6721 fallthrough;
6722 case KVM_CAP_DISABLE_QUIRKS:
6723 kvm->arch.disabled_quirks |= cap->args[0] & kvm_caps.supported_quirks;
6724 r = 0;
6725 break;
6726 case KVM_CAP_SPLIT_IRQCHIP: {
6727 mutex_lock(&kvm->lock);
6728 r = -EINVAL;
6729 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6730 goto split_irqchip_unlock;
6731 r = -EEXIST;
6732 if (irqchip_in_kernel(kvm))
6733 goto split_irqchip_unlock;
6734 if (kvm->created_vcpus)
6735 goto split_irqchip_unlock;
6736 /* Pairs with irqchip_in_kernel. */
6737 smp_wmb();
6738 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6739 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6740 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6741 r = 0;
6742 split_irqchip_unlock:
6743 mutex_unlock(&kvm->lock);
6744 break;
6745 }
6746 case KVM_CAP_X2APIC_API:
6747 r = -EINVAL;
6748 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6749 break;
6750
6751 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6752 kvm->arch.x2apic_format = true;
6753 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6754 kvm->arch.x2apic_broadcast_quirk_disabled = true;
6755
6756 r = 0;
6757 break;
6758 case KVM_CAP_X86_DISABLE_EXITS:
6759 r = -EINVAL;
6760 if (cap->args[0] & ~kvm_get_allowed_disable_exits())
6761 break;
6762
6763 mutex_lock(&kvm->lock);
6764 if (kvm->created_vcpus)
6765 goto disable_exits_unlock;
6766
6767 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6768 "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6769
6770 if (!mitigate_smt_rsb && boot_cpu_has_bug(X86_BUG_SMT_RSB) &&
6771 cpu_smt_possible() &&
6772 (cap->args[0] & ~(KVM_X86_DISABLE_EXITS_PAUSE |
6773 KVM_X86_DISABLE_EXITS_APERFMPERF)))
6774 pr_warn_once(SMT_RSB_MSG);
6775
6776 kvm_disable_exits(kvm, cap->args[0]);
6777 r = 0;
6778 disable_exits_unlock:
6779 mutex_unlock(&kvm->lock);
6780 break;
6781 case KVM_CAP_MSR_PLATFORM_INFO:
6782 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6783 r = 0;
6784 break;
6785 case KVM_CAP_EXCEPTION_PAYLOAD:
6786 kvm->arch.exception_payload_enabled = cap->args[0];
6787 r = 0;
6788 break;
6789 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6790 kvm->arch.triple_fault_event = cap->args[0];
6791 r = 0;
6792 break;
6793 case KVM_CAP_X86_USER_SPACE_MSR:
6794 r = -EINVAL;
6795 if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
6796 break;
6797 kvm->arch.user_space_msr_mask = cap->args[0];
6798 r = 0;
6799 break;
6800 case KVM_CAP_X86_BUS_LOCK_EXIT:
6801 r = -EINVAL;
6802 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6803 break;
6804
6805 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6806 (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6807 break;
6808
6809 if (kvm_caps.has_bus_lock_exit &&
6810 cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6811 kvm->arch.bus_lock_detection_enabled = true;
6812 r = 0;
6813 break;
6814 #ifdef CONFIG_X86_SGX_KVM
6815 case KVM_CAP_SGX_ATTRIBUTE: {
6816 unsigned long allowed_attributes = 0;
6817
6818 r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6819 if (r)
6820 break;
6821
6822 /* KVM only supports the PROVISIONKEY privileged attribute. */
6823 if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6824 !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6825 kvm->arch.sgx_provisioning_allowed = true;
6826 else
6827 r = -EINVAL;
6828 break;
6829 }
6830 #endif
6831 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6832 r = -EINVAL;
6833 if (!kvm_x86_ops.vm_copy_enc_context_from)
6834 break;
6835
6836 r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
6837 break;
6838 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6839 r = -EINVAL;
6840 if (!kvm_x86_ops.vm_move_enc_context_from)
6841 break;
6842
6843 r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
6844 break;
6845 case KVM_CAP_EXIT_HYPERCALL:
6846 if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6847 r = -EINVAL;
6848 break;
6849 }
6850 kvm->arch.hypercall_exit_enabled = cap->args[0];
6851 r = 0;
6852 break;
6853 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6854 r = -EINVAL;
6855 if (cap->args[0] & ~1)
6856 break;
6857 kvm->arch.exit_on_emulation_error = cap->args[0];
6858 r = 0;
6859 break;
6860 case KVM_CAP_PMU_CAPABILITY:
6861 r = -EINVAL;
6862 if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6863 break;
6864
6865 mutex_lock(&kvm->lock);
6866 if (!kvm->created_vcpus) {
6867 kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6868 r = 0;
6869 }
6870 mutex_unlock(&kvm->lock);
6871 break;
6872 case KVM_CAP_MAX_VCPU_ID:
6873 r = -EINVAL;
6874 if (cap->args[0] > KVM_MAX_VCPU_IDS)
6875 break;
6876
6877 mutex_lock(&kvm->lock);
6878 if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
6879 ;
6880 } else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6881 r = 0;
6882 } else if (!kvm->arch.max_vcpu_ids) {
6883 kvm->arch.max_vcpu_ids = cap->args[0];
6884 r = 0;
6885 }
6886 mutex_unlock(&kvm->lock);
6887 break;
6888 case KVM_CAP_X86_NOTIFY_VMEXIT:
6889 r = -EINVAL;
6890 if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6891 break;
6892 if (!kvm_caps.has_notify_vmexit)
6893 break;
6894 if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6895 break;
6896 mutex_lock(&kvm->lock);
6897 if (!kvm->created_vcpus) {
6898 kvm->arch.notify_window = cap->args[0] >> 32;
6899 kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6900 r = 0;
6901 }
6902 mutex_unlock(&kvm->lock);
6903 break;
6904 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6905 r = -EINVAL;
6906
6907 /*
6908 * Since the risk of disabling NX hugepages is a guest crashing
6909 * the system, ensure the userspace process has permission to
6910 * reboot the system.
6911 *
6912 * Note that unlike the reboot() syscall, the process must have
6913 * this capability in the root namespace because exposing
6914 * /dev/kvm into a container does not limit the scope of the
6915 * iTLB multihit bug to that container. In other words,
6916 * this must use capable(), not ns_capable().
6917 */
6918 if (!capable(CAP_SYS_BOOT)) {
6919 r = -EPERM;
6920 break;
6921 }
6922
6923 if (cap->args[0])
6924 break;
6925
6926 mutex_lock(&kvm->lock);
6927 if (!kvm->created_vcpus) {
6928 kvm->arch.disable_nx_huge_pages = true;
6929 r = 0;
6930 }
6931 mutex_unlock(&kvm->lock);
6932 break;
6933 case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
6934 u64 bus_cycle_ns = cap->args[0];
6935 u64 unused;
6936
6937 /*
6938 * Guard against overflow in tmict_to_ns(). 128 is the highest
6939 * divide value that can be programmed in APIC_TDCR.
6940 */
6941 r = -EINVAL;
6942 if (!bus_cycle_ns ||
6943 check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
6944 break;
6945
6946 r = 0;
6947 mutex_lock(&kvm->lock);
6948 if (!irqchip_in_kernel(kvm))
6949 r = -ENXIO;
6950 else if (kvm->created_vcpus)
6951 r = -EINVAL;
6952 else
6953 kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
6954 mutex_unlock(&kvm->lock);
6955 break;
6956 }
6957 default:
6958 r = -EINVAL;
6959 break;
6960 }
6961 return r;
6962 }
6963
kvm_alloc_msr_filter(bool default_allow)6964 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6965 {
6966 struct kvm_x86_msr_filter *msr_filter;
6967
6968 msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6969 if (!msr_filter)
6970 return NULL;
6971
6972 msr_filter->default_allow = default_allow;
6973 return msr_filter;
6974 }
6975
kvm_free_msr_filter(struct kvm_x86_msr_filter * msr_filter)6976 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
6977 {
6978 u32 i;
6979
6980 if (!msr_filter)
6981 return;
6982
6983 for (i = 0; i < msr_filter->count; i++)
6984 kfree(msr_filter->ranges[i].bitmap);
6985
6986 kfree(msr_filter);
6987 }
6988
kvm_add_msr_filter(struct kvm_x86_msr_filter * msr_filter,struct kvm_msr_filter_range * user_range)6989 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6990 struct kvm_msr_filter_range *user_range)
6991 {
6992 unsigned long *bitmap;
6993 size_t bitmap_size;
6994
6995 if (!user_range->nmsrs)
6996 return 0;
6997
6998 if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
6999 return -EINVAL;
7000
7001 if (!user_range->flags)
7002 return -EINVAL;
7003
7004 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
7005 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
7006 return -EINVAL;
7007
7008 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
7009 if (IS_ERR(bitmap))
7010 return PTR_ERR(bitmap);
7011
7012 msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
7013 .flags = user_range->flags,
7014 .base = user_range->base,
7015 .nmsrs = user_range->nmsrs,
7016 .bitmap = bitmap,
7017 };
7018
7019 msr_filter->count++;
7020 return 0;
7021 }
7022
kvm_vm_ioctl_set_msr_filter(struct kvm * kvm,struct kvm_msr_filter * filter)7023 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
7024 struct kvm_msr_filter *filter)
7025 {
7026 struct kvm_x86_msr_filter *new_filter, *old_filter;
7027 bool default_allow;
7028 bool empty = true;
7029 int r;
7030 u32 i;
7031
7032 if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
7033 return -EINVAL;
7034
7035 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
7036 empty &= !filter->ranges[i].nmsrs;
7037
7038 default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
7039 if (empty && !default_allow)
7040 return -EINVAL;
7041
7042 new_filter = kvm_alloc_msr_filter(default_allow);
7043 if (!new_filter)
7044 return -ENOMEM;
7045
7046 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
7047 r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
7048 if (r) {
7049 kvm_free_msr_filter(new_filter);
7050 return r;
7051 }
7052 }
7053
7054 mutex_lock(&kvm->lock);
7055 old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
7056 mutex_is_locked(&kvm->lock));
7057 mutex_unlock(&kvm->lock);
7058 synchronize_srcu(&kvm->srcu);
7059
7060 kvm_free_msr_filter(old_filter);
7061
7062 /*
7063 * Recalc MSR intercepts as userspace may want to intercept accesses to
7064 * MSRs that KVM would otherwise pass through to the guest.
7065 */
7066 kvm_make_all_cpus_request(kvm, KVM_REQ_RECALC_INTERCEPTS);
7067
7068 return 0;
7069 }
7070
7071 #ifdef CONFIG_KVM_COMPAT
7072 /* for KVM_X86_SET_MSR_FILTER */
7073 struct kvm_msr_filter_range_compat {
7074 __u32 flags;
7075 __u32 nmsrs;
7076 __u32 base;
7077 __u32 bitmap;
7078 };
7079
7080 struct kvm_msr_filter_compat {
7081 __u32 flags;
7082 struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
7083 };
7084
7085 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
7086
kvm_arch_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7087 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
7088 unsigned long arg)
7089 {
7090 void __user *argp = (void __user *)arg;
7091 struct kvm *kvm = filp->private_data;
7092 long r = -ENOTTY;
7093
7094 switch (ioctl) {
7095 case KVM_X86_SET_MSR_FILTER_COMPAT: {
7096 struct kvm_msr_filter __user *user_msr_filter = argp;
7097 struct kvm_msr_filter_compat filter_compat;
7098 struct kvm_msr_filter filter;
7099 int i;
7100
7101 if (copy_from_user(&filter_compat, user_msr_filter,
7102 sizeof(filter_compat)))
7103 return -EFAULT;
7104
7105 filter.flags = filter_compat.flags;
7106 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
7107 struct kvm_msr_filter_range_compat *cr;
7108
7109 cr = &filter_compat.ranges[i];
7110 filter.ranges[i] = (struct kvm_msr_filter_range) {
7111 .flags = cr->flags,
7112 .nmsrs = cr->nmsrs,
7113 .base = cr->base,
7114 .bitmap = (__u8 *)(ulong)cr->bitmap,
7115 };
7116 }
7117
7118 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7119 break;
7120 }
7121 }
7122
7123 return r;
7124 }
7125 #endif
7126
7127 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_arch_suspend_notifier(struct kvm * kvm)7128 static int kvm_arch_suspend_notifier(struct kvm *kvm)
7129 {
7130 struct kvm_vcpu *vcpu;
7131 unsigned long i;
7132
7133 /*
7134 * Ignore the return, marking the guest paused only "fails" if the vCPU
7135 * isn't using kvmclock; continuing on is correct and desirable.
7136 */
7137 kvm_for_each_vcpu(i, vcpu, kvm)
7138 (void)kvm_set_guest_paused(vcpu);
7139
7140 return NOTIFY_DONE;
7141 }
7142
kvm_arch_pm_notifier(struct kvm * kvm,unsigned long state)7143 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
7144 {
7145 switch (state) {
7146 case PM_HIBERNATION_PREPARE:
7147 case PM_SUSPEND_PREPARE:
7148 return kvm_arch_suspend_notifier(kvm);
7149 }
7150
7151 return NOTIFY_DONE;
7152 }
7153 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
7154
kvm_vm_ioctl_get_clock(struct kvm * kvm,void __user * argp)7155 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
7156 {
7157 struct kvm_clock_data data = { 0 };
7158
7159 get_kvmclock(kvm, &data);
7160 if (copy_to_user(argp, &data, sizeof(data)))
7161 return -EFAULT;
7162
7163 return 0;
7164 }
7165
kvm_vm_ioctl_set_clock(struct kvm * kvm,void __user * argp)7166 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
7167 {
7168 struct kvm_arch *ka = &kvm->arch;
7169 struct kvm_clock_data data;
7170 u64 now_raw_ns;
7171
7172 if (copy_from_user(&data, argp, sizeof(data)))
7173 return -EFAULT;
7174
7175 /*
7176 * Only KVM_CLOCK_REALTIME is used, but allow passing the
7177 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
7178 */
7179 if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
7180 return -EINVAL;
7181
7182 kvm_hv_request_tsc_page_update(kvm);
7183 kvm_start_pvclock_update(kvm);
7184 pvclock_update_vm_gtod_copy(kvm);
7185
7186 /*
7187 * This pairs with kvm_guest_time_update(): when masterclock is
7188 * in use, we use master_kernel_ns + kvmclock_offset to set
7189 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
7190 * is slightly ahead) here we risk going negative on unsigned
7191 * 'system_time' when 'data.clock' is very small.
7192 */
7193 if (data.flags & KVM_CLOCK_REALTIME) {
7194 u64 now_real_ns = ktime_get_real_ns();
7195
7196 /*
7197 * Avoid stepping the kvmclock backwards.
7198 */
7199 if (now_real_ns > data.realtime)
7200 data.clock += now_real_ns - data.realtime;
7201 }
7202
7203 if (ka->use_master_clock)
7204 now_raw_ns = ka->master_kernel_ns;
7205 else
7206 now_raw_ns = get_kvmclock_base_ns();
7207 ka->kvmclock_offset = data.clock - now_raw_ns;
7208 kvm_end_pvclock_update(kvm);
7209 return 0;
7210 }
7211
kvm_arch_vcpu_unlocked_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7212 long kvm_arch_vcpu_unlocked_ioctl(struct file *filp, unsigned int ioctl,
7213 unsigned long arg)
7214 {
7215 struct kvm_vcpu *vcpu = filp->private_data;
7216 void __user *argp = (void __user *)arg;
7217
7218 if (ioctl == KVM_MEMORY_ENCRYPT_OP &&
7219 kvm_x86_ops.vcpu_mem_enc_unlocked_ioctl)
7220 return kvm_x86_call(vcpu_mem_enc_unlocked_ioctl)(vcpu, argp);
7221
7222 return -ENOIOCTLCMD;
7223 }
7224
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7225 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
7226 {
7227 struct kvm *kvm = filp->private_data;
7228 void __user *argp = (void __user *)arg;
7229 int r = -ENOTTY;
7230
7231 #ifdef CONFIG_KVM_IOAPIC
7232 /*
7233 * This union makes it completely explicit to gcc-3.x
7234 * that these three variables' stack usage should be
7235 * combined, not added together.
7236 */
7237 union {
7238 struct kvm_pit_state ps;
7239 struct kvm_pit_state2 ps2;
7240 struct kvm_pit_config pit_config;
7241 } u;
7242 #endif
7243
7244 switch (ioctl) {
7245 case KVM_SET_TSS_ADDR:
7246 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
7247 break;
7248 case KVM_SET_IDENTITY_MAP_ADDR: {
7249 u64 ident_addr;
7250
7251 mutex_lock(&kvm->lock);
7252 r = -EINVAL;
7253 if (kvm->created_vcpus)
7254 goto set_identity_unlock;
7255 r = -EFAULT;
7256 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
7257 goto set_identity_unlock;
7258 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
7259 set_identity_unlock:
7260 mutex_unlock(&kvm->lock);
7261 break;
7262 }
7263 case KVM_SET_NR_MMU_PAGES:
7264 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
7265 break;
7266 #ifdef CONFIG_KVM_IOAPIC
7267 case KVM_CREATE_IRQCHIP: {
7268 mutex_lock(&kvm->lock);
7269
7270 r = -EEXIST;
7271 if (irqchip_in_kernel(kvm))
7272 goto create_irqchip_unlock;
7273
7274 /*
7275 * Disallow an in-kernel I/O APIC if the VM has protected EOIs,
7276 * i.e. if KVM can't intercept EOIs and thus can't properly
7277 * emulate level-triggered interrupts.
7278 */
7279 r = -ENOTTY;
7280 if (kvm->arch.has_protected_eoi)
7281 goto create_irqchip_unlock;
7282
7283 r = -EINVAL;
7284 if (kvm->created_vcpus)
7285 goto create_irqchip_unlock;
7286
7287 r = kvm_pic_init(kvm);
7288 if (r)
7289 goto create_irqchip_unlock;
7290
7291 r = kvm_ioapic_init(kvm);
7292 if (r) {
7293 kvm_pic_destroy(kvm);
7294 goto create_irqchip_unlock;
7295 }
7296
7297 r = kvm_setup_default_ioapic_and_pic_routing(kvm);
7298 if (r) {
7299 kvm_ioapic_destroy(kvm);
7300 kvm_pic_destroy(kvm);
7301 goto create_irqchip_unlock;
7302 }
7303 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
7304 smp_wmb();
7305 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
7306 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
7307 create_irqchip_unlock:
7308 mutex_unlock(&kvm->lock);
7309 break;
7310 }
7311 case KVM_CREATE_PIT:
7312 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7313 goto create_pit;
7314 case KVM_CREATE_PIT2:
7315 r = -EFAULT;
7316 if (copy_from_user(&u.pit_config, argp,
7317 sizeof(struct kvm_pit_config)))
7318 goto out;
7319 create_pit:
7320 mutex_lock(&kvm->lock);
7321 r = -EEXIST;
7322 if (kvm->arch.vpit)
7323 goto create_pit_unlock;
7324 r = -ENOENT;
7325 if (!pic_in_kernel(kvm))
7326 goto create_pit_unlock;
7327 r = -ENOMEM;
7328 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7329 if (kvm->arch.vpit)
7330 r = 0;
7331 create_pit_unlock:
7332 mutex_unlock(&kvm->lock);
7333 break;
7334 case KVM_GET_IRQCHIP: {
7335 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7336 struct kvm_irqchip *chip;
7337
7338 chip = memdup_user(argp, sizeof(*chip));
7339 if (IS_ERR(chip)) {
7340 r = PTR_ERR(chip);
7341 goto out;
7342 }
7343
7344 r = -ENXIO;
7345 if (!irqchip_full(kvm))
7346 goto get_irqchip_out;
7347 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
7348 if (r)
7349 goto get_irqchip_out;
7350 r = -EFAULT;
7351 if (copy_to_user(argp, chip, sizeof(*chip)))
7352 goto get_irqchip_out;
7353 r = 0;
7354 get_irqchip_out:
7355 kfree(chip);
7356 break;
7357 }
7358 case KVM_SET_IRQCHIP: {
7359 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7360 struct kvm_irqchip *chip;
7361
7362 chip = memdup_user(argp, sizeof(*chip));
7363 if (IS_ERR(chip)) {
7364 r = PTR_ERR(chip);
7365 goto out;
7366 }
7367
7368 r = -ENXIO;
7369 if (!irqchip_full(kvm))
7370 goto set_irqchip_out;
7371 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
7372 set_irqchip_out:
7373 kfree(chip);
7374 break;
7375 }
7376 case KVM_GET_PIT: {
7377 r = -EFAULT;
7378 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
7379 goto out;
7380 r = -ENXIO;
7381 if (!kvm->arch.vpit)
7382 goto out;
7383 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
7384 if (r)
7385 goto out;
7386 r = -EFAULT;
7387 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
7388 goto out;
7389 r = 0;
7390 break;
7391 }
7392 case KVM_SET_PIT: {
7393 r = -EFAULT;
7394 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
7395 goto out;
7396 mutex_lock(&kvm->lock);
7397 r = -ENXIO;
7398 if (!kvm->arch.vpit)
7399 goto set_pit_out;
7400 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7401 set_pit_out:
7402 mutex_unlock(&kvm->lock);
7403 break;
7404 }
7405 case KVM_GET_PIT2: {
7406 r = -ENXIO;
7407 if (!kvm->arch.vpit)
7408 goto out;
7409 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7410 if (r)
7411 goto out;
7412 r = -EFAULT;
7413 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7414 goto out;
7415 r = 0;
7416 break;
7417 }
7418 case KVM_SET_PIT2: {
7419 r = -EFAULT;
7420 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7421 goto out;
7422 mutex_lock(&kvm->lock);
7423 r = -ENXIO;
7424 if (!kvm->arch.vpit)
7425 goto set_pit2_out;
7426 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7427 set_pit2_out:
7428 mutex_unlock(&kvm->lock);
7429 break;
7430 }
7431 case KVM_REINJECT_CONTROL: {
7432 struct kvm_reinject_control control;
7433 r = -EFAULT;
7434 if (copy_from_user(&control, argp, sizeof(control)))
7435 goto out;
7436 r = -ENXIO;
7437 if (!kvm->arch.vpit)
7438 goto out;
7439 r = kvm_vm_ioctl_reinject(kvm, &control);
7440 break;
7441 }
7442 #endif
7443 case KVM_SET_BOOT_CPU_ID:
7444 r = 0;
7445 mutex_lock(&kvm->lock);
7446 if (kvm->created_vcpus)
7447 r = -EBUSY;
7448 else if (arg > KVM_MAX_VCPU_IDS ||
7449 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
7450 r = -EINVAL;
7451 else
7452 kvm->arch.bsp_vcpu_id = arg;
7453 mutex_unlock(&kvm->lock);
7454 break;
7455 #ifdef CONFIG_KVM_XEN
7456 case KVM_XEN_HVM_CONFIG: {
7457 struct kvm_xen_hvm_config xhc;
7458 r = -EFAULT;
7459 if (copy_from_user(&xhc, argp, sizeof(xhc)))
7460 goto out;
7461 r = kvm_xen_hvm_config(kvm, &xhc);
7462 break;
7463 }
7464 case KVM_XEN_HVM_GET_ATTR: {
7465 struct kvm_xen_hvm_attr xha;
7466
7467 r = -EFAULT;
7468 if (copy_from_user(&xha, argp, sizeof(xha)))
7469 goto out;
7470 r = kvm_xen_hvm_get_attr(kvm, &xha);
7471 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7472 r = -EFAULT;
7473 break;
7474 }
7475 case KVM_XEN_HVM_SET_ATTR: {
7476 struct kvm_xen_hvm_attr xha;
7477
7478 r = -EFAULT;
7479 if (copy_from_user(&xha, argp, sizeof(xha)))
7480 goto out;
7481 r = kvm_xen_hvm_set_attr(kvm, &xha);
7482 break;
7483 }
7484 case KVM_XEN_HVM_EVTCHN_SEND: {
7485 struct kvm_irq_routing_xen_evtchn uxe;
7486
7487 r = -EFAULT;
7488 if (copy_from_user(&uxe, argp, sizeof(uxe)))
7489 goto out;
7490 r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7491 break;
7492 }
7493 #endif
7494 case KVM_SET_CLOCK:
7495 r = kvm_vm_ioctl_set_clock(kvm, argp);
7496 break;
7497 case KVM_GET_CLOCK:
7498 r = kvm_vm_ioctl_get_clock(kvm, argp);
7499 break;
7500 case KVM_SET_TSC_KHZ: {
7501 u32 user_tsc_khz;
7502
7503 r = -EINVAL;
7504 user_tsc_khz = (u32)arg;
7505
7506 if (kvm_caps.has_tsc_control &&
7507 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
7508 goto out;
7509
7510 if (user_tsc_khz == 0)
7511 user_tsc_khz = tsc_khz;
7512
7513 mutex_lock(&kvm->lock);
7514 if (!kvm->created_vcpus) {
7515 WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7516 r = 0;
7517 }
7518 mutex_unlock(&kvm->lock);
7519 goto out;
7520 }
7521 case KVM_GET_TSC_KHZ: {
7522 r = READ_ONCE(kvm->arch.default_tsc_khz);
7523 goto out;
7524 }
7525 case KVM_MEMORY_ENCRYPT_OP:
7526 r = -ENOTTY;
7527 if (!kvm_x86_ops.mem_enc_ioctl)
7528 goto out;
7529
7530 r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
7531 break;
7532 case KVM_MEMORY_ENCRYPT_REG_REGION: {
7533 struct kvm_enc_region region;
7534
7535 r = -EFAULT;
7536 if (copy_from_user(®ion, argp, sizeof(region)))
7537 goto out;
7538
7539 r = -ENOTTY;
7540 if (!kvm_x86_ops.mem_enc_register_region)
7541 goto out;
7542
7543 r = kvm_x86_call(mem_enc_register_region)(kvm, ®ion);
7544 break;
7545 }
7546 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7547 struct kvm_enc_region region;
7548
7549 r = -EFAULT;
7550 if (copy_from_user(®ion, argp, sizeof(region)))
7551 goto out;
7552
7553 r = -ENOTTY;
7554 if (!kvm_x86_ops.mem_enc_unregister_region)
7555 goto out;
7556
7557 r = kvm_x86_call(mem_enc_unregister_region)(kvm, ®ion);
7558 break;
7559 }
7560 #ifdef CONFIG_KVM_HYPERV
7561 case KVM_HYPERV_EVENTFD: {
7562 struct kvm_hyperv_eventfd hvevfd;
7563
7564 r = -EFAULT;
7565 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7566 goto out;
7567 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7568 break;
7569 }
7570 #endif
7571 case KVM_SET_PMU_EVENT_FILTER:
7572 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7573 break;
7574 case KVM_X86_SET_MSR_FILTER: {
7575 struct kvm_msr_filter __user *user_msr_filter = argp;
7576 struct kvm_msr_filter filter;
7577
7578 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7579 return -EFAULT;
7580
7581 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7582 break;
7583 }
7584 default:
7585 r = -ENOTTY;
7586 }
7587 out:
7588 return r;
7589 }
7590
kvm_probe_feature_msr(u32 msr_index)7591 static void kvm_probe_feature_msr(u32 msr_index)
7592 {
7593 u64 data;
7594
7595 if (kvm_get_feature_msr(NULL, msr_index, &data, true))
7596 return;
7597
7598 msr_based_features[num_msr_based_features++] = msr_index;
7599 }
7600
kvm_probe_msr_to_save(u32 msr_index)7601 static void kvm_probe_msr_to_save(u32 msr_index)
7602 {
7603 u32 dummy[2];
7604
7605 if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7606 return;
7607
7608 /*
7609 * Even MSRs that are valid in the host may not be exposed to guests in
7610 * some cases.
7611 */
7612 switch (msr_index) {
7613 case MSR_IA32_BNDCFGS:
7614 if (!kvm_mpx_supported())
7615 return;
7616 break;
7617 case MSR_TSC_AUX:
7618 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7619 !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7620 return;
7621 break;
7622 case MSR_IA32_UMWAIT_CONTROL:
7623 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7624 return;
7625 break;
7626 case MSR_IA32_RTIT_CTL:
7627 case MSR_IA32_RTIT_STATUS:
7628 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7629 return;
7630 break;
7631 case MSR_IA32_RTIT_CR3_MATCH:
7632 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7633 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7634 return;
7635 break;
7636 case MSR_IA32_RTIT_OUTPUT_BASE:
7637 case MSR_IA32_RTIT_OUTPUT_MASK:
7638 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7639 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7640 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7641 return;
7642 break;
7643 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7644 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7645 (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7646 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7647 return;
7648 break;
7649 case MSR_ARCH_PERFMON_PERFCTR0 ...
7650 MSR_ARCH_PERFMON_PERFCTR0 + KVM_MAX_NR_GP_COUNTERS - 1:
7651 if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7652 kvm_pmu_cap.num_counters_gp)
7653 return;
7654 break;
7655 case MSR_ARCH_PERFMON_EVENTSEL0 ...
7656 MSR_ARCH_PERFMON_EVENTSEL0 + KVM_MAX_NR_GP_COUNTERS - 1:
7657 if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7658 kvm_pmu_cap.num_counters_gp)
7659 return;
7660 break;
7661 case MSR_ARCH_PERFMON_FIXED_CTR0 ...
7662 MSR_ARCH_PERFMON_FIXED_CTR0 + KVM_MAX_NR_FIXED_COUNTERS - 1:
7663 if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7664 kvm_pmu_cap.num_counters_fixed)
7665 return;
7666 break;
7667 case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7668 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7669 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7670 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET:
7671 if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7672 return;
7673 break;
7674 case MSR_IA32_XFD:
7675 case MSR_IA32_XFD_ERR:
7676 if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7677 return;
7678 break;
7679 case MSR_IA32_TSX_CTRL:
7680 if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7681 return;
7682 break;
7683 case MSR_IA32_XSS:
7684 if (!kvm_caps.supported_xss)
7685 return;
7686 break;
7687 case MSR_IA32_U_CET:
7688 case MSR_IA32_S_CET:
7689 if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
7690 !kvm_cpu_cap_has(X86_FEATURE_IBT))
7691 return;
7692 break;
7693 case MSR_IA32_INT_SSP_TAB:
7694 if (!kvm_cpu_cap_has(X86_FEATURE_LM))
7695 return;
7696 fallthrough;
7697 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
7698 if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK))
7699 return;
7700 break;
7701 default:
7702 break;
7703 }
7704
7705 msrs_to_save[num_msrs_to_save++] = msr_index;
7706 }
7707
kvm_init_msr_lists(void)7708 static void kvm_init_msr_lists(void)
7709 {
7710 unsigned i;
7711
7712 BUILD_BUG_ON_MSG(KVM_MAX_NR_FIXED_COUNTERS != 3,
7713 "Please update the fixed PMCs in msrs_to_save_pmu[]");
7714
7715 num_msrs_to_save = 0;
7716 num_emulated_msrs = 0;
7717 num_msr_based_features = 0;
7718
7719 for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7720 kvm_probe_msr_to_save(msrs_to_save_base[i]);
7721
7722 if (enable_pmu) {
7723 for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7724 kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
7725 }
7726
7727 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7728 if (!kvm_x86_call(has_emulated_msr)(NULL,
7729 emulated_msrs_all[i]))
7730 continue;
7731
7732 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7733 }
7734
7735 for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7736 kvm_probe_feature_msr(i);
7737
7738 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7739 kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
7740 }
7741
vcpu_mmio_write(struct kvm_vcpu * vcpu,gpa_t addr,int len,const void * v)7742 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7743 const void *v)
7744 {
7745 int handled = 0;
7746 int n;
7747
7748 do {
7749 n = min(len, 8);
7750 if (!(lapic_in_kernel(vcpu) &&
7751 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7752 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7753 break;
7754 handled += n;
7755 addr += n;
7756 len -= n;
7757 v += n;
7758 } while (len);
7759
7760 return handled;
7761 }
7762
vcpu_mmio_read(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * v)7763 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7764 {
7765 int handled = 0;
7766 int n;
7767
7768 do {
7769 n = min(len, 8);
7770 if (!(lapic_in_kernel(vcpu) &&
7771 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7772 addr, n, v))
7773 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7774 break;
7775 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7776 handled += n;
7777 addr += n;
7778 len -= n;
7779 v += n;
7780 } while (len);
7781
7782 return handled;
7783 }
7784
kvm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7785 void kvm_set_segment(struct kvm_vcpu *vcpu,
7786 struct kvm_segment *var, int seg)
7787 {
7788 kvm_x86_call(set_segment)(vcpu, var, seg);
7789 }
7790
kvm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7791 void kvm_get_segment(struct kvm_vcpu *vcpu,
7792 struct kvm_segment *var, int seg)
7793 {
7794 kvm_x86_call(get_segment)(vcpu, var, seg);
7795 }
7796
translate_nested_gpa(struct kvm_vcpu * vcpu,gpa_t gpa,u64 access,struct x86_exception * exception)7797 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7798 struct x86_exception *exception)
7799 {
7800 struct kvm_mmu *mmu = vcpu->arch.mmu;
7801 gpa_t t_gpa;
7802
7803 BUG_ON(!mmu_is_nested(vcpu));
7804
7805 /* NPT walks are always user-walks */
7806 access |= PFERR_USER_MASK;
7807 t_gpa = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7808
7809 return t_gpa;
7810 }
7811
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7812 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7813 struct x86_exception *exception)
7814 {
7815 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7816
7817 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7818 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7819 }
7820 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_read);
7821
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7822 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7823 struct x86_exception *exception)
7824 {
7825 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7826
7827 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7828 access |= PFERR_WRITE_MASK;
7829 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7830 }
7831 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_write);
7832
7833 /* uses this to access any guest's mapped memory without checking CPL */
kvm_mmu_gva_to_gpa_system(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7834 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7835 struct x86_exception *exception)
7836 {
7837 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7838
7839 return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7840 }
7841
kvm_read_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7842 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7843 struct kvm_vcpu *vcpu, u64 access,
7844 struct x86_exception *exception)
7845 {
7846 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7847 void *data = val;
7848 int r = X86EMUL_CONTINUE;
7849
7850 while (bytes) {
7851 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7852 unsigned offset = addr & (PAGE_SIZE-1);
7853 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7854 int ret;
7855
7856 if (gpa == INVALID_GPA)
7857 return X86EMUL_PROPAGATE_FAULT;
7858 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7859 offset, toread);
7860 if (ret < 0) {
7861 r = X86EMUL_IO_NEEDED;
7862 goto out;
7863 }
7864
7865 bytes -= toread;
7866 data += toread;
7867 addr += toread;
7868 }
7869 out:
7870 return r;
7871 }
7872
7873 /* used for instruction fetching */
kvm_fetch_guest_virt(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7874 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7875 gva_t addr, void *val, unsigned int bytes,
7876 struct x86_exception *exception)
7877 {
7878 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7879 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7880 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7881 unsigned offset;
7882 int ret;
7883
7884 /* Inline kvm_read_guest_virt_helper for speed. */
7885 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7886 exception);
7887 if (unlikely(gpa == INVALID_GPA))
7888 return X86EMUL_PROPAGATE_FAULT;
7889
7890 offset = addr & (PAGE_SIZE-1);
7891 if (WARN_ON(offset + bytes > PAGE_SIZE))
7892 bytes = (unsigned)PAGE_SIZE - offset;
7893 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7894 offset, bytes);
7895 if (unlikely(ret < 0))
7896 return X86EMUL_IO_NEEDED;
7897
7898 return X86EMUL_CONTINUE;
7899 }
7900
kvm_read_guest_virt(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7901 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7902 gva_t addr, void *val, unsigned int bytes,
7903 struct x86_exception *exception)
7904 {
7905 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7906
7907 /*
7908 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7909 * is returned, but our callers are not ready for that and they blindly
7910 * call kvm_inject_page_fault. Ensure that they at least do not leak
7911 * uninitialized kernel stack memory into cr2 and error code.
7912 */
7913 memset(exception, 0, sizeof(*exception));
7914 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7915 exception);
7916 }
7917 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_virt);
7918
emulator_read_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7919 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7920 gva_t addr, void *val, unsigned int bytes,
7921 struct x86_exception *exception, bool system)
7922 {
7923 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7924 u64 access = 0;
7925
7926 if (system)
7927 access |= PFERR_IMPLICIT_ACCESS;
7928 else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7929 access |= PFERR_USER_MASK;
7930
7931 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7932 }
7933
kvm_write_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7934 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7935 struct kvm_vcpu *vcpu, u64 access,
7936 struct x86_exception *exception)
7937 {
7938 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7939 void *data = val;
7940 int r = X86EMUL_CONTINUE;
7941
7942 while (bytes) {
7943 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7944 unsigned offset = addr & (PAGE_SIZE-1);
7945 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7946 int ret;
7947
7948 if (gpa == INVALID_GPA)
7949 return X86EMUL_PROPAGATE_FAULT;
7950 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7951 if (ret < 0) {
7952 r = X86EMUL_IO_NEEDED;
7953 goto out;
7954 }
7955
7956 bytes -= towrite;
7957 data += towrite;
7958 addr += towrite;
7959 }
7960 out:
7961 return r;
7962 }
7963
emulator_write_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7964 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7965 unsigned int bytes, struct x86_exception *exception,
7966 bool system)
7967 {
7968 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7969 u64 access = PFERR_WRITE_MASK;
7970
7971 if (system)
7972 access |= PFERR_IMPLICIT_ACCESS;
7973 else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7974 access |= PFERR_USER_MASK;
7975
7976 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7977 access, exception);
7978 }
7979
kvm_write_guest_virt_system(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7980 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7981 unsigned int bytes, struct x86_exception *exception)
7982 {
7983 /* kvm_write_guest_virt_system can pull in tons of pages. */
7984 kvm_request_l1tf_flush_l1d();
7985
7986 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7987 PFERR_WRITE_MASK, exception);
7988 }
7989 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_write_guest_virt_system);
7990
kvm_check_emulate_insn(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)7991 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7992 void *insn, int insn_len)
7993 {
7994 return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
7995 insn, insn_len);
7996 }
7997
handle_ud(struct kvm_vcpu * vcpu)7998 int handle_ud(struct kvm_vcpu *vcpu)
7999 {
8000 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
8001 int fep_flags = READ_ONCE(force_emulation_prefix);
8002 int emul_type = EMULTYPE_TRAP_UD;
8003 char sig[5]; /* ud2; .ascii "kvm" */
8004 struct x86_exception e;
8005 int r;
8006
8007 r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
8008 if (r != X86EMUL_CONTINUE)
8009 return 1;
8010
8011 if (fep_flags &&
8012 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
8013 sig, sizeof(sig), &e) == 0 &&
8014 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
8015 if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
8016 kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
8017 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
8018 emul_type = EMULTYPE_TRAP_UD_FORCED;
8019 }
8020
8021 return kvm_emulate_instruction(vcpu, emul_type);
8022 }
8023 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_ud);
8024
vcpu_is_mmio_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t gpa,bool write)8025 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
8026 gpa_t gpa, bool write)
8027 {
8028 /* For APIC access vmexit */
8029 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8030 return 1;
8031
8032 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
8033 trace_vcpu_match_mmio(gva, gpa, write, true);
8034 return 1;
8035 }
8036
8037 return 0;
8038 }
8039
vcpu_mmio_gva_to_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t * gpa,struct x86_exception * exception,bool write)8040 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
8041 gpa_t *gpa, struct x86_exception *exception,
8042 bool write)
8043 {
8044 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8045 u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
8046 | (write ? PFERR_WRITE_MASK : 0);
8047
8048 /*
8049 * currently PKRU is only applied to ept enabled guest so
8050 * there is no pkey in EPT page table for L1 guest or EPT
8051 * shadow page table for L2 guest.
8052 */
8053 if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
8054 !permission_fault(vcpu, vcpu->arch.walk_mmu,
8055 vcpu->arch.mmio_access, 0, access))) {
8056 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
8057 (gva & (PAGE_SIZE - 1));
8058 trace_vcpu_match_mmio(gva, *gpa, write, false);
8059 return 1;
8060 }
8061
8062 *gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
8063
8064 if (*gpa == INVALID_GPA)
8065 return -1;
8066
8067 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
8068 }
8069
emulator_write_phys(struct kvm_vcpu * vcpu,gpa_t gpa,const void * val,int bytes)8070 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
8071 const void *val, int bytes)
8072 {
8073 int ret;
8074
8075 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
8076 if (ret < 0)
8077 return 0;
8078 kvm_page_track_write(vcpu, gpa, val, bytes);
8079 return 1;
8080 }
8081
8082 struct read_write_emulator_ops {
8083 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
8084 int bytes);
8085 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
8086 void *val, int bytes);
8087 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
8088 int bytes, void *val);
8089 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
8090 void *val, int bytes);
8091 bool write;
8092 };
8093
read_prepare(struct kvm_vcpu * vcpu,void * val,int bytes)8094 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
8095 {
8096 if (vcpu->mmio_read_completed) {
8097 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
8098 vcpu->mmio_fragments[0].gpa, val);
8099 vcpu->mmio_read_completed = 0;
8100 return 1;
8101 }
8102
8103 return 0;
8104 }
8105
read_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8106 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
8107 void *val, int bytes)
8108 {
8109 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
8110 }
8111
write_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8112 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
8113 void *val, int bytes)
8114 {
8115 return emulator_write_phys(vcpu, gpa, val, bytes);
8116 }
8117
write_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,int bytes,void * val)8118 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
8119 {
8120 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
8121 return vcpu_mmio_write(vcpu, gpa, bytes, val);
8122 }
8123
read_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8124 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
8125 void *val, int bytes)
8126 {
8127 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
8128 return X86EMUL_IO_NEEDED;
8129 }
8130
write_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8131 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
8132 void *val, int bytes)
8133 {
8134 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
8135
8136 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
8137 return X86EMUL_CONTINUE;
8138 }
8139
8140 static const struct read_write_emulator_ops read_emultor = {
8141 .read_write_prepare = read_prepare,
8142 .read_write_emulate = read_emulate,
8143 .read_write_mmio = vcpu_mmio_read,
8144 .read_write_exit_mmio = read_exit_mmio,
8145 };
8146
8147 static const struct read_write_emulator_ops write_emultor = {
8148 .read_write_emulate = write_emulate,
8149 .read_write_mmio = write_mmio,
8150 .read_write_exit_mmio = write_exit_mmio,
8151 .write = true,
8152 };
8153
emulator_read_write_onepage(unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception,struct kvm_vcpu * vcpu,const struct read_write_emulator_ops * ops)8154 static int emulator_read_write_onepage(unsigned long addr, void *val,
8155 unsigned int bytes,
8156 struct x86_exception *exception,
8157 struct kvm_vcpu *vcpu,
8158 const struct read_write_emulator_ops *ops)
8159 {
8160 gpa_t gpa;
8161 int handled, ret;
8162 bool write = ops->write;
8163 struct kvm_mmio_fragment *frag;
8164 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8165
8166 /*
8167 * If the exit was due to a NPF we may already have a GPA.
8168 * If the GPA is present, use it to avoid the GVA to GPA table walk.
8169 * Note, this cannot be used on string operations since string
8170 * operation using rep will only have the initial GPA from the NPF
8171 * occurred.
8172 */
8173 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
8174 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
8175 gpa = ctxt->gpa_val;
8176 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
8177 } else {
8178 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
8179 if (ret < 0)
8180 return X86EMUL_PROPAGATE_FAULT;
8181 }
8182
8183 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
8184 return X86EMUL_CONTINUE;
8185
8186 /*
8187 * Is this MMIO handled locally?
8188 */
8189 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
8190 if (handled == bytes)
8191 return X86EMUL_CONTINUE;
8192
8193 gpa += handled;
8194 bytes -= handled;
8195 val += handled;
8196
8197 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
8198 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
8199 frag->gpa = gpa;
8200 frag->data = val;
8201 frag->len = bytes;
8202 return X86EMUL_CONTINUE;
8203 }
8204
emulator_read_write(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception,const struct read_write_emulator_ops * ops)8205 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
8206 unsigned long addr,
8207 void *val, unsigned int bytes,
8208 struct x86_exception *exception,
8209 const struct read_write_emulator_ops *ops)
8210 {
8211 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8212 gpa_t gpa;
8213 int rc;
8214
8215 if (ops->read_write_prepare &&
8216 ops->read_write_prepare(vcpu, val, bytes))
8217 return X86EMUL_CONTINUE;
8218
8219 vcpu->mmio_nr_fragments = 0;
8220
8221 /* Crossing a page boundary? */
8222 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
8223 int now;
8224
8225 now = -addr & ~PAGE_MASK;
8226 rc = emulator_read_write_onepage(addr, val, now, exception,
8227 vcpu, ops);
8228
8229 if (rc != X86EMUL_CONTINUE)
8230 return rc;
8231 addr += now;
8232 if (ctxt->mode != X86EMUL_MODE_PROT64)
8233 addr = (u32)addr;
8234 val += now;
8235 bytes -= now;
8236 }
8237
8238 rc = emulator_read_write_onepage(addr, val, bytes, exception,
8239 vcpu, ops);
8240 if (rc != X86EMUL_CONTINUE)
8241 return rc;
8242
8243 if (!vcpu->mmio_nr_fragments)
8244 return X86EMUL_CONTINUE;
8245
8246 gpa = vcpu->mmio_fragments[0].gpa;
8247
8248 vcpu->mmio_needed = 1;
8249 vcpu->mmio_cur_fragment = 0;
8250
8251 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
8252 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
8253 vcpu->run->exit_reason = KVM_EXIT_MMIO;
8254 vcpu->run->mmio.phys_addr = gpa;
8255
8256 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
8257 }
8258
emulator_read_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception)8259 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8260 unsigned long addr,
8261 void *val,
8262 unsigned int bytes,
8263 struct x86_exception *exception)
8264 {
8265 return emulator_read_write(ctxt, addr, val, bytes,
8266 exception, &read_emultor);
8267 }
8268
emulator_write_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * val,unsigned int bytes,struct x86_exception * exception)8269 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
8270 unsigned long addr,
8271 const void *val,
8272 unsigned int bytes,
8273 struct x86_exception *exception)
8274 {
8275 return emulator_read_write(ctxt, addr, (void *)val, bytes,
8276 exception, &write_emultor);
8277 }
8278
8279 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
8280 (__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
8281
emulator_cmpxchg_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * old,const void * new,unsigned int bytes,struct x86_exception * exception)8282 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8283 unsigned long addr,
8284 const void *old,
8285 const void *new,
8286 unsigned int bytes,
8287 struct x86_exception *exception)
8288 {
8289 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8290 u64 page_line_mask;
8291 unsigned long hva;
8292 gpa_t gpa;
8293 int r;
8294
8295 /* guests cmpxchg8b have to be emulated atomically */
8296 if (bytes > 8 || (bytes & (bytes - 1)))
8297 goto emul_write;
8298
8299 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
8300
8301 if (gpa == INVALID_GPA ||
8302 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8303 goto emul_write;
8304
8305 /*
8306 * Emulate the atomic as a straight write to avoid #AC if SLD is
8307 * enabled in the host and the access splits a cache line.
8308 */
8309 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8310 page_line_mask = ~(cache_line_size() - 1);
8311 else
8312 page_line_mask = PAGE_MASK;
8313
8314 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
8315 goto emul_write;
8316
8317 hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
8318 if (kvm_is_error_hva(hva))
8319 goto emul_write;
8320
8321 hva += offset_in_page(gpa);
8322
8323 switch (bytes) {
8324 case 1:
8325 r = emulator_try_cmpxchg_user(u8, hva, old, new);
8326 break;
8327 case 2:
8328 r = emulator_try_cmpxchg_user(u16, hva, old, new);
8329 break;
8330 case 4:
8331 r = emulator_try_cmpxchg_user(u32, hva, old, new);
8332 break;
8333 case 8:
8334 r = emulator_try_cmpxchg_user(u64, hva, old, new);
8335 break;
8336 default:
8337 BUG();
8338 }
8339
8340 if (r < 0)
8341 return X86EMUL_UNHANDLEABLE;
8342
8343 /*
8344 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8345 * successful, as the old value is written back on failure. Note, for
8346 * live migration, this is unnecessarily conservative as CMPXCHG writes
8347 * back the original value and the access is atomic, but KVM's ABI is
8348 * that all writes are dirty logged, regardless of the value written.
8349 */
8350 kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8351
8352 if (r)
8353 return X86EMUL_CMPXCHG_FAILED;
8354
8355 kvm_page_track_write(vcpu, gpa, new, bytes);
8356
8357 return X86EMUL_CONTINUE;
8358
8359 emul_write:
8360 pr_warn_once("emulating exchange as write\n");
8361
8362 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
8363 }
8364
emulator_pio_in_out(struct kvm_vcpu * vcpu,int size,unsigned short port,void * data,unsigned int count,bool in)8365 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
8366 unsigned short port, void *data,
8367 unsigned int count, bool in)
8368 {
8369 unsigned i;
8370 int r;
8371
8372 WARN_ON_ONCE(vcpu->arch.pio.count);
8373 for (i = 0; i < count; i++) {
8374 if (in)
8375 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
8376 else
8377 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
8378
8379 if (r) {
8380 if (i == 0)
8381 goto userspace_io;
8382
8383 /*
8384 * Userspace must have unregistered the device while PIO
8385 * was running. Drop writes / read as 0.
8386 */
8387 if (in)
8388 memset(data, 0, size * (count - i));
8389 break;
8390 }
8391
8392 data += size;
8393 }
8394 return 1;
8395
8396 userspace_io:
8397 vcpu->arch.pio.port = port;
8398 vcpu->arch.pio.in = in;
8399 vcpu->arch.pio.count = count;
8400 vcpu->arch.pio.size = size;
8401
8402 if (in)
8403 memset(vcpu->arch.pio_data, 0, size * count);
8404 else
8405 memcpy(vcpu->arch.pio_data, data, size * count);
8406
8407 vcpu->run->exit_reason = KVM_EXIT_IO;
8408 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
8409 vcpu->run->io.size = size;
8410 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8411 vcpu->run->io.count = count;
8412 vcpu->run->io.port = port;
8413 return 0;
8414 }
8415
emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,void * val,unsigned int count)8416 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8417 unsigned short port, void *val, unsigned int count)
8418 {
8419 int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8420 if (r)
8421 trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8422
8423 return r;
8424 }
8425
complete_emulator_pio_in(struct kvm_vcpu * vcpu,void * val)8426 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
8427 {
8428 int size = vcpu->arch.pio.size;
8429 unsigned int count = vcpu->arch.pio.count;
8430 memcpy(val, vcpu->arch.pio_data, size * count);
8431 trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
8432 vcpu->arch.pio.count = 0;
8433 }
8434
emulator_pio_in_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,void * val,unsigned int count)8435 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8436 int size, unsigned short port, void *val,
8437 unsigned int count)
8438 {
8439 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8440 if (vcpu->arch.pio.count) {
8441 /*
8442 * Complete a previous iteration that required userspace I/O.
8443 * Note, @count isn't guaranteed to match pio.count as userspace
8444 * can modify ECX before rerunning the vCPU. Ignore any such
8445 * shenanigans as KVM doesn't support modifying the rep count,
8446 * and the emulator ensures @count doesn't overflow the buffer.
8447 */
8448 complete_emulator_pio_in(vcpu, val);
8449 return 1;
8450 }
8451
8452 return emulator_pio_in(vcpu, size, port, val, count);
8453 }
8454
emulator_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port,const void * val,unsigned int count)8455 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8456 unsigned short port, const void *val,
8457 unsigned int count)
8458 {
8459 trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
8460 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
8461 }
8462
emulator_pio_out_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,const void * val,unsigned int count)8463 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8464 int size, unsigned short port,
8465 const void *val, unsigned int count)
8466 {
8467 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8468 }
8469
get_segment_base(struct kvm_vcpu * vcpu,int seg)8470 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8471 {
8472 return kvm_x86_call(get_segment_base)(vcpu, seg);
8473 }
8474
emulator_invlpg(struct x86_emulate_ctxt * ctxt,ulong address)8475 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
8476 {
8477 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
8478 }
8479
kvm_emulate_wbinvd_noskip(struct kvm_vcpu * vcpu)8480 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
8481 {
8482 if (!need_emulate_wbinvd(vcpu))
8483 return X86EMUL_CONTINUE;
8484
8485 if (kvm_x86_call(has_wbinvd_exit)()) {
8486 int cpu = get_cpu();
8487
8488 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
8489 wbinvd_on_cpus_mask(vcpu->arch.wbinvd_dirty_mask);
8490 put_cpu();
8491 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
8492 } else
8493 wbinvd();
8494 return X86EMUL_CONTINUE;
8495 }
8496
kvm_emulate_wbinvd(struct kvm_vcpu * vcpu)8497 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8498 {
8499 kvm_emulate_wbinvd_noskip(vcpu);
8500 return kvm_skip_emulated_instruction(vcpu);
8501 }
8502 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wbinvd);
8503
8504
8505
emulator_wbinvd(struct x86_emulate_ctxt * ctxt)8506 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8507 {
8508 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
8509 }
8510
emulator_get_dr(struct x86_emulate_ctxt * ctxt,int dr)8511 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
8512 {
8513 return kvm_get_dr(emul_to_vcpu(ctxt), dr);
8514 }
8515
emulator_set_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long value)8516 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8517 unsigned long value)
8518 {
8519
8520 return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
8521 }
8522
mk_cr_64(u64 curr_cr,u32 new_val)8523 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
8524 {
8525 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
8526 }
8527
emulator_get_cr(struct x86_emulate_ctxt * ctxt,int cr)8528 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
8529 {
8530 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8531 unsigned long value;
8532
8533 switch (cr) {
8534 case 0:
8535 value = kvm_read_cr0(vcpu);
8536 break;
8537 case 2:
8538 value = vcpu->arch.cr2;
8539 break;
8540 case 3:
8541 value = kvm_read_cr3(vcpu);
8542 break;
8543 case 4:
8544 value = kvm_read_cr4(vcpu);
8545 break;
8546 case 8:
8547 value = kvm_get_cr8(vcpu);
8548 break;
8549 default:
8550 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8551 return 0;
8552 }
8553
8554 return value;
8555 }
8556
emulator_set_cr(struct x86_emulate_ctxt * ctxt,int cr,ulong val)8557 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
8558 {
8559 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8560 int res = 0;
8561
8562 switch (cr) {
8563 case 0:
8564 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
8565 break;
8566 case 2:
8567 vcpu->arch.cr2 = val;
8568 break;
8569 case 3:
8570 res = kvm_set_cr3(vcpu, val);
8571 break;
8572 case 4:
8573 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
8574 break;
8575 case 8:
8576 res = kvm_set_cr8(vcpu, val);
8577 break;
8578 default:
8579 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8580 res = -1;
8581 }
8582
8583 return res;
8584 }
8585
emulator_get_cpl(struct x86_emulate_ctxt * ctxt)8586 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8587 {
8588 return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
8589 }
8590
emulator_get_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8591 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8592 {
8593 kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
8594 }
8595
emulator_get_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8596 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8597 {
8598 kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
8599 }
8600
emulator_set_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8601 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8602 {
8603 kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
8604 }
8605
emulator_set_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8606 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8607 {
8608 kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
8609 }
8610
emulator_get_cached_segment_base(struct x86_emulate_ctxt * ctxt,int seg)8611 static unsigned long emulator_get_cached_segment_base(
8612 struct x86_emulate_ctxt *ctxt, int seg)
8613 {
8614 return get_segment_base(emul_to_vcpu(ctxt), seg);
8615 }
8616
emulator_get_segment(struct x86_emulate_ctxt * ctxt,u16 * selector,struct desc_struct * desc,u32 * base3,int seg)8617 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8618 struct desc_struct *desc, u32 *base3,
8619 int seg)
8620 {
8621 struct kvm_segment var;
8622
8623 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8624 *selector = var.selector;
8625
8626 if (var.unusable) {
8627 memset(desc, 0, sizeof(*desc));
8628 if (base3)
8629 *base3 = 0;
8630 return false;
8631 }
8632
8633 if (var.g)
8634 var.limit >>= 12;
8635 set_desc_limit(desc, var.limit);
8636 set_desc_base(desc, (unsigned long)var.base);
8637 #ifdef CONFIG_X86_64
8638 if (base3)
8639 *base3 = var.base >> 32;
8640 #endif
8641 desc->type = var.type;
8642 desc->s = var.s;
8643 desc->dpl = var.dpl;
8644 desc->p = var.present;
8645 desc->avl = var.avl;
8646 desc->l = var.l;
8647 desc->d = var.db;
8648 desc->g = var.g;
8649
8650 return true;
8651 }
8652
emulator_set_segment(struct x86_emulate_ctxt * ctxt,u16 selector,struct desc_struct * desc,u32 base3,int seg)8653 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8654 struct desc_struct *desc, u32 base3,
8655 int seg)
8656 {
8657 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8658 struct kvm_segment var;
8659
8660 var.selector = selector;
8661 var.base = get_desc_base(desc);
8662 #ifdef CONFIG_X86_64
8663 var.base |= ((u64)base3) << 32;
8664 #endif
8665 var.limit = get_desc_limit(desc);
8666 if (desc->g)
8667 var.limit = (var.limit << 12) | 0xfff;
8668 var.type = desc->type;
8669 var.dpl = desc->dpl;
8670 var.db = desc->d;
8671 var.s = desc->s;
8672 var.l = desc->l;
8673 var.g = desc->g;
8674 var.avl = desc->avl;
8675 var.present = desc->p;
8676 var.unusable = !var.present;
8677 var.padding = 0;
8678
8679 kvm_set_segment(vcpu, &var, seg);
8680 return;
8681 }
8682
emulator_get_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8683 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8684 u32 msr_index, u64 *pdata)
8685 {
8686 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8687 int r;
8688
8689 r = kvm_emulate_msr_read(vcpu, msr_index, pdata);
8690 if (r < 0)
8691 return X86EMUL_UNHANDLEABLE;
8692
8693 if (r) {
8694 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8695 complete_emulated_rdmsr, r))
8696 return X86EMUL_IO_NEEDED;
8697
8698 trace_kvm_msr_read_ex(msr_index);
8699 return X86EMUL_PROPAGATE_FAULT;
8700 }
8701
8702 trace_kvm_msr_read(msr_index, *pdata);
8703 return X86EMUL_CONTINUE;
8704 }
8705
emulator_set_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)8706 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8707 u32 msr_index, u64 data)
8708 {
8709 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8710 int r;
8711
8712 r = kvm_emulate_msr_write(vcpu, msr_index, data);
8713 if (r < 0)
8714 return X86EMUL_UNHANDLEABLE;
8715
8716 if (r) {
8717 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8718 complete_emulated_msr_access, r))
8719 return X86EMUL_IO_NEEDED;
8720
8721 trace_kvm_msr_write_ex(msr_index, data);
8722 return X86EMUL_PROPAGATE_FAULT;
8723 }
8724
8725 trace_kvm_msr_write(msr_index, data);
8726 return X86EMUL_CONTINUE;
8727 }
8728
emulator_get_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8729 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8730 u32 msr_index, u64 *pdata)
8731 {
8732 /*
8733 * Treat emulator accesses to the current shadow stack pointer as host-
8734 * initiated, as they aren't true MSR accesses (SSP is a "just a reg"),
8735 * and this API is used only for implicit accesses, i.e. not RDMSR, and
8736 * so the index is fully KVM-controlled.
8737 */
8738 if (unlikely(msr_index == MSR_KVM_INTERNAL_GUEST_SSP))
8739 return kvm_msr_read(emul_to_vcpu(ctxt), msr_index, pdata);
8740
8741 return __kvm_emulate_msr_read(emul_to_vcpu(ctxt), msr_index, pdata);
8742 }
8743
emulator_check_rdpmc_early(struct x86_emulate_ctxt * ctxt,u32 pmc)8744 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
8745 {
8746 return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
8747 }
8748
emulator_read_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc,u64 * pdata)8749 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8750 u32 pmc, u64 *pdata)
8751 {
8752 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8753 }
8754
emulator_halt(struct x86_emulate_ctxt * ctxt)8755 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8756 {
8757 emul_to_vcpu(ctxt)->arch.halt_request = 1;
8758 }
8759
emulator_intercept(struct x86_emulate_ctxt * ctxt,struct x86_instruction_info * info,enum x86_intercept_stage stage)8760 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8761 struct x86_instruction_info *info,
8762 enum x86_intercept_stage stage)
8763 {
8764 return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
8765 &ctxt->exception);
8766 }
8767
emulator_get_cpuid(struct x86_emulate_ctxt * ctxt,u32 * eax,u32 * ebx,u32 * ecx,u32 * edx,bool exact_only)8768 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8769 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8770 bool exact_only)
8771 {
8772 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8773 }
8774
emulator_guest_has_movbe(struct x86_emulate_ctxt * ctxt)8775 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8776 {
8777 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8778 }
8779
emulator_guest_has_fxsr(struct x86_emulate_ctxt * ctxt)8780 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8781 {
8782 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8783 }
8784
emulator_guest_has_rdpid(struct x86_emulate_ctxt * ctxt)8785 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8786 {
8787 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8788 }
8789
emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt * ctxt)8790 static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
8791 {
8792 return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
8793 }
8794
emulator_read_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg)8795 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8796 {
8797 return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8798 }
8799
emulator_write_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg,ulong val)8800 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8801 {
8802 kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8803 }
8804
emulator_set_nmi_mask(struct x86_emulate_ctxt * ctxt,bool masked)8805 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8806 {
8807 kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8808 }
8809
emulator_is_smm(struct x86_emulate_ctxt * ctxt)8810 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
8811 {
8812 return is_smm(emul_to_vcpu(ctxt));
8813 }
8814
8815 #ifndef CONFIG_KVM_SMM
emulator_leave_smm(struct x86_emulate_ctxt * ctxt)8816 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8817 {
8818 WARN_ON_ONCE(1);
8819 return X86EMUL_UNHANDLEABLE;
8820 }
8821 #endif
8822
emulator_triple_fault(struct x86_emulate_ctxt * ctxt)8823 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8824 {
8825 kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8826 }
8827
emulator_get_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 * xcr)8828 static int emulator_get_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 *xcr)
8829 {
8830 if (index != XCR_XFEATURE_ENABLED_MASK)
8831 return 1;
8832 *xcr = emul_to_vcpu(ctxt)->arch.xcr0;
8833 return 0;
8834 }
8835
emulator_set_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 xcr)8836 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8837 {
8838 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8839 }
8840
emulator_vm_bugged(struct x86_emulate_ctxt * ctxt)8841 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8842 {
8843 struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8844
8845 if (!kvm->vm_bugged)
8846 kvm_vm_bugged(kvm);
8847 }
8848
emulator_get_untagged_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8849 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8850 gva_t addr, unsigned int flags)
8851 {
8852 if (!kvm_x86_ops.get_untagged_addr)
8853 return addr;
8854
8855 return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
8856 addr, flags);
8857 }
8858
emulator_is_canonical_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8859 static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
8860 gva_t addr, unsigned int flags)
8861 {
8862 return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
8863 }
8864
8865 static const struct x86_emulate_ops emulate_ops = {
8866 .vm_bugged = emulator_vm_bugged,
8867 .read_gpr = emulator_read_gpr,
8868 .write_gpr = emulator_write_gpr,
8869 .read_std = emulator_read_std,
8870 .write_std = emulator_write_std,
8871 .fetch = kvm_fetch_guest_virt,
8872 .read_emulated = emulator_read_emulated,
8873 .write_emulated = emulator_write_emulated,
8874 .cmpxchg_emulated = emulator_cmpxchg_emulated,
8875 .invlpg = emulator_invlpg,
8876 .pio_in_emulated = emulator_pio_in_emulated,
8877 .pio_out_emulated = emulator_pio_out_emulated,
8878 .get_segment = emulator_get_segment,
8879 .set_segment = emulator_set_segment,
8880 .get_cached_segment_base = emulator_get_cached_segment_base,
8881 .get_gdt = emulator_get_gdt,
8882 .get_idt = emulator_get_idt,
8883 .set_gdt = emulator_set_gdt,
8884 .set_idt = emulator_set_idt,
8885 .get_cr = emulator_get_cr,
8886 .set_cr = emulator_set_cr,
8887 .cpl = emulator_get_cpl,
8888 .get_dr = emulator_get_dr,
8889 .set_dr = emulator_set_dr,
8890 .set_msr_with_filter = emulator_set_msr_with_filter,
8891 .get_msr_with_filter = emulator_get_msr_with_filter,
8892 .get_msr = emulator_get_msr,
8893 .check_rdpmc_early = emulator_check_rdpmc_early,
8894 .read_pmc = emulator_read_pmc,
8895 .halt = emulator_halt,
8896 .wbinvd = emulator_wbinvd,
8897 .fix_hypercall = emulator_fix_hypercall,
8898 .intercept = emulator_intercept,
8899 .get_cpuid = emulator_get_cpuid,
8900 .guest_has_movbe = emulator_guest_has_movbe,
8901 .guest_has_fxsr = emulator_guest_has_fxsr,
8902 .guest_has_rdpid = emulator_guest_has_rdpid,
8903 .guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
8904 .set_nmi_mask = emulator_set_nmi_mask,
8905 .is_smm = emulator_is_smm,
8906 .leave_smm = emulator_leave_smm,
8907 .triple_fault = emulator_triple_fault,
8908 .get_xcr = emulator_get_xcr,
8909 .set_xcr = emulator_set_xcr,
8910 .get_untagged_addr = emulator_get_untagged_addr,
8911 .is_canonical_addr = emulator_is_canonical_addr,
8912 };
8913
toggle_interruptibility(struct kvm_vcpu * vcpu,u32 mask)8914 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8915 {
8916 u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
8917 /*
8918 * an sti; sti; sequence only disable interrupts for the first
8919 * instruction. So, if the last instruction, be it emulated or
8920 * not, left the system with the INT_STI flag enabled, it
8921 * means that the last instruction is an sti. We should not
8922 * leave the flag on in this case. The same goes for mov ss
8923 */
8924 if (int_shadow & mask)
8925 mask = 0;
8926 if (unlikely(int_shadow || mask)) {
8927 kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
8928 if (!mask)
8929 kvm_make_request(KVM_REQ_EVENT, vcpu);
8930 }
8931 }
8932
inject_emulated_exception(struct kvm_vcpu * vcpu)8933 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8934 {
8935 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8936
8937 if (ctxt->exception.vector == PF_VECTOR)
8938 kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8939 else if (ctxt->exception.error_code_valid)
8940 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8941 ctxt->exception.error_code);
8942 else
8943 kvm_queue_exception(vcpu, ctxt->exception.vector);
8944 }
8945
alloc_emulate_ctxt(struct kvm_vcpu * vcpu)8946 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8947 {
8948 struct x86_emulate_ctxt *ctxt;
8949
8950 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8951 if (!ctxt) {
8952 pr_err("failed to allocate vcpu's emulator\n");
8953 return NULL;
8954 }
8955
8956 ctxt->vcpu = vcpu;
8957 ctxt->ops = &emulate_ops;
8958 vcpu->arch.emulate_ctxt = ctxt;
8959
8960 return ctxt;
8961 }
8962
init_emulate_ctxt(struct kvm_vcpu * vcpu)8963 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8964 {
8965 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8966 int cs_db, cs_l;
8967
8968 kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8969
8970 ctxt->gpa_available = false;
8971 ctxt->eflags = kvm_get_rflags(vcpu);
8972 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8973
8974 ctxt->eip = kvm_rip_read(vcpu);
8975 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
8976 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
8977 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
8978 cs_db ? X86EMUL_MODE_PROT32 :
8979 X86EMUL_MODE_PROT16;
8980 ctxt->interruptibility = 0;
8981 ctxt->have_exception = false;
8982 ctxt->exception.vector = -1;
8983 ctxt->perm_ok = false;
8984
8985 init_decode_cache(ctxt);
8986 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8987 }
8988
kvm_inject_realmode_interrupt(struct kvm_vcpu * vcpu,int irq,int inc_eip)8989 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8990 {
8991 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8992 int ret;
8993
8994 init_emulate_ctxt(vcpu);
8995
8996 ctxt->op_bytes = 2;
8997 ctxt->ad_bytes = 2;
8998 ctxt->_eip = ctxt->eip + inc_eip;
8999 ret = emulate_int_real(ctxt, irq);
9000
9001 if (ret != X86EMUL_CONTINUE) {
9002 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
9003 } else {
9004 ctxt->eip = ctxt->_eip;
9005 kvm_rip_write(vcpu, ctxt->eip);
9006 kvm_set_rflags(vcpu, ctxt->eflags);
9007 }
9008 }
9009 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_realmode_interrupt);
9010
prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata,u8 * insn_bytes,u8 insn_size)9011 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
9012 u8 ndata, u8 *insn_bytes, u8 insn_size)
9013 {
9014 struct kvm_run *run = vcpu->run;
9015 u64 info[5];
9016 u8 info_start;
9017
9018 /*
9019 * Zero the whole array used to retrieve the exit info, as casting to
9020 * u32 for select entries will leave some chunks uninitialized.
9021 */
9022 memset(&info, 0, sizeof(info));
9023
9024 kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
9025 (u32 *)&info[3], (u32 *)&info[4]);
9026
9027 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9028 run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
9029
9030 /*
9031 * There's currently space for 13 entries, but 5 are used for the exit
9032 * reason and info. Restrict to 4 to reduce the maintenance burden
9033 * when expanding kvm_run.emulation_failure in the future.
9034 */
9035 if (WARN_ON_ONCE(ndata > 4))
9036 ndata = 4;
9037
9038 /* Always include the flags as a 'data' entry. */
9039 info_start = 1;
9040 run->emulation_failure.flags = 0;
9041
9042 if (insn_size) {
9043 BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
9044 sizeof(run->emulation_failure.insn_bytes) != 16));
9045 info_start += 2;
9046 run->emulation_failure.flags |=
9047 KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
9048 run->emulation_failure.insn_size = insn_size;
9049 memset(run->emulation_failure.insn_bytes, 0x90,
9050 sizeof(run->emulation_failure.insn_bytes));
9051 memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
9052 }
9053
9054 memcpy(&run->internal.data[info_start], info, sizeof(info));
9055 memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
9056 ndata * sizeof(data[0]));
9057
9058 run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
9059 }
9060
prepare_emulation_ctxt_failure_exit(struct kvm_vcpu * vcpu)9061 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
9062 {
9063 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9064
9065 prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
9066 ctxt->fetch.end - ctxt->fetch.data);
9067 }
9068
__kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata)9069 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
9070 u8 ndata)
9071 {
9072 prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
9073 }
9074 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_prepare_emulation_failure_exit);
9075
kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu)9076 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
9077 {
9078 __kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
9079 }
9080 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_emulation_failure_exit);
9081
kvm_prepare_event_vectoring_exit(struct kvm_vcpu * vcpu,gpa_t gpa)9082 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa)
9083 {
9084 u32 reason, intr_info, error_code;
9085 struct kvm_run *run = vcpu->run;
9086 u64 info1, info2;
9087 int ndata = 0;
9088
9089 kvm_x86_call(get_exit_info)(vcpu, &reason, &info1, &info2,
9090 &intr_info, &error_code);
9091
9092 run->internal.data[ndata++] = info2;
9093 run->internal.data[ndata++] = reason;
9094 run->internal.data[ndata++] = info1;
9095 run->internal.data[ndata++] = gpa;
9096 run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
9097
9098 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9099 run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
9100 run->internal.ndata = ndata;
9101 }
9102 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_event_vectoring_exit);
9103
kvm_prepare_unexpected_reason_exit(struct kvm_vcpu * vcpu,u64 exit_reason)9104 void kvm_prepare_unexpected_reason_exit(struct kvm_vcpu *vcpu, u64 exit_reason)
9105 {
9106 vcpu_unimpl(vcpu, "unexpected exit reason 0x%llx\n", exit_reason);
9107
9108 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9109 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
9110 vcpu->run->internal.ndata = 2;
9111 vcpu->run->internal.data[0] = exit_reason;
9112 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
9113 }
9114 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_unexpected_reason_exit);
9115
handle_emulation_failure(struct kvm_vcpu * vcpu,int emulation_type)9116 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
9117 {
9118 struct kvm *kvm = vcpu->kvm;
9119
9120 ++vcpu->stat.insn_emulation_fail;
9121 trace_kvm_emulate_insn_failed(vcpu);
9122
9123 if (emulation_type & EMULTYPE_VMWARE_GP) {
9124 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9125 return 1;
9126 }
9127
9128 if (kvm->arch.exit_on_emulation_error ||
9129 (emulation_type & EMULTYPE_SKIP)) {
9130 prepare_emulation_ctxt_failure_exit(vcpu);
9131 return 0;
9132 }
9133
9134 kvm_queue_exception(vcpu, UD_VECTOR);
9135
9136 if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
9137 prepare_emulation_ctxt_failure_exit(vcpu);
9138 return 0;
9139 }
9140
9141 return 1;
9142 }
9143
kvm_unprotect_and_retry_on_failure(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type)9144 static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
9145 gpa_t cr2_or_gpa,
9146 int emulation_type)
9147 {
9148 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
9149 return false;
9150
9151 /*
9152 * If the failed instruction faulted on an access to page tables that
9153 * are used to translate any part of the instruction, KVM can't resolve
9154 * the issue by unprotecting the gfn, as zapping the shadow page will
9155 * result in the instruction taking a !PRESENT page fault and thus put
9156 * the vCPU into an infinite loop of page faults. E.g. KVM will create
9157 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
9158 * then zap the SPTE to unprotect the gfn, and then do it all over
9159 * again. Report the error to userspace.
9160 */
9161 if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
9162 return false;
9163
9164 /*
9165 * If emulation may have been triggered by a write to a shadowed page
9166 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
9167 * guest to let the CPU re-execute the instruction in the hope that the
9168 * CPU can cleanly execute the instruction that KVM failed to emulate.
9169 */
9170 __kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
9171
9172 /*
9173 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
9174 * all SPTEs were already zapped by a different task. The alternative
9175 * is to report the error to userspace and likely terminate the guest,
9176 * and the last_retry_{eip,addr} checks will prevent retrying the page
9177 * fault indefinitely, i.e. there's nothing to lose by retrying.
9178 */
9179 return true;
9180 }
9181
9182 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
9183 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
9184
kvm_vcpu_check_hw_bp(unsigned long addr,u32 type,u32 dr7,unsigned long * db)9185 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
9186 unsigned long *db)
9187 {
9188 u32 dr6 = 0;
9189 int i;
9190 u32 enable, rwlen;
9191
9192 enable = dr7;
9193 rwlen = dr7 >> 16;
9194 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
9195 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
9196 dr6 |= (1 << i);
9197 return dr6;
9198 }
9199
kvm_vcpu_do_singlestep(struct kvm_vcpu * vcpu)9200 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
9201 {
9202 struct kvm_run *kvm_run = vcpu->run;
9203
9204 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
9205 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
9206 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
9207 kvm_run->debug.arch.exception = DB_VECTOR;
9208 kvm_run->exit_reason = KVM_EXIT_DEBUG;
9209 return 0;
9210 }
9211 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
9212 return 1;
9213 }
9214
kvm_skip_emulated_instruction(struct kvm_vcpu * vcpu)9215 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
9216 {
9217 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9218 int r;
9219
9220 r = kvm_x86_call(skip_emulated_instruction)(vcpu);
9221 if (unlikely(!r))
9222 return 0;
9223
9224 kvm_pmu_instruction_retired(vcpu);
9225
9226 /*
9227 * rflags is the old, "raw" value of the flags. The new value has
9228 * not been saved yet.
9229 *
9230 * This is correct even for TF set by the guest, because "the
9231 * processor will not generate this exception after the instruction
9232 * that sets the TF flag".
9233 */
9234 if (unlikely(rflags & X86_EFLAGS_TF))
9235 r = kvm_vcpu_do_singlestep(vcpu);
9236 return r;
9237 }
9238 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_skip_emulated_instruction);
9239
kvm_is_code_breakpoint_inhibited(struct kvm_vcpu * vcpu)9240 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
9241 {
9242 if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
9243 return true;
9244
9245 /*
9246 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
9247 * active, but AMD compatible CPUs do not.
9248 */
9249 if (!guest_cpuid_is_intel_compatible(vcpu))
9250 return false;
9251
9252 return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
9253 }
9254
kvm_vcpu_check_code_breakpoint(struct kvm_vcpu * vcpu,int emulation_type,int * r)9255 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
9256 int emulation_type, int *r)
9257 {
9258 WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
9259
9260 /*
9261 * Do not check for code breakpoints if hardware has already done the
9262 * checks, as inferred from the emulation type. On NO_DECODE and SKIP,
9263 * the instruction has passed all exception checks, and all intercepted
9264 * exceptions that trigger emulation have lower priority than code
9265 * breakpoints, i.e. the fact that the intercepted exception occurred
9266 * means any code breakpoints have already been serviced.
9267 *
9268 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
9269 * hardware has checked the RIP of the magic prefix, but not the RIP of
9270 * the instruction being emulated. The intent of forced emulation is
9271 * to behave as if KVM intercepted the instruction without an exception
9272 * and without a prefix.
9273 */
9274 if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
9275 EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
9276 return false;
9277
9278 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
9279 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
9280 struct kvm_run *kvm_run = vcpu->run;
9281 unsigned long eip = kvm_get_linear_rip(vcpu);
9282 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9283 vcpu->arch.guest_debug_dr7,
9284 vcpu->arch.eff_db);
9285
9286 if (dr6 != 0) {
9287 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
9288 kvm_run->debug.arch.pc = eip;
9289 kvm_run->debug.arch.exception = DB_VECTOR;
9290 kvm_run->exit_reason = KVM_EXIT_DEBUG;
9291 *r = 0;
9292 return true;
9293 }
9294 }
9295
9296 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
9297 !kvm_is_code_breakpoint_inhibited(vcpu)) {
9298 unsigned long eip = kvm_get_linear_rip(vcpu);
9299 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9300 vcpu->arch.dr7,
9301 vcpu->arch.db);
9302
9303 if (dr6 != 0) {
9304 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
9305 *r = 1;
9306 return true;
9307 }
9308 }
9309
9310 return false;
9311 }
9312
is_vmware_backdoor_opcode(struct x86_emulate_ctxt * ctxt)9313 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9314 {
9315 switch (ctxt->opcode_len) {
9316 case 1:
9317 switch (ctxt->b) {
9318 case 0xe4: /* IN */
9319 case 0xe5:
9320 case 0xec:
9321 case 0xed:
9322 case 0xe6: /* OUT */
9323 case 0xe7:
9324 case 0xee:
9325 case 0xef:
9326 case 0x6c: /* INS */
9327 case 0x6d:
9328 case 0x6e: /* OUTS */
9329 case 0x6f:
9330 return true;
9331 }
9332 break;
9333 case 2:
9334 switch (ctxt->b) {
9335 case 0x33: /* RDPMC */
9336 return true;
9337 }
9338 break;
9339 }
9340
9341 return false;
9342 }
9343
is_soft_int_instruction(struct x86_emulate_ctxt * ctxt,int emulation_type)9344 static bool is_soft_int_instruction(struct x86_emulate_ctxt *ctxt,
9345 int emulation_type)
9346 {
9347 u8 vector = EMULTYPE_GET_SOFT_INT_VECTOR(emulation_type);
9348
9349 switch (ctxt->b) {
9350 case 0xcc:
9351 return vector == BP_VECTOR;
9352 case 0xcd:
9353 return vector == ctxt->src.val;
9354 case 0xce:
9355 return vector == OF_VECTOR;
9356 default:
9357 return false;
9358 }
9359 }
9360
9361 /*
9362 * Decode an instruction for emulation. The caller is responsible for handling
9363 * code breakpoints. Note, manually detecting code breakpoints is unnecessary
9364 * (and wrong) when emulating on an intercepted fault-like exception[*], as
9365 * code breakpoints have higher priority and thus have already been done by
9366 * hardware.
9367 *
9368 * [*] Except #MC, which is higher priority, but KVM should never emulate in
9369 * response to a machine check.
9370 */
x86_decode_emulated_instruction(struct kvm_vcpu * vcpu,int emulation_type,void * insn,int insn_len)9371 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9372 void *insn, int insn_len)
9373 {
9374 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9375 int r;
9376
9377 init_emulate_ctxt(vcpu);
9378
9379 r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
9380
9381 trace_kvm_emulate_insn_start(vcpu);
9382 ++vcpu->stat.insn_emulation;
9383
9384 return r;
9385 }
9386 EXPORT_SYMBOL_FOR_KVM_INTERNAL(x86_decode_emulated_instruction);
9387
x86_emulate_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type,void * insn,int insn_len)9388 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9389 int emulation_type, void *insn, int insn_len)
9390 {
9391 int r;
9392 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9393 bool writeback = true;
9394
9395 if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9396 (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
9397 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
9398 emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
9399
9400 r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
9401 if (r != X86EMUL_CONTINUE) {
9402 if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9403 return 1;
9404
9405 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9406 emulation_type))
9407 return 1;
9408
9409 if (r == X86EMUL_UNHANDLEABLE_VECTORING) {
9410 kvm_prepare_event_vectoring_exit(vcpu, cr2_or_gpa);
9411 return 0;
9412 }
9413
9414 WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9415 return handle_emulation_failure(vcpu, emulation_type);
9416 }
9417
9418 kvm_request_l1tf_flush_l1d();
9419
9420 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
9421 kvm_clear_exception_queue(vcpu);
9422
9423 /*
9424 * Return immediately if RIP hits a code breakpoint, such #DBs
9425 * are fault-like and are higher priority than any faults on
9426 * the code fetch itself.
9427 */
9428 if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
9429 return r;
9430
9431 r = x86_decode_emulated_instruction(vcpu, emulation_type,
9432 insn, insn_len);
9433 if (r != EMULATION_OK) {
9434 if ((emulation_type & EMULTYPE_TRAP_UD) ||
9435 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9436 kvm_queue_exception(vcpu, UD_VECTOR);
9437 return 1;
9438 }
9439 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9440 emulation_type))
9441 return 1;
9442
9443 if (ctxt->have_exception &&
9444 !(emulation_type & EMULTYPE_SKIP)) {
9445 /*
9446 * #UD should result in just EMULATION_FAILED, and trap-like
9447 * exception should not be encountered during decode.
9448 */
9449 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9450 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
9451 inject_emulated_exception(vcpu);
9452 return 1;
9453 }
9454 return handle_emulation_failure(vcpu, emulation_type);
9455 }
9456 }
9457
9458 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9459 !is_vmware_backdoor_opcode(ctxt)) {
9460 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9461 return 1;
9462 }
9463
9464 /*
9465 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9466 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9467 * The caller is responsible for updating interruptibility state and
9468 * injecting single-step #DBs.
9469 */
9470 if (emulation_type & EMULTYPE_SKIP) {
9471 if (emulation_type & EMULTYPE_SKIP_SOFT_INT &&
9472 !is_soft_int_instruction(ctxt, emulation_type))
9473 return 0;
9474
9475 if (ctxt->mode != X86EMUL_MODE_PROT64)
9476 ctxt->eip = (u32)ctxt->_eip;
9477 else
9478 ctxt->eip = ctxt->_eip;
9479
9480 if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9481 r = 1;
9482 goto writeback;
9483 }
9484
9485 kvm_rip_write(vcpu, ctxt->eip);
9486 if (ctxt->eflags & X86_EFLAGS_RF)
9487 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
9488 return 1;
9489 }
9490
9491 /*
9492 * If emulation was caused by a write-protection #PF on a non-page_table
9493 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
9494 * and retry the instruction, as the vCPU is likely no longer using the
9495 * gfn as a page table.
9496 */
9497 if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9498 !x86_page_table_writing_insn(ctxt) &&
9499 kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
9500 return 1;
9501
9502 /* this is needed for vmware backdoor interface to work since it
9503 changes registers values during IO operation */
9504 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9505 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9506 emulator_invalidate_register_cache(ctxt);
9507 }
9508
9509 restart:
9510 if (emulation_type & EMULTYPE_PF) {
9511 /* Save the faulting GPA (cr2) in the address field */
9512 ctxt->exception.address = cr2_or_gpa;
9513
9514 /* With shadow page tables, cr2 contains a GVA or nGPA. */
9515 if (vcpu->arch.mmu->root_role.direct) {
9516 ctxt->gpa_available = true;
9517 ctxt->gpa_val = cr2_or_gpa;
9518 }
9519 } else {
9520 /* Sanitize the address out of an abundance of paranoia. */
9521 ctxt->exception.address = 0;
9522 }
9523
9524 /*
9525 * Check L1's instruction intercepts when emulating instructions for
9526 * L2, unless KVM is re-emulating a previously decoded instruction,
9527 * e.g. to complete userspace I/O, in which case KVM has already
9528 * checked the intercepts.
9529 */
9530 r = x86_emulate_insn(ctxt, is_guest_mode(vcpu) &&
9531 !(emulation_type & EMULTYPE_NO_DECODE));
9532
9533 if (r == EMULATION_INTERCEPTED)
9534 return 1;
9535
9536 if (r == EMULATION_FAILED) {
9537 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9538 emulation_type))
9539 return 1;
9540
9541 return handle_emulation_failure(vcpu, emulation_type);
9542 }
9543
9544 if (ctxt->have_exception) {
9545 WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9546 vcpu->mmio_needed = false;
9547 r = 1;
9548 inject_emulated_exception(vcpu);
9549 } else if (vcpu->arch.pio.count) {
9550 if (!vcpu->arch.pio.in) {
9551 /* FIXME: return into emulator if single-stepping. */
9552 vcpu->arch.pio.count = 0;
9553 } else {
9554 writeback = false;
9555 vcpu->arch.complete_userspace_io = complete_emulated_pio;
9556 }
9557 r = 0;
9558 } else if (vcpu->mmio_needed) {
9559 ++vcpu->stat.mmio_exits;
9560
9561 if (!vcpu->mmio_is_write)
9562 writeback = false;
9563 r = 0;
9564 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9565 } else if (vcpu->arch.complete_userspace_io) {
9566 writeback = false;
9567 r = 0;
9568 } else if (r == EMULATION_RESTART)
9569 goto restart;
9570 else
9571 r = 1;
9572
9573 writeback:
9574 if (writeback) {
9575 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9576 toggle_interruptibility(vcpu, ctxt->interruptibility);
9577 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9578
9579 /*
9580 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9581 * only supports code breakpoints and general detect #DB, both
9582 * of which are fault-like.
9583 */
9584 if (!ctxt->have_exception ||
9585 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9586 kvm_pmu_instruction_retired(vcpu);
9587 if (ctxt->is_branch)
9588 kvm_pmu_branch_retired(vcpu);
9589 kvm_rip_write(vcpu, ctxt->eip);
9590 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9591 r = kvm_vcpu_do_singlestep(vcpu);
9592 kvm_x86_call(update_emulated_instruction)(vcpu);
9593 __kvm_set_rflags(vcpu, ctxt->eflags);
9594 }
9595
9596 /*
9597 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9598 * do nothing, and it will be requested again as soon as
9599 * the shadow expires. But we still need to check here,
9600 * because POPF has no interrupt shadow.
9601 */
9602 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9603 kvm_make_request(KVM_REQ_EVENT, vcpu);
9604 } else
9605 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9606
9607 return r;
9608 }
9609
kvm_emulate_instruction(struct kvm_vcpu * vcpu,int emulation_type)9610 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9611 {
9612 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9613 }
9614 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction);
9615
kvm_emulate_instruction_from_buffer(struct kvm_vcpu * vcpu,void * insn,int insn_len)9616 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9617 void *insn, int insn_len)
9618 {
9619 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9620 }
9621 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction_from_buffer);
9622
complete_fast_pio_out_port_0x7e(struct kvm_vcpu * vcpu)9623 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9624 {
9625 vcpu->arch.pio.count = 0;
9626 return 1;
9627 }
9628
complete_fast_pio_out(struct kvm_vcpu * vcpu)9629 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9630 {
9631 vcpu->arch.pio.count = 0;
9632
9633 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip)))
9634 return 1;
9635
9636 return kvm_skip_emulated_instruction(vcpu);
9637 }
9638
kvm_fast_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port)9639 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9640 unsigned short port)
9641 {
9642 unsigned long val = kvm_rax_read(vcpu);
9643 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9644
9645 if (ret)
9646 return ret;
9647
9648 /*
9649 * Workaround userspace that relies on old KVM behavior of %rip being
9650 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9651 */
9652 if (port == 0x7e &&
9653 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9654 vcpu->arch.complete_userspace_io =
9655 complete_fast_pio_out_port_0x7e;
9656 kvm_skip_emulated_instruction(vcpu);
9657 } else {
9658 vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9659 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9660 }
9661 return 0;
9662 }
9663
complete_fast_pio_in(struct kvm_vcpu * vcpu)9664 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9665 {
9666 unsigned long val;
9667
9668 /* We should only ever be called with arch.pio.count equal to 1 */
9669 BUG_ON(vcpu->arch.pio.count != 1);
9670
9671 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip))) {
9672 vcpu->arch.pio.count = 0;
9673 return 1;
9674 }
9675
9676 /* For size less than 4 we merge, else we zero extend */
9677 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9678
9679 complete_emulator_pio_in(vcpu, &val);
9680 kvm_rax_write(vcpu, val);
9681
9682 return kvm_skip_emulated_instruction(vcpu);
9683 }
9684
kvm_fast_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port)9685 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9686 unsigned short port)
9687 {
9688 unsigned long val;
9689 int ret;
9690
9691 /* For size less than 4 we merge, else we zero extend */
9692 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9693
9694 ret = emulator_pio_in(vcpu, size, port, &val, 1);
9695 if (ret) {
9696 kvm_rax_write(vcpu, val);
9697 return ret;
9698 }
9699
9700 vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9701 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9702
9703 return 0;
9704 }
9705
kvm_fast_pio(struct kvm_vcpu * vcpu,int size,unsigned short port,int in)9706 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9707 {
9708 int ret;
9709
9710 if (in)
9711 ret = kvm_fast_pio_in(vcpu, size, port);
9712 else
9713 ret = kvm_fast_pio_out(vcpu, size, port);
9714 return ret && kvm_skip_emulated_instruction(vcpu);
9715 }
9716 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fast_pio);
9717
kvmclock_cpu_down_prep(unsigned int cpu)9718 static int kvmclock_cpu_down_prep(unsigned int cpu)
9719 {
9720 __this_cpu_write(cpu_tsc_khz, 0);
9721 return 0;
9722 }
9723
tsc_khz_changed(void * data)9724 static void tsc_khz_changed(void *data)
9725 {
9726 struct cpufreq_freqs *freq = data;
9727 unsigned long khz;
9728
9729 WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9730
9731 if (data)
9732 khz = freq->new;
9733 else
9734 khz = cpufreq_quick_get(raw_smp_processor_id());
9735 if (!khz)
9736 khz = tsc_khz;
9737 __this_cpu_write(cpu_tsc_khz, khz);
9738 }
9739
9740 #ifdef CONFIG_X86_64
kvm_hyperv_tsc_notifier(void)9741 static void kvm_hyperv_tsc_notifier(void)
9742 {
9743 struct kvm *kvm;
9744 int cpu;
9745
9746 mutex_lock(&kvm_lock);
9747 list_for_each_entry(kvm, &vm_list, vm_list)
9748 kvm_make_mclock_inprogress_request(kvm);
9749
9750 /* no guest entries from this point */
9751 hyperv_stop_tsc_emulation();
9752
9753 /* TSC frequency always matches when on Hyper-V */
9754 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9755 for_each_present_cpu(cpu)
9756 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9757 }
9758 kvm_caps.max_guest_tsc_khz = tsc_khz;
9759
9760 list_for_each_entry(kvm, &vm_list, vm_list) {
9761 __kvm_start_pvclock_update(kvm);
9762 pvclock_update_vm_gtod_copy(kvm);
9763 kvm_end_pvclock_update(kvm);
9764 }
9765
9766 mutex_unlock(&kvm_lock);
9767 }
9768 #endif
9769
__kvmclock_cpufreq_notifier(struct cpufreq_freqs * freq,int cpu)9770 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9771 {
9772 struct kvm *kvm;
9773 struct kvm_vcpu *vcpu;
9774 int send_ipi = 0;
9775 unsigned long i;
9776
9777 /*
9778 * We allow guests to temporarily run on slowing clocks,
9779 * provided we notify them after, or to run on accelerating
9780 * clocks, provided we notify them before. Thus time never
9781 * goes backwards.
9782 *
9783 * However, we have a problem. We can't atomically update
9784 * the frequency of a given CPU from this function; it is
9785 * merely a notifier, which can be called from any CPU.
9786 * Changing the TSC frequency at arbitrary points in time
9787 * requires a recomputation of local variables related to
9788 * the TSC for each VCPU. We must flag these local variables
9789 * to be updated and be sure the update takes place with the
9790 * new frequency before any guests proceed.
9791 *
9792 * Unfortunately, the combination of hotplug CPU and frequency
9793 * change creates an intractable locking scenario; the order
9794 * of when these callouts happen is undefined with respect to
9795 * CPU hotplug, and they can race with each other. As such,
9796 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9797 * undefined; you can actually have a CPU frequency change take
9798 * place in between the computation of X and the setting of the
9799 * variable. To protect against this problem, all updates of
9800 * the per_cpu tsc_khz variable are done in an interrupt
9801 * protected IPI, and all callers wishing to update the value
9802 * must wait for a synchronous IPI to complete (which is trivial
9803 * if the caller is on the CPU already). This establishes the
9804 * necessary total order on variable updates.
9805 *
9806 * Note that because a guest time update may take place
9807 * anytime after the setting of the VCPU's request bit, the
9808 * correct TSC value must be set before the request. However,
9809 * to ensure the update actually makes it to any guest which
9810 * starts running in hardware virtualization between the set
9811 * and the acquisition of the spinlock, we must also ping the
9812 * CPU after setting the request bit.
9813 *
9814 */
9815
9816 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9817
9818 mutex_lock(&kvm_lock);
9819 list_for_each_entry(kvm, &vm_list, vm_list) {
9820 kvm_for_each_vcpu(i, vcpu, kvm) {
9821 if (vcpu->cpu != cpu)
9822 continue;
9823 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9824 if (vcpu->cpu != raw_smp_processor_id())
9825 send_ipi = 1;
9826 }
9827 }
9828 mutex_unlock(&kvm_lock);
9829
9830 if (freq->old < freq->new && send_ipi) {
9831 /*
9832 * We upscale the frequency. Must make the guest
9833 * doesn't see old kvmclock values while running with
9834 * the new frequency, otherwise we risk the guest sees
9835 * time go backwards.
9836 *
9837 * In case we update the frequency for another cpu
9838 * (which might be in guest context) send an interrupt
9839 * to kick the cpu out of guest context. Next time
9840 * guest context is entered kvmclock will be updated,
9841 * so the guest will not see stale values.
9842 */
9843 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9844 }
9845 }
9846
kvmclock_cpufreq_notifier(struct notifier_block * nb,unsigned long val,void * data)9847 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9848 void *data)
9849 {
9850 struct cpufreq_freqs *freq = data;
9851 int cpu;
9852
9853 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9854 return 0;
9855 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9856 return 0;
9857
9858 for_each_cpu(cpu, freq->policy->cpus)
9859 __kvmclock_cpufreq_notifier(freq, cpu);
9860
9861 return 0;
9862 }
9863
9864 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9865 .notifier_call = kvmclock_cpufreq_notifier
9866 };
9867
kvmclock_cpu_online(unsigned int cpu)9868 static int kvmclock_cpu_online(unsigned int cpu)
9869 {
9870 tsc_khz_changed(NULL);
9871 return 0;
9872 }
9873
kvm_timer_init(void)9874 static void kvm_timer_init(void)
9875 {
9876 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9877 max_tsc_khz = tsc_khz;
9878
9879 if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9880 struct cpufreq_policy *policy;
9881 int cpu;
9882
9883 cpu = get_cpu();
9884 policy = cpufreq_cpu_get(cpu);
9885 if (policy) {
9886 if (policy->cpuinfo.max_freq)
9887 max_tsc_khz = policy->cpuinfo.max_freq;
9888 cpufreq_cpu_put(policy);
9889 }
9890 put_cpu();
9891 }
9892 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9893 CPUFREQ_TRANSITION_NOTIFIER);
9894
9895 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9896 kvmclock_cpu_online, kvmclock_cpu_down_prep);
9897 }
9898 }
9899
9900 #ifdef CONFIG_X86_64
pvclock_gtod_update_fn(struct work_struct * work)9901 static void pvclock_gtod_update_fn(struct work_struct *work)
9902 {
9903 struct kvm *kvm;
9904 struct kvm_vcpu *vcpu;
9905 unsigned long i;
9906
9907 mutex_lock(&kvm_lock);
9908 list_for_each_entry(kvm, &vm_list, vm_list)
9909 kvm_for_each_vcpu(i, vcpu, kvm)
9910 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9911 atomic_set(&kvm_guest_has_master_clock, 0);
9912 mutex_unlock(&kvm_lock);
9913 }
9914
9915 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9916
9917 /*
9918 * Indirection to move queue_work() out of the tk_core.seq write held
9919 * region to prevent possible deadlocks against time accessors which
9920 * are invoked with work related locks held.
9921 */
pvclock_irq_work_fn(struct irq_work * w)9922 static void pvclock_irq_work_fn(struct irq_work *w)
9923 {
9924 queue_work(system_long_wq, &pvclock_gtod_work);
9925 }
9926
9927 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9928
9929 /*
9930 * Notification about pvclock gtod data update.
9931 */
pvclock_gtod_notify(struct notifier_block * nb,unsigned long unused,void * priv)9932 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9933 void *priv)
9934 {
9935 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9936 struct timekeeper *tk = priv;
9937
9938 update_pvclock_gtod(tk);
9939
9940 /*
9941 * Disable master clock if host does not trust, or does not use,
9942 * TSC based clocksource. Delegate queue_work() to irq_work as
9943 * this is invoked with tk_core.seq write held.
9944 */
9945 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9946 atomic_read(&kvm_guest_has_master_clock) != 0)
9947 irq_work_queue(&pvclock_irq_work);
9948 return 0;
9949 }
9950
9951 static struct notifier_block pvclock_gtod_notifier = {
9952 .notifier_call = pvclock_gtod_notify,
9953 };
9954 #endif
9955
kvm_ops_update(struct kvm_x86_init_ops * ops)9956 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
9957 {
9958 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9959
9960 #define __KVM_X86_OP(func) \
9961 static_call_update(kvm_x86_##func, kvm_x86_ops.func);
9962 #define KVM_X86_OP(func) \
9963 WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
9964 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
9965 #define KVM_X86_OP_OPTIONAL_RET0(func) \
9966 static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
9967 (void *)__static_call_return0);
9968 #include <asm/kvm-x86-ops.h>
9969 #undef __KVM_X86_OP
9970
9971 kvm_pmu_ops_update(ops->pmu_ops);
9972 }
9973
kvm_x86_check_processor_compatibility(void)9974 static int kvm_x86_check_processor_compatibility(void)
9975 {
9976 int cpu = smp_processor_id();
9977 struct cpuinfo_x86 *c = &cpu_data(cpu);
9978
9979 /*
9980 * Compatibility checks are done when loading KVM and when enabling
9981 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
9982 * compatible, i.e. KVM should never perform a compatibility check on
9983 * an offline CPU.
9984 */
9985 WARN_ON(!cpu_online(cpu));
9986
9987 if (__cr4_reserved_bits(cpu_has, c) !=
9988 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9989 return -EIO;
9990
9991 return kvm_x86_call(check_processor_compatibility)();
9992 }
9993
kvm_x86_check_cpu_compat(void * ret)9994 static void kvm_x86_check_cpu_compat(void *ret)
9995 {
9996 *(int *)ret = kvm_x86_check_processor_compatibility();
9997 }
9998
kvm_x86_vendor_init(struct kvm_x86_init_ops * ops)9999 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
10000 {
10001 u64 host_pat;
10002 int r, cpu;
10003
10004 guard(mutex)(&vendor_module_lock);
10005
10006 if (kvm_x86_ops.enable_virtualization_cpu) {
10007 pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
10008 return -EEXIST;
10009 }
10010
10011 /*
10012 * KVM explicitly assumes that the guest has an FPU and
10013 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
10014 * vCPU's FPU state as a fxregs_state struct.
10015 */
10016 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
10017 pr_err("inadequate fpu\n");
10018 return -EOPNOTSUPP;
10019 }
10020
10021 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
10022 pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
10023 return -EOPNOTSUPP;
10024 }
10025
10026 /*
10027 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
10028 * the PAT bits in SPTEs. Bail if PAT[0] is programmed to something
10029 * other than WB. Note, EPT doesn't utilize the PAT, but don't bother
10030 * with an exception. PAT[0] is set to WB on RESET and also by the
10031 * kernel, i.e. failure indicates a kernel bug or broken firmware.
10032 */
10033 if (rdmsrq_safe(MSR_IA32_CR_PAT, &host_pat) ||
10034 (host_pat & GENMASK(2, 0)) != 6) {
10035 pr_err("host PAT[0] is not WB\n");
10036 return -EIO;
10037 }
10038
10039 if (boot_cpu_has(X86_FEATURE_SHSTK) || boot_cpu_has(X86_FEATURE_IBT)) {
10040 rdmsrq(MSR_IA32_S_CET, kvm_host.s_cet);
10041 /*
10042 * Linux doesn't yet support supervisor shadow stacks (SSS), so
10043 * KVM doesn't save/restore the associated MSRs, i.e. KVM may
10044 * clobber the host values. Yell and refuse to load if SSS is
10045 * unexpectedly enabled, e.g. to avoid crashing the host.
10046 */
10047 if (WARN_ON_ONCE(kvm_host.s_cet & CET_SHSTK_EN))
10048 return -EIO;
10049 }
10050
10051 memset(&kvm_caps, 0, sizeof(kvm_caps));
10052
10053 x86_emulator_cache = kvm_alloc_emulator_cache();
10054 if (!x86_emulator_cache) {
10055 pr_err("failed to allocate cache for x86 emulator\n");
10056 return -ENOMEM;
10057 }
10058
10059 r = kvm_mmu_vendor_module_init();
10060 if (r)
10061 goto out_free_x86_emulator_cache;
10062
10063 kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
10064 kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
10065
10066 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
10067 kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
10068 kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
10069 }
10070
10071 if (boot_cpu_has(X86_FEATURE_XSAVES)) {
10072 rdmsrq(MSR_IA32_XSS, kvm_host.xss);
10073 kvm_caps.supported_xss = kvm_host.xss & KVM_SUPPORTED_XSS;
10074 }
10075
10076 kvm_caps.supported_quirks = KVM_X86_VALID_QUIRKS;
10077 kvm_caps.inapplicable_quirks = KVM_X86_CONDITIONAL_QUIRKS;
10078
10079 rdmsrq_safe(MSR_EFER, &kvm_host.efer);
10080
10081 kvm_init_pmu_capability(ops->pmu_ops);
10082
10083 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
10084 rdmsrq(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
10085
10086 WARN_ON_ONCE(kvm_nr_uret_msrs);
10087
10088 r = ops->hardware_setup();
10089 if (r != 0)
10090 goto out_mmu_exit;
10091
10092 enable_device_posted_irqs &= enable_apicv &&
10093 irq_remapping_cap(IRQ_POSTING_CAP);
10094
10095 kvm_ops_update(ops);
10096
10097 for_each_online_cpu(cpu) {
10098 smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
10099 if (r < 0)
10100 goto out_unwind_ops;
10101 }
10102
10103 /*
10104 * Point of no return! DO NOT add error paths below this point unless
10105 * absolutely necessary, as most operations from this point forward
10106 * require unwinding.
10107 */
10108 kvm_timer_init();
10109
10110 if (pi_inject_timer == -1)
10111 pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
10112 #ifdef CONFIG_X86_64
10113 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
10114
10115 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
10116 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
10117 #endif
10118
10119 kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
10120
10121 if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
10122 kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
10123
10124 /* KVM always ignores guest PAT for shadow paging. */
10125 if (!tdp_enabled)
10126 kvm_caps.supported_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT;
10127
10128 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
10129 kvm_caps.supported_xss = 0;
10130
10131 if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
10132 !kvm_cpu_cap_has(X86_FEATURE_IBT))
10133 kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
10134
10135 if ((kvm_caps.supported_xss & XFEATURE_MASK_CET_ALL) != XFEATURE_MASK_CET_ALL) {
10136 kvm_cpu_cap_clear(X86_FEATURE_SHSTK);
10137 kvm_cpu_cap_clear(X86_FEATURE_IBT);
10138 kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
10139 }
10140
10141 if (kvm_caps.has_tsc_control) {
10142 /*
10143 * Make sure the user can only configure tsc_khz values that
10144 * fit into a signed integer.
10145 * A min value is not calculated because it will always
10146 * be 1 on all machines.
10147 */
10148 u64 max = min(0x7fffffffULL,
10149 __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
10150 kvm_caps.max_guest_tsc_khz = max;
10151 }
10152 kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
10153 kvm_init_msr_lists();
10154 return 0;
10155
10156 out_unwind_ops:
10157 kvm_x86_ops.enable_virtualization_cpu = NULL;
10158 kvm_x86_call(hardware_unsetup)();
10159 out_mmu_exit:
10160 kvm_destroy_user_return_msrs();
10161 kvm_mmu_vendor_module_exit();
10162 out_free_x86_emulator_cache:
10163 kmem_cache_destroy(x86_emulator_cache);
10164 return r;
10165 }
10166 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_init);
10167
kvm_x86_vendor_exit(void)10168 void kvm_x86_vendor_exit(void)
10169 {
10170 kvm_unregister_perf_callbacks();
10171
10172 #ifdef CONFIG_X86_64
10173 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
10174 clear_hv_tscchange_cb();
10175 #endif
10176 kvm_lapic_exit();
10177
10178 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
10179 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
10180 CPUFREQ_TRANSITION_NOTIFIER);
10181 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
10182 }
10183 #ifdef CONFIG_X86_64
10184 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
10185 irq_work_sync(&pvclock_irq_work);
10186 cancel_work_sync(&pvclock_gtod_work);
10187 #endif
10188 kvm_x86_call(hardware_unsetup)();
10189 kvm_destroy_user_return_msrs();
10190 kvm_mmu_vendor_module_exit();
10191 kmem_cache_destroy(x86_emulator_cache);
10192 #ifdef CONFIG_KVM_XEN
10193 static_key_deferred_flush(&kvm_xen_enabled);
10194 WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
10195 #endif
10196 mutex_lock(&vendor_module_lock);
10197 kvm_x86_ops.enable_virtualization_cpu = NULL;
10198 mutex_unlock(&vendor_module_lock);
10199 }
10200 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_exit);
10201
10202 #ifdef CONFIG_X86_64
kvm_pv_clock_pairing(struct kvm_vcpu * vcpu,gpa_t paddr,unsigned long clock_type)10203 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
10204 unsigned long clock_type)
10205 {
10206 struct kvm_clock_pairing clock_pairing;
10207 struct timespec64 ts;
10208 u64 cycle;
10209 int ret;
10210
10211 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
10212 return -KVM_EOPNOTSUPP;
10213
10214 /*
10215 * When tsc is in permanent catchup mode guests won't be able to use
10216 * pvclock_read_retry loop to get consistent view of pvclock
10217 */
10218 if (vcpu->arch.tsc_always_catchup)
10219 return -KVM_EOPNOTSUPP;
10220
10221 if (!kvm_get_walltime_and_clockread(&ts, &cycle))
10222 return -KVM_EOPNOTSUPP;
10223
10224 clock_pairing.sec = ts.tv_sec;
10225 clock_pairing.nsec = ts.tv_nsec;
10226 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
10227 clock_pairing.flags = 0;
10228 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
10229
10230 ret = 0;
10231 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
10232 sizeof(struct kvm_clock_pairing)))
10233 ret = -KVM_EFAULT;
10234
10235 return ret;
10236 }
10237 #endif
10238
10239 /*
10240 * kvm_pv_kick_cpu_op: Kick a vcpu.
10241 *
10242 * @apicid - apicid of vcpu to be kicked.
10243 */
kvm_pv_kick_cpu_op(struct kvm * kvm,int apicid)10244 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
10245 {
10246 /*
10247 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
10248 * common code, e.g. for tracing. Defer initialization to the compiler.
10249 */
10250 struct kvm_lapic_irq lapic_irq = {
10251 .delivery_mode = APIC_DM_REMRD,
10252 .dest_mode = APIC_DEST_PHYSICAL,
10253 .shorthand = APIC_DEST_NOSHORT,
10254 .dest_id = apicid,
10255 };
10256
10257 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
10258 }
10259
kvm_apicv_activated(struct kvm * kvm)10260 bool kvm_apicv_activated(struct kvm *kvm)
10261 {
10262 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
10263 }
10264 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_apicv_activated);
10265
kvm_vcpu_apicv_activated(struct kvm_vcpu * vcpu)10266 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
10267 {
10268 ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
10269 ulong vcpu_reasons =
10270 kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
10271
10272 return (vm_reasons | vcpu_reasons) == 0;
10273 }
10274 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_apicv_activated);
10275
set_or_clear_apicv_inhibit(unsigned long * inhibits,enum kvm_apicv_inhibit reason,bool set)10276 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
10277 enum kvm_apicv_inhibit reason, bool set)
10278 {
10279 const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
10280
10281 BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
10282
10283 if (set)
10284 __set_bit(reason, inhibits);
10285 else
10286 __clear_bit(reason, inhibits);
10287
10288 trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
10289 }
10290
kvm_apicv_init(struct kvm * kvm)10291 static void kvm_apicv_init(struct kvm *kvm)
10292 {
10293 enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
10294 APICV_INHIBIT_REASON_DISABLED;
10295
10296 set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
10297
10298 init_rwsem(&kvm->arch.apicv_update_lock);
10299 }
10300
kvm_sched_yield(struct kvm_vcpu * vcpu,unsigned long dest_id)10301 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
10302 {
10303 struct kvm_vcpu *target = NULL;
10304 struct kvm_apic_map *map;
10305
10306 vcpu->stat.directed_yield_attempted++;
10307
10308 if (single_task_running())
10309 goto no_yield;
10310
10311 rcu_read_lock();
10312 map = rcu_dereference(vcpu->kvm->arch.apic_map);
10313
10314 if (likely(map) && dest_id <= map->max_apic_id) {
10315 dest_id = array_index_nospec(dest_id, map->max_apic_id + 1);
10316 if (map->phys_map[dest_id])
10317 target = map->phys_map[dest_id]->vcpu;
10318 }
10319
10320 rcu_read_unlock();
10321
10322 if (!target || !READ_ONCE(target->ready))
10323 goto no_yield;
10324
10325 /* Ignore requests to yield to self */
10326 if (vcpu == target)
10327 goto no_yield;
10328
10329 if (kvm_vcpu_yield_to(target) <= 0)
10330 goto no_yield;
10331
10332 vcpu->stat.directed_yield_successful++;
10333
10334 no_yield:
10335 return;
10336 }
10337
complete_hypercall_exit(struct kvm_vcpu * vcpu)10338 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
10339 {
10340 u64 ret = vcpu->run->hypercall.ret;
10341
10342 if (!is_64_bit_hypercall(vcpu))
10343 ret = (u32)ret;
10344 kvm_rax_write(vcpu, ret);
10345 return kvm_skip_emulated_instruction(vcpu);
10346 }
10347
____kvm_emulate_hypercall(struct kvm_vcpu * vcpu,int cpl,int (* complete_hypercall)(struct kvm_vcpu *))10348 int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
10349 int (*complete_hypercall)(struct kvm_vcpu *))
10350 {
10351 unsigned long ret;
10352 unsigned long nr = kvm_rax_read(vcpu);
10353 unsigned long a0 = kvm_rbx_read(vcpu);
10354 unsigned long a1 = kvm_rcx_read(vcpu);
10355 unsigned long a2 = kvm_rdx_read(vcpu);
10356 unsigned long a3 = kvm_rsi_read(vcpu);
10357 int op_64_bit = is_64_bit_hypercall(vcpu);
10358
10359 ++vcpu->stat.hypercalls;
10360
10361 trace_kvm_hypercall(nr, a0, a1, a2, a3);
10362
10363 if (!op_64_bit) {
10364 nr &= 0xFFFFFFFF;
10365 a0 &= 0xFFFFFFFF;
10366 a1 &= 0xFFFFFFFF;
10367 a2 &= 0xFFFFFFFF;
10368 a3 &= 0xFFFFFFFF;
10369 }
10370
10371 if (cpl) {
10372 ret = -KVM_EPERM;
10373 goto out;
10374 }
10375
10376 ret = -KVM_ENOSYS;
10377
10378 switch (nr) {
10379 case KVM_HC_VAPIC_POLL_IRQ:
10380 ret = 0;
10381 break;
10382 case KVM_HC_KICK_CPU:
10383 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10384 break;
10385
10386 kvm_pv_kick_cpu_op(vcpu->kvm, a1);
10387 kvm_sched_yield(vcpu, a1);
10388 ret = 0;
10389 break;
10390 #ifdef CONFIG_X86_64
10391 case KVM_HC_CLOCK_PAIRING:
10392 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10393 break;
10394 #endif
10395 case KVM_HC_SEND_IPI:
10396 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10397 break;
10398
10399 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10400 break;
10401 case KVM_HC_SCHED_YIELD:
10402 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10403 break;
10404
10405 kvm_sched_yield(vcpu, a0);
10406 ret = 0;
10407 break;
10408 case KVM_HC_MAP_GPA_RANGE: {
10409 u64 gpa = a0, npages = a1, attrs = a2;
10410
10411 ret = -KVM_ENOSYS;
10412 if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE))
10413 break;
10414
10415 if (!PAGE_ALIGNED(gpa) || !npages ||
10416 gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10417 ret = -KVM_EINVAL;
10418 break;
10419 }
10420
10421 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
10422 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
10423 /*
10424 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
10425 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
10426 * it was always zero on KVM_EXIT_HYPERCALL. Since KVM is now overwriting
10427 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
10428 */
10429 vcpu->run->hypercall.ret = 0;
10430 vcpu->run->hypercall.args[0] = gpa;
10431 vcpu->run->hypercall.args[1] = npages;
10432 vcpu->run->hypercall.args[2] = attrs;
10433 vcpu->run->hypercall.flags = 0;
10434 if (op_64_bit)
10435 vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10436
10437 WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
10438 vcpu->arch.complete_userspace_io = complete_hypercall;
10439 return 0;
10440 }
10441 default:
10442 ret = -KVM_ENOSYS;
10443 break;
10444 }
10445
10446 out:
10447 vcpu->run->hypercall.ret = ret;
10448 return 1;
10449 }
10450 EXPORT_SYMBOL_FOR_KVM_INTERNAL(____kvm_emulate_hypercall);
10451
kvm_emulate_hypercall(struct kvm_vcpu * vcpu)10452 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10453 {
10454 if (kvm_xen_hypercall_enabled(vcpu->kvm))
10455 return kvm_xen_hypercall(vcpu);
10456
10457 if (kvm_hv_hypercall_enabled(vcpu))
10458 return kvm_hv_hypercall(vcpu);
10459
10460 return __kvm_emulate_hypercall(vcpu, kvm_x86_call(get_cpl)(vcpu),
10461 complete_hypercall_exit);
10462 }
10463 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_hypercall);
10464
emulator_fix_hypercall(struct x86_emulate_ctxt * ctxt)10465 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
10466 {
10467 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
10468 char instruction[3];
10469 unsigned long rip = kvm_rip_read(vcpu);
10470
10471 /*
10472 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10473 * the pieces.
10474 */
10475 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10476 ctxt->exception.error_code_valid = false;
10477 ctxt->exception.vector = UD_VECTOR;
10478 ctxt->have_exception = true;
10479 return X86EMUL_PROPAGATE_FAULT;
10480 }
10481
10482 kvm_x86_call(patch_hypercall)(vcpu, instruction);
10483
10484 return emulator_write_emulated(ctxt, rip, instruction, 3,
10485 &ctxt->exception);
10486 }
10487
dm_request_for_irq_injection(struct kvm_vcpu * vcpu)10488 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
10489 {
10490 return vcpu->run->request_interrupt_window &&
10491 likely(!pic_in_kernel(vcpu->kvm));
10492 }
10493
10494 /* Called within kvm->srcu read side. */
post_kvm_run_save(struct kvm_vcpu * vcpu)10495 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
10496 {
10497 struct kvm_run *kvm_run = vcpu->run;
10498
10499 kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
10500 kvm_run->cr8 = kvm_get_cr8(vcpu);
10501 kvm_run->apic_base = vcpu->arch.apic_base;
10502
10503 kvm_run->ready_for_interrupt_injection =
10504 pic_in_kernel(vcpu->kvm) ||
10505 kvm_vcpu_ready_for_interrupt_injection(vcpu);
10506
10507 if (is_smm(vcpu))
10508 kvm_run->flags |= KVM_RUN_X86_SMM;
10509 if (is_guest_mode(vcpu))
10510 kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
10511 }
10512
update_cr8_intercept(struct kvm_vcpu * vcpu)10513 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10514 {
10515 int max_irr, tpr;
10516
10517 if (!kvm_x86_ops.update_cr8_intercept)
10518 return;
10519
10520 if (!lapic_in_kernel(vcpu))
10521 return;
10522
10523 if (vcpu->arch.apic->apicv_active)
10524 return;
10525
10526 if (!vcpu->arch.apic->vapic_addr)
10527 max_irr = kvm_lapic_find_highest_irr(vcpu);
10528 else
10529 max_irr = -1;
10530
10531 if (max_irr != -1)
10532 max_irr >>= 4;
10533
10534 tpr = kvm_lapic_get_cr8(vcpu);
10535
10536 kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
10537 }
10538
10539
kvm_check_nested_events(struct kvm_vcpu * vcpu)10540 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10541 {
10542 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10543 kvm_x86_ops.nested_ops->triple_fault(vcpu);
10544 return 1;
10545 }
10546
10547 return kvm_x86_ops.nested_ops->check_events(vcpu);
10548 }
10549
kvm_inject_exception(struct kvm_vcpu * vcpu)10550 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10551 {
10552 /*
10553 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10554 * exceptions don't report error codes. The presence of an error code
10555 * is carried with the exception and only stripped when the exception
10556 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10557 * report an error code despite the CPU being in Real Mode.
10558 */
10559 vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10560
10561 trace_kvm_inj_exception(vcpu->arch.exception.vector,
10562 vcpu->arch.exception.has_error_code,
10563 vcpu->arch.exception.error_code,
10564 vcpu->arch.exception.injected);
10565
10566 kvm_x86_call(inject_exception)(vcpu);
10567 }
10568
10569 /*
10570 * Check for any event (interrupt or exception) that is ready to be injected,
10571 * and if there is at least one event, inject the event with the highest
10572 * priority. This handles both "pending" events, i.e. events that have never
10573 * been injected into the guest, and "injected" events, i.e. events that were
10574 * injected as part of a previous VM-Enter, but weren't successfully delivered
10575 * and need to be re-injected.
10576 *
10577 * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10578 * i.e. doesn't guarantee that there's an event window in the guest. KVM must
10579 * be able to inject exceptions in the "middle" of an instruction, and so must
10580 * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10581 * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10582 * boundaries is necessary and correct.
10583 *
10584 * For simplicity, KVM uses a single path to inject all events (except events
10585 * that are injected directly from L1 to L2) and doesn't explicitly track
10586 * instruction boundaries for asynchronous events. However, because VM-Exits
10587 * that can occur during instruction execution typically result in KVM skipping
10588 * the instruction or injecting an exception, e.g. instruction and exception
10589 * intercepts, and because pending exceptions have higher priority than pending
10590 * interrupts, KVM still honors instruction boundaries in most scenarios.
10591 *
10592 * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10593 * the instruction or inject an exception, then KVM can incorrecty inject a new
10594 * asynchronous event if the event became pending after the CPU fetched the
10595 * instruction (in the guest). E.g. if a page fault (#PF, #NPF, EPT violation)
10596 * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10597 * injected on the restarted instruction instead of being deferred until the
10598 * instruction completes.
10599 *
10600 * In practice, this virtualization hole is unlikely to be observed by the
10601 * guest, and even less likely to cause functional problems. To detect the
10602 * hole, the guest would have to trigger an event on a side effect of an early
10603 * phase of instruction execution, e.g. on the instruction fetch from memory.
10604 * And for it to be a functional problem, the guest would need to depend on the
10605 * ordering between that side effect, the instruction completing, _and_ the
10606 * delivery of the asynchronous event.
10607 */
kvm_check_and_inject_events(struct kvm_vcpu * vcpu,bool * req_immediate_exit)10608 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10609 bool *req_immediate_exit)
10610 {
10611 bool can_inject;
10612 int r;
10613
10614 /*
10615 * Process nested events first, as nested VM-Exit supersedes event
10616 * re-injection. If there's an event queued for re-injection, it will
10617 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10618 */
10619 if (is_guest_mode(vcpu))
10620 r = kvm_check_nested_events(vcpu);
10621 else
10622 r = 0;
10623
10624 /*
10625 * Re-inject exceptions and events *especially* if immediate entry+exit
10626 * to/from L2 is needed, as any event that has already been injected
10627 * into L2 needs to complete its lifecycle before injecting a new event.
10628 *
10629 * Don't re-inject an NMI or interrupt if there is a pending exception.
10630 * This collision arises if an exception occurred while vectoring the
10631 * injected event, KVM intercepted said exception, and KVM ultimately
10632 * determined the fault belongs to the guest and queues the exception
10633 * for injection back into the guest.
10634 *
10635 * "Injected" interrupts can also collide with pending exceptions if
10636 * userspace ignores the "ready for injection" flag and blindly queues
10637 * an interrupt. In that case, prioritizing the exception is correct,
10638 * as the exception "occurred" before the exit to userspace. Trap-like
10639 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10640 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10641 * priority, they're only generated (pended) during instruction
10642 * execution, and interrupts are recognized at instruction boundaries.
10643 * Thus a pending fault-like exception means the fault occurred on the
10644 * *previous* instruction and must be serviced prior to recognizing any
10645 * new events in order to fully complete the previous instruction.
10646 */
10647 if (vcpu->arch.exception.injected)
10648 kvm_inject_exception(vcpu);
10649 else if (kvm_is_exception_pending(vcpu))
10650 ; /* see above */
10651 else if (vcpu->arch.nmi_injected)
10652 kvm_x86_call(inject_nmi)(vcpu);
10653 else if (vcpu->arch.interrupt.injected)
10654 kvm_x86_call(inject_irq)(vcpu, true);
10655
10656 /*
10657 * Exceptions that morph to VM-Exits are handled above, and pending
10658 * exceptions on top of injected exceptions that do not VM-Exit should
10659 * either morph to #DF or, sadly, override the injected exception.
10660 */
10661 WARN_ON_ONCE(vcpu->arch.exception.injected &&
10662 vcpu->arch.exception.pending);
10663
10664 /*
10665 * Bail if immediate entry+exit to/from the guest is needed to complete
10666 * nested VM-Enter or event re-injection so that a different pending
10667 * event can be serviced (or if KVM needs to exit to userspace).
10668 *
10669 * Otherwise, continue processing events even if VM-Exit occurred. The
10670 * VM-Exit will have cleared exceptions that were meant for L2, but
10671 * there may now be events that can be injected into L1.
10672 */
10673 if (r < 0)
10674 goto out;
10675
10676 /*
10677 * A pending exception VM-Exit should either result in nested VM-Exit
10678 * or force an immediate re-entry and exit to/from L2, and exception
10679 * VM-Exits cannot be injected (flag should _never_ be set).
10680 */
10681 WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10682 vcpu->arch.exception_vmexit.pending);
10683
10684 /*
10685 * New events, other than exceptions, cannot be injected if KVM needs
10686 * to re-inject a previous event. See above comments on re-injecting
10687 * for why pending exceptions get priority.
10688 */
10689 can_inject = !kvm_event_needs_reinjection(vcpu);
10690
10691 if (vcpu->arch.exception.pending) {
10692 /*
10693 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10694 * value pushed on the stack. Trap-like exception and all #DBs
10695 * leave RF as-is (KVM follows Intel's behavior in this regard;
10696 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10697 *
10698 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10699 * describe the behavior of General Detect #DBs, which are
10700 * fault-like. They do _not_ set RF, a la code breakpoints.
10701 */
10702 if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10703 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10704 X86_EFLAGS_RF);
10705
10706 if (vcpu->arch.exception.vector == DB_VECTOR) {
10707 kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
10708 if (vcpu->arch.dr7 & DR7_GD) {
10709 vcpu->arch.dr7 &= ~DR7_GD;
10710 kvm_update_dr7(vcpu);
10711 }
10712 }
10713
10714 kvm_inject_exception(vcpu);
10715
10716 vcpu->arch.exception.pending = false;
10717 vcpu->arch.exception.injected = true;
10718
10719 can_inject = false;
10720 }
10721
10722 /* Don't inject interrupts if the user asked to avoid doing so */
10723 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10724 return 0;
10725
10726 /*
10727 * Finally, inject interrupt events. If an event cannot be injected
10728 * due to architectural conditions (e.g. IF=0) a window-open exit
10729 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
10730 * and can architecturally be injected, but we cannot do it right now:
10731 * an interrupt could have arrived just now and we have to inject it
10732 * as a vmexit, or there could already an event in the queue, which is
10733 * indicated by can_inject. In that case we request an immediate exit
10734 * in order to make progress and get back here for another iteration.
10735 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10736 */
10737 #ifdef CONFIG_KVM_SMM
10738 if (vcpu->arch.smi_pending) {
10739 r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
10740 -EBUSY;
10741 if (r < 0)
10742 goto out;
10743 if (r) {
10744 vcpu->arch.smi_pending = false;
10745 ++vcpu->arch.smi_count;
10746 enter_smm(vcpu);
10747 can_inject = false;
10748 } else
10749 kvm_x86_call(enable_smi_window)(vcpu);
10750 }
10751 #endif
10752
10753 if (vcpu->arch.nmi_pending) {
10754 r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
10755 -EBUSY;
10756 if (r < 0)
10757 goto out;
10758 if (r) {
10759 --vcpu->arch.nmi_pending;
10760 vcpu->arch.nmi_injected = true;
10761 kvm_x86_call(inject_nmi)(vcpu);
10762 can_inject = false;
10763 WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
10764 }
10765 if (vcpu->arch.nmi_pending)
10766 kvm_x86_call(enable_nmi_window)(vcpu);
10767 }
10768
10769 if (kvm_cpu_has_injectable_intr(vcpu)) {
10770 r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
10771 -EBUSY;
10772 if (r < 0)
10773 goto out;
10774 if (r) {
10775 int irq = kvm_cpu_get_interrupt(vcpu);
10776
10777 if (!WARN_ON_ONCE(irq == -1)) {
10778 kvm_queue_interrupt(vcpu, irq, false);
10779 kvm_x86_call(inject_irq)(vcpu, false);
10780 WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
10781 }
10782 }
10783 if (kvm_cpu_has_injectable_intr(vcpu))
10784 kvm_x86_call(enable_irq_window)(vcpu);
10785 }
10786
10787 if (is_guest_mode(vcpu) &&
10788 kvm_x86_ops.nested_ops->has_events &&
10789 kvm_x86_ops.nested_ops->has_events(vcpu, true))
10790 *req_immediate_exit = true;
10791
10792 /*
10793 * KVM must never queue a new exception while injecting an event; KVM
10794 * is done emulating and should only propagate the to-be-injected event
10795 * to the VMCS/VMCB. Queueing a new exception can put the vCPU into an
10796 * infinite loop as KVM will bail from VM-Enter to inject the pending
10797 * exception and start the cycle all over.
10798 *
10799 * Exempt triple faults as they have special handling and won't put the
10800 * vCPU into an infinite loop. Triple fault can be queued when running
10801 * VMX without unrestricted guest, as that requires KVM to emulate Real
10802 * Mode events (see kvm_inject_realmode_interrupt()).
10803 */
10804 WARN_ON_ONCE(vcpu->arch.exception.pending ||
10805 vcpu->arch.exception_vmexit.pending);
10806 return 0;
10807
10808 out:
10809 if (r == -EBUSY) {
10810 *req_immediate_exit = true;
10811 r = 0;
10812 }
10813 return r;
10814 }
10815
process_nmi(struct kvm_vcpu * vcpu)10816 static void process_nmi(struct kvm_vcpu *vcpu)
10817 {
10818 unsigned int limit;
10819
10820 /*
10821 * x86 is limited to one NMI pending, but because KVM can't react to
10822 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10823 * scheduled out, KVM needs to play nice with two queued NMIs showing
10824 * up at the same time. To handle this scenario, allow two NMIs to be
10825 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10826 * waiting for a previous NMI injection to complete (which effectively
10827 * blocks NMIs). KVM will immediately inject one of the two NMIs, and
10828 * will request an NMI window to handle the second NMI.
10829 */
10830 if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10831 limit = 1;
10832 else
10833 limit = 2;
10834
10835 /*
10836 * Adjust the limit to account for pending virtual NMIs, which aren't
10837 * tracked in vcpu->arch.nmi_pending.
10838 */
10839 if (kvm_x86_call(is_vnmi_pending)(vcpu))
10840 limit--;
10841
10842 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10843 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10844
10845 if (vcpu->arch.nmi_pending &&
10846 (kvm_x86_call(set_vnmi_pending)(vcpu)))
10847 vcpu->arch.nmi_pending--;
10848
10849 if (vcpu->arch.nmi_pending)
10850 kvm_make_request(KVM_REQ_EVENT, vcpu);
10851 }
10852
10853 /* Return total number of NMIs pending injection to the VM */
kvm_get_nr_pending_nmis(struct kvm_vcpu * vcpu)10854 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10855 {
10856 return vcpu->arch.nmi_pending +
10857 kvm_x86_call(is_vnmi_pending)(vcpu);
10858 }
10859
kvm_make_scan_ioapic_request_mask(struct kvm * kvm,unsigned long * vcpu_bitmap)10860 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10861 unsigned long *vcpu_bitmap)
10862 {
10863 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10864 }
10865
kvm_make_scan_ioapic_request(struct kvm * kvm)10866 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10867 {
10868 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10869 }
10870
__kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10871 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10872 {
10873 struct kvm_lapic *apic = vcpu->arch.apic;
10874 bool activate;
10875
10876 if (!lapic_in_kernel(vcpu))
10877 return;
10878
10879 down_read(&vcpu->kvm->arch.apicv_update_lock);
10880 preempt_disable();
10881
10882 /* Do not activate APICV when APIC is disabled */
10883 activate = kvm_vcpu_apicv_activated(vcpu) &&
10884 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10885
10886 if (apic->apicv_active == activate)
10887 goto out;
10888
10889 apic->apicv_active = activate;
10890 kvm_apic_update_apicv(vcpu);
10891 kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
10892
10893 /*
10894 * When APICv gets disabled, we may still have injected interrupts
10895 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10896 * still active when the interrupt got accepted. Make sure
10897 * kvm_check_and_inject_events() is called to check for that.
10898 *
10899 * Update SVI when APICv gets enabled, otherwise SVI won't reflect the
10900 * highest bit in vISR and the next accelerated EOI in the guest won't
10901 * be virtualized correctly (the CPU uses SVI to determine which vISR
10902 * vector to clear).
10903 */
10904 if (!apic->apicv_active)
10905 kvm_make_request(KVM_REQ_EVENT, vcpu);
10906 else
10907 kvm_apic_update_hwapic_isr(vcpu);
10908
10909 out:
10910 preempt_enable();
10911 up_read(&vcpu->kvm->arch.apicv_update_lock);
10912 }
10913 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_vcpu_update_apicv);
10914
kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10915 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10916 {
10917 if (!lapic_in_kernel(vcpu))
10918 return;
10919
10920 /*
10921 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10922 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10923 * and hardware doesn't support x2APIC virtualization. E.g. some AMD
10924 * CPUs support AVIC but not x2APIC. KVM still allows enabling AVIC in
10925 * this case so that KVM can use the AVIC doorbell to inject interrupts
10926 * to running vCPUs, but KVM must not create SPTEs for the APIC base as
10927 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
10928 * despite being in x2APIC mode. For simplicity, inhibiting the APIC
10929 * access page is sticky.
10930 */
10931 if (apic_x2apic_mode(vcpu->arch.apic) &&
10932 kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
10933 kvm_inhibit_apic_access_page(vcpu);
10934
10935 __kvm_vcpu_update_apicv(vcpu);
10936 }
10937
__kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10938 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10939 enum kvm_apicv_inhibit reason, bool set)
10940 {
10941 unsigned long old, new;
10942
10943 lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10944
10945 if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
10946 return;
10947
10948 old = new = kvm->arch.apicv_inhibit_reasons;
10949
10950 set_or_clear_apicv_inhibit(&new, reason, set);
10951
10952 if (!!old != !!new) {
10953 /*
10954 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10955 * false positives in the sanity check WARN in vcpu_enter_guest().
10956 * This task will wait for all vCPUs to ack the kick IRQ before
10957 * updating apicv_inhibit_reasons, and all other vCPUs will
10958 * block on acquiring apicv_update_lock so that vCPUs can't
10959 * redo vcpu_enter_guest() without seeing the new inhibit state.
10960 *
10961 * Note, holding apicv_update_lock and taking it in the read
10962 * side (handling the request) also prevents other vCPUs from
10963 * servicing the request with a stale apicv_inhibit_reasons.
10964 */
10965 kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10966 kvm->arch.apicv_inhibit_reasons = new;
10967 if (new) {
10968 unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10969 int idx = srcu_read_lock(&kvm->srcu);
10970
10971 kvm_zap_gfn_range(kvm, gfn, gfn+1);
10972 srcu_read_unlock(&kvm->srcu, idx);
10973 }
10974 } else {
10975 kvm->arch.apicv_inhibit_reasons = new;
10976 }
10977 }
10978
kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10979 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10980 enum kvm_apicv_inhibit reason, bool set)
10981 {
10982 if (!enable_apicv)
10983 return;
10984
10985 down_write(&kvm->arch.apicv_update_lock);
10986 __kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10987 up_write(&kvm->arch.apicv_update_lock);
10988 }
10989 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_or_clear_apicv_inhibit);
10990
vcpu_scan_ioapic(struct kvm_vcpu * vcpu)10991 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10992 {
10993 if (!kvm_apic_present(vcpu))
10994 return;
10995
10996 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10997 vcpu->arch.highest_stale_pending_ioapic_eoi = -1;
10998
10999 kvm_x86_call(sync_pir_to_irr)(vcpu);
11000
11001 if (irqchip_split(vcpu->kvm))
11002 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
11003 #ifdef CONFIG_KVM_IOAPIC
11004 else if (ioapic_in_kernel(vcpu->kvm))
11005 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
11006 #endif
11007
11008 if (is_guest_mode(vcpu))
11009 vcpu->arch.load_eoi_exitmap_pending = true;
11010 else
11011 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
11012 }
11013
vcpu_load_eoi_exitmap(struct kvm_vcpu * vcpu)11014 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
11015 {
11016 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
11017 return;
11018
11019 #ifdef CONFIG_KVM_HYPERV
11020 if (to_hv_vcpu(vcpu)) {
11021 u64 eoi_exit_bitmap[4];
11022
11023 bitmap_or((ulong *)eoi_exit_bitmap,
11024 vcpu->arch.ioapic_handled_vectors,
11025 to_hv_synic(vcpu)->vec_bitmap, 256);
11026 kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
11027 return;
11028 }
11029 #endif
11030 kvm_x86_call(load_eoi_exitmap)(
11031 vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
11032 }
11033
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)11034 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
11035 {
11036 kvm_x86_call(guest_memory_reclaimed)(kvm);
11037 }
11038
kvm_vcpu_reload_apic_access_page(struct kvm_vcpu * vcpu)11039 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
11040 {
11041 if (!lapic_in_kernel(vcpu))
11042 return;
11043
11044 kvm_x86_call(set_apic_access_page_addr)(vcpu);
11045 }
11046
11047 /*
11048 * Called within kvm->srcu read side.
11049 * Returns 1 to let vcpu_run() continue the guest execution loop without
11050 * exiting to the userspace. Otherwise, the value will be returned to the
11051 * userspace.
11052 */
vcpu_enter_guest(struct kvm_vcpu * vcpu)11053 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
11054 {
11055 int r;
11056 bool req_int_win =
11057 dm_request_for_irq_injection(vcpu) &&
11058 kvm_cpu_accept_dm_intr(vcpu);
11059 fastpath_t exit_fastpath;
11060 u64 run_flags, debug_ctl;
11061
11062 bool req_immediate_exit = false;
11063
11064 if (kvm_request_pending(vcpu)) {
11065 if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
11066 r = -EIO;
11067 goto out;
11068 }
11069
11070 if (kvm_dirty_ring_check_request(vcpu)) {
11071 r = 0;
11072 goto out;
11073 }
11074
11075 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
11076 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
11077 r = 0;
11078 goto out;
11079 }
11080 }
11081 if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
11082 kvm_mmu_free_obsolete_roots(vcpu);
11083 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
11084 __kvm_migrate_timers(vcpu);
11085 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
11086 kvm_update_masterclock(vcpu->kvm);
11087 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
11088 kvm_gen_kvmclock_update(vcpu);
11089 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
11090 r = kvm_guest_time_update(vcpu);
11091 if (unlikely(r))
11092 goto out;
11093 }
11094 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
11095 kvm_mmu_sync_roots(vcpu);
11096 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
11097 kvm_mmu_load_pgd(vcpu);
11098
11099 /*
11100 * Note, the order matters here, as flushing "all" TLB entries
11101 * also flushes the "current" TLB entries, i.e. servicing the
11102 * flush "all" will clear any request to flush "current".
11103 */
11104 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
11105 kvm_vcpu_flush_tlb_all(vcpu);
11106
11107 kvm_service_local_tlb_flush_requests(vcpu);
11108
11109 /*
11110 * Fall back to a "full" guest flush if Hyper-V's precise
11111 * flushing fails. Note, Hyper-V's flushing is per-vCPU, but
11112 * the flushes are considered "remote" and not "local" because
11113 * the requests can be initiated from other vCPUs.
11114 */
11115 #ifdef CONFIG_KVM_HYPERV
11116 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
11117 kvm_hv_vcpu_flush_tlb(vcpu))
11118 kvm_vcpu_flush_tlb_guest(vcpu);
11119 #endif
11120
11121 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
11122 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
11123 r = 0;
11124 goto out;
11125 }
11126 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
11127 if (is_guest_mode(vcpu))
11128 kvm_x86_ops.nested_ops->triple_fault(vcpu);
11129
11130 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
11131 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
11132 vcpu->mmio_needed = 0;
11133 r = 0;
11134 goto out;
11135 }
11136 }
11137 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
11138 /* Page is swapped out. Do synthetic halt */
11139 vcpu->arch.apf.halted = true;
11140 r = 1;
11141 goto out;
11142 }
11143 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
11144 record_steal_time(vcpu);
11145 if (kvm_check_request(KVM_REQ_PMU, vcpu))
11146 kvm_pmu_handle_event(vcpu);
11147 if (kvm_check_request(KVM_REQ_PMI, vcpu))
11148 kvm_pmu_deliver_pmi(vcpu);
11149 #ifdef CONFIG_KVM_SMM
11150 if (kvm_check_request(KVM_REQ_SMI, vcpu))
11151 process_smi(vcpu);
11152 #endif
11153 if (kvm_check_request(KVM_REQ_NMI, vcpu))
11154 process_nmi(vcpu);
11155 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
11156 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
11157 if (test_bit(vcpu->arch.pending_ioapic_eoi,
11158 vcpu->arch.ioapic_handled_vectors)) {
11159 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
11160 vcpu->run->eoi.vector =
11161 vcpu->arch.pending_ioapic_eoi;
11162 r = 0;
11163 goto out;
11164 }
11165 }
11166 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
11167 vcpu_scan_ioapic(vcpu);
11168 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
11169 vcpu_load_eoi_exitmap(vcpu);
11170 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
11171 kvm_vcpu_reload_apic_access_page(vcpu);
11172 #ifdef CONFIG_KVM_HYPERV
11173 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
11174 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
11175 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
11176 vcpu->run->system_event.ndata = 0;
11177 r = 0;
11178 goto out;
11179 }
11180 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
11181 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
11182 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
11183 vcpu->run->system_event.ndata = 0;
11184 r = 0;
11185 goto out;
11186 }
11187 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
11188 struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
11189
11190 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
11191 vcpu->run->hyperv = hv_vcpu->exit;
11192 r = 0;
11193 goto out;
11194 }
11195
11196 /*
11197 * KVM_REQ_HV_STIMER has to be processed after
11198 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
11199 * depend on the guest clock being up-to-date
11200 */
11201 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
11202 kvm_hv_process_stimers(vcpu);
11203 #endif
11204 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
11205 kvm_vcpu_update_apicv(vcpu);
11206 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
11207 kvm_check_async_pf_completion(vcpu);
11208
11209 if (kvm_check_request(KVM_REQ_RECALC_INTERCEPTS, vcpu))
11210 kvm_x86_call(recalc_intercepts)(vcpu);
11211
11212 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
11213 kvm_x86_call(update_cpu_dirty_logging)(vcpu);
11214
11215 if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
11216 kvm_vcpu_reset(vcpu, true);
11217 if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
11218 r = 1;
11219 goto out;
11220 }
11221 }
11222 }
11223
11224 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
11225 kvm_xen_has_interrupt(vcpu)) {
11226 ++vcpu->stat.req_event;
11227 r = kvm_apic_accept_events(vcpu);
11228 if (r < 0) {
11229 r = 0;
11230 goto out;
11231 }
11232 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
11233 r = 1;
11234 goto out;
11235 }
11236
11237 r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
11238 if (r < 0) {
11239 r = 0;
11240 goto out;
11241 }
11242 if (req_int_win)
11243 kvm_x86_call(enable_irq_window)(vcpu);
11244
11245 if (kvm_lapic_enabled(vcpu)) {
11246 update_cr8_intercept(vcpu);
11247 kvm_lapic_sync_to_vapic(vcpu);
11248 }
11249 }
11250
11251 r = kvm_mmu_reload(vcpu);
11252 if (unlikely(r)) {
11253 goto cancel_injection;
11254 }
11255
11256 preempt_disable();
11257
11258 kvm_x86_call(prepare_switch_to_guest)(vcpu);
11259
11260 /*
11261 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
11262 * IPI are then delayed after guest entry, which ensures that they
11263 * result in virtual interrupt delivery.
11264 */
11265 local_irq_disable();
11266
11267 /* Store vcpu->apicv_active before vcpu->mode. */
11268 smp_store_release(&vcpu->mode, IN_GUEST_MODE);
11269
11270 kvm_vcpu_srcu_read_unlock(vcpu);
11271
11272 /*
11273 * 1) We should set ->mode before checking ->requests. Please see
11274 * the comment in kvm_vcpu_exiting_guest_mode().
11275 *
11276 * 2) For APICv, we should set ->mode before checking PID.ON. This
11277 * pairs with the memory barrier implicit in pi_test_and_set_on
11278 * (see vmx_deliver_posted_interrupt).
11279 *
11280 * 3) This also orders the write to mode from any reads to the page
11281 * tables done while the VCPU is running. Please see the comment
11282 * in kvm_flush_remote_tlbs.
11283 */
11284 smp_mb__after_srcu_read_unlock();
11285
11286 /*
11287 * Process pending posted interrupts to handle the case where the
11288 * notification IRQ arrived in the host, or was never sent (because the
11289 * target vCPU wasn't running). Do this regardless of the vCPU's APICv
11290 * status, KVM doesn't update assigned devices when APICv is inhibited,
11291 * i.e. they can post interrupts even if APICv is temporarily disabled.
11292 */
11293 if (kvm_lapic_enabled(vcpu))
11294 kvm_x86_call(sync_pir_to_irr)(vcpu);
11295
11296 if (kvm_vcpu_exit_request(vcpu)) {
11297 vcpu->mode = OUTSIDE_GUEST_MODE;
11298 smp_wmb();
11299 local_irq_enable();
11300 preempt_enable();
11301 kvm_vcpu_srcu_read_lock(vcpu);
11302 r = 1;
11303 goto cancel_injection;
11304 }
11305
11306 run_flags = 0;
11307 if (req_immediate_exit) {
11308 run_flags |= KVM_RUN_FORCE_IMMEDIATE_EXIT;
11309 kvm_make_request(KVM_REQ_EVENT, vcpu);
11310 }
11311
11312 fpregs_assert_state_consistent();
11313 if (test_thread_flag(TIF_NEED_FPU_LOAD))
11314 switch_fpu_return();
11315
11316 if (vcpu->arch.guest_fpu.xfd_err)
11317 wrmsrq(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
11318
11319 kvm_load_xfeatures(vcpu, true);
11320
11321 if (unlikely(vcpu->arch.switch_db_regs &&
11322 !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
11323 set_debugreg(DR7_FIXED_1, 7);
11324 set_debugreg(vcpu->arch.eff_db[0], 0);
11325 set_debugreg(vcpu->arch.eff_db[1], 1);
11326 set_debugreg(vcpu->arch.eff_db[2], 2);
11327 set_debugreg(vcpu->arch.eff_db[3], 3);
11328 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
11329 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
11330 run_flags |= KVM_RUN_LOAD_GUEST_DR6;
11331 } else if (unlikely(hw_breakpoint_active())) {
11332 set_debugreg(DR7_FIXED_1, 7);
11333 }
11334
11335 /*
11336 * Refresh the host DEBUGCTL snapshot after disabling IRQs, as DEBUGCTL
11337 * can be modified in IRQ context, e.g. via SMP function calls. Inform
11338 * vendor code if any host-owned bits were changed, e.g. so that the
11339 * value loaded into hardware while running the guest can be updated.
11340 */
11341 debug_ctl = get_debugctlmsr();
11342 if ((debug_ctl ^ vcpu->arch.host_debugctl) & kvm_x86_ops.HOST_OWNED_DEBUGCTL &&
11343 !vcpu->arch.guest_state_protected)
11344 run_flags |= KVM_RUN_LOAD_DEBUGCTL;
11345 vcpu->arch.host_debugctl = debug_ctl;
11346
11347 guest_timing_enter_irqoff();
11348
11349 /*
11350 * Swap PKRU with hardware breakpoints disabled to minimize the number
11351 * of flows where non-KVM code can run with guest state loaded.
11352 */
11353 kvm_load_guest_pkru(vcpu);
11354
11355 for (;;) {
11356 /*
11357 * Assert that vCPU vs. VM APICv state is consistent. An APICv
11358 * update must kick and wait for all vCPUs before toggling the
11359 * per-VM state, and responding vCPUs must wait for the update
11360 * to complete before servicing KVM_REQ_APICV_UPDATE.
11361 */
11362 WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11363 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
11364
11365 exit_fastpath = kvm_x86_call(vcpu_run)(vcpu, run_flags);
11366 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11367 break;
11368
11369 if (kvm_lapic_enabled(vcpu))
11370 kvm_x86_call(sync_pir_to_irr)(vcpu);
11371
11372 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
11373 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11374 break;
11375 }
11376
11377 run_flags = 0;
11378
11379 /* Note, VM-Exits that go down the "slow" path are accounted below. */
11380 ++vcpu->stat.exits;
11381 }
11382
11383 kvm_load_host_pkru(vcpu);
11384
11385 /*
11386 * Do this here before restoring debug registers on the host. And
11387 * since we do this before handling the vmexit, a DR access vmexit
11388 * can (a) read the correct value of the debug registers, (b) set
11389 * KVM_DEBUGREG_WONT_EXIT again.
11390 */
11391 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
11392 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
11393 WARN_ON(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH);
11394 kvm_x86_call(sync_dirty_debug_regs)(vcpu);
11395 kvm_update_dr0123(vcpu);
11396 kvm_update_dr7(vcpu);
11397 }
11398
11399 /*
11400 * If the guest has used debug registers, at least dr7
11401 * will be disabled while returning to the host.
11402 * If we don't have active breakpoints in the host, we don't
11403 * care about the messed up debug address registers. But if
11404 * we have some of them active, restore the old state.
11405 */
11406 if (hw_breakpoint_active())
11407 hw_breakpoint_restore();
11408
11409 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
11410 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
11411
11412 vcpu->mode = OUTSIDE_GUEST_MODE;
11413 smp_wmb();
11414
11415 kvm_load_xfeatures(vcpu, false);
11416
11417 /*
11418 * Sync xfd before calling handle_exit_irqoff() which may
11419 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11420 * in #NM irqoff handler).
11421 */
11422 if (vcpu->arch.xfd_no_write_intercept)
11423 fpu_sync_guest_vmexit_xfd_state();
11424
11425 kvm_x86_call(handle_exit_irqoff)(vcpu);
11426
11427 if (vcpu->arch.guest_fpu.xfd_err)
11428 wrmsrq(MSR_IA32_XFD_ERR, 0);
11429
11430 /*
11431 * Mark this CPU as needing a branch predictor flush before running
11432 * userspace. Must be done before enabling preemption to ensure it gets
11433 * set for the CPU that actually ran the guest, and not the CPU that it
11434 * may migrate to.
11435 */
11436 if (cpu_feature_enabled(X86_FEATURE_IBPB_EXIT_TO_USER))
11437 this_cpu_write(x86_ibpb_exit_to_user, true);
11438
11439 /*
11440 * Consume any pending interrupts, including the possible source of
11441 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11442 * An instruction is required after local_irq_enable() to fully unblock
11443 * interrupts on processors that implement an interrupt shadow, the
11444 * stat.exits increment will do nicely.
11445 */
11446 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
11447 local_irq_enable();
11448 ++vcpu->stat.exits;
11449 local_irq_disable();
11450 kvm_after_interrupt(vcpu);
11451
11452 /*
11453 * Wait until after servicing IRQs to account guest time so that any
11454 * ticks that occurred while running the guest are properly accounted
11455 * to the guest. Waiting until IRQs are enabled degrades the accuracy
11456 * of accounting via context tracking, but the loss of accuracy is
11457 * acceptable for all known use cases.
11458 */
11459 guest_timing_exit_irqoff();
11460
11461 local_irq_enable();
11462 preempt_enable();
11463
11464 kvm_vcpu_srcu_read_lock(vcpu);
11465
11466 /*
11467 * Call this to ensure WC buffers in guest are evicted after each VM
11468 * Exit, so that the evicted WC writes can be snooped across all cpus
11469 */
11470 smp_mb__after_srcu_read_lock();
11471
11472 /*
11473 * Profile KVM exit RIPs:
11474 */
11475 if (unlikely(prof_on == KVM_PROFILING &&
11476 !vcpu->arch.guest_state_protected)) {
11477 unsigned long rip = kvm_rip_read(vcpu);
11478 profile_hit(KVM_PROFILING, (void *)rip);
11479 }
11480
11481 if (unlikely(vcpu->arch.tsc_always_catchup))
11482 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11483
11484 if (vcpu->arch.apic_attention)
11485 kvm_lapic_sync_from_vapic(vcpu);
11486
11487 if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
11488 return 0;
11489
11490 r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
11491 return r;
11492
11493 cancel_injection:
11494 if (req_immediate_exit)
11495 kvm_make_request(KVM_REQ_EVENT, vcpu);
11496 kvm_x86_call(cancel_injection)(vcpu);
11497 if (unlikely(vcpu->arch.apic_attention))
11498 kvm_lapic_sync_from_vapic(vcpu);
11499 out:
11500 return r;
11501 }
11502
kvm_vcpu_running(struct kvm_vcpu * vcpu)11503 static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11504 {
11505 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11506 !vcpu->arch.apf.halted);
11507 }
11508
kvm_vcpu_has_events(struct kvm_vcpu * vcpu)11509 bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
11510 {
11511 if (!list_empty_careful(&vcpu->async_pf.done))
11512 return true;
11513
11514 if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
11515 kvm_apic_init_sipi_allowed(vcpu))
11516 return true;
11517
11518 if (kvm_is_exception_pending(vcpu))
11519 return true;
11520
11521 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11522 (vcpu->arch.nmi_pending &&
11523 kvm_x86_call(nmi_allowed)(vcpu, false)))
11524 return true;
11525
11526 #ifdef CONFIG_KVM_SMM
11527 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11528 (vcpu->arch.smi_pending &&
11529 kvm_x86_call(smi_allowed)(vcpu, false)))
11530 return true;
11531 #endif
11532
11533 if (kvm_test_request(KVM_REQ_PMI, vcpu))
11534 return true;
11535
11536 if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
11537 return true;
11538
11539 if (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
11540 return true;
11541
11542 if (kvm_hv_has_stimer_pending(vcpu))
11543 return true;
11544
11545 if (is_guest_mode(vcpu) &&
11546 kvm_x86_ops.nested_ops->has_events &&
11547 kvm_x86_ops.nested_ops->has_events(vcpu, false))
11548 return true;
11549
11550 if (kvm_xen_has_pending_events(vcpu))
11551 return true;
11552
11553 return false;
11554 }
11555 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_has_events);
11556
kvm_arch_vcpu_runnable(struct kvm_vcpu * vcpu)11557 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11558 {
11559 return kvm_vcpu_running(vcpu) || vcpu->arch.pv.pv_unhalted ||
11560 kvm_vcpu_has_events(vcpu);
11561 }
11562
11563 /* Called within kvm->srcu read side. */
vcpu_block(struct kvm_vcpu * vcpu)11564 static inline int vcpu_block(struct kvm_vcpu *vcpu)
11565 {
11566 bool hv_timer;
11567
11568 if (!kvm_arch_vcpu_runnable(vcpu)) {
11569 /*
11570 * Switch to the software timer before halt-polling/blocking as
11571 * the guest's timer may be a break event for the vCPU, and the
11572 * hypervisor timer runs only when the CPU is in guest mode.
11573 * Switch before halt-polling so that KVM recognizes an expired
11574 * timer before blocking.
11575 */
11576 hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11577 if (hv_timer)
11578 kvm_lapic_switch_to_sw_timer(vcpu);
11579
11580 kvm_vcpu_srcu_read_unlock(vcpu);
11581 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11582 kvm_vcpu_halt(vcpu);
11583 else
11584 kvm_vcpu_block(vcpu);
11585 kvm_vcpu_srcu_read_lock(vcpu);
11586
11587 if (hv_timer)
11588 kvm_lapic_switch_to_hv_timer(vcpu);
11589
11590 /*
11591 * If the vCPU is not runnable, a signal or another host event
11592 * of some kind is pending; service it without changing the
11593 * vCPU's activity state.
11594 */
11595 if (!kvm_arch_vcpu_runnable(vcpu))
11596 return 1;
11597 }
11598
11599 /*
11600 * Evaluate nested events before exiting the halted state. This allows
11601 * the halt state to be recorded properly in the VMCS12's activity
11602 * state field (AMD does not have a similar field and a VM-Exit always
11603 * causes a spurious wakeup from HLT).
11604 */
11605 if (is_guest_mode(vcpu)) {
11606 int r = kvm_check_nested_events(vcpu);
11607
11608 WARN_ON_ONCE(r == -EBUSY);
11609 if (r < 0)
11610 return 0;
11611 }
11612
11613 if (kvm_apic_accept_events(vcpu) < 0)
11614 return 0;
11615 switch(vcpu->arch.mp_state) {
11616 case KVM_MP_STATE_HALTED:
11617 case KVM_MP_STATE_AP_RESET_HOLD:
11618 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
11619 fallthrough;
11620 case KVM_MP_STATE_RUNNABLE:
11621 vcpu->arch.apf.halted = false;
11622 break;
11623 case KVM_MP_STATE_INIT_RECEIVED:
11624 break;
11625 default:
11626 WARN_ON_ONCE(1);
11627 break;
11628 }
11629 return 1;
11630 }
11631
11632 /* Called within kvm->srcu read side. */
vcpu_run(struct kvm_vcpu * vcpu)11633 static int vcpu_run(struct kvm_vcpu *vcpu)
11634 {
11635 int r;
11636
11637 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
11638
11639 for (;;) {
11640 /*
11641 * If another guest vCPU requests a PV TLB flush in the middle
11642 * of instruction emulation, the rest of the emulation could
11643 * use a stale page translation. Assume that any code after
11644 * this point can start executing an instruction.
11645 */
11646 vcpu->arch.at_instruction_boundary = false;
11647 if (kvm_vcpu_running(vcpu)) {
11648 r = vcpu_enter_guest(vcpu);
11649 } else {
11650 r = vcpu_block(vcpu);
11651 }
11652
11653 if (r <= 0)
11654 break;
11655
11656 kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11657 if (kvm_xen_has_pending_events(vcpu))
11658 kvm_xen_inject_pending_events(vcpu);
11659
11660 if (kvm_cpu_has_pending_timer(vcpu))
11661 kvm_inject_pending_timer_irqs(vcpu);
11662
11663 if (dm_request_for_irq_injection(vcpu) &&
11664 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11665 r = 0;
11666 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11667 ++vcpu->stat.request_irq_exits;
11668 break;
11669 }
11670
11671 if (__xfer_to_guest_mode_work_pending()) {
11672 kvm_vcpu_srcu_read_unlock(vcpu);
11673 r = kvm_xfer_to_guest_mode_handle_work(vcpu);
11674 kvm_vcpu_srcu_read_lock(vcpu);
11675 if (r)
11676 return r;
11677 }
11678 }
11679
11680 return r;
11681 }
11682
__kvm_emulate_halt(struct kvm_vcpu * vcpu,int state,int reason)11683 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
11684 {
11685 /*
11686 * The vCPU has halted, e.g. executed HLT. Update the run state if the
11687 * local APIC is in-kernel, the run loop will detect the non-runnable
11688 * state and halt the vCPU. Exit to userspace if the local APIC is
11689 * managed by userspace, in which case userspace is responsible for
11690 * handling wake events.
11691 */
11692 ++vcpu->stat.halt_exits;
11693 if (lapic_in_kernel(vcpu)) {
11694 if (kvm_vcpu_has_events(vcpu) || vcpu->arch.pv.pv_unhalted)
11695 state = KVM_MP_STATE_RUNNABLE;
11696 kvm_set_mp_state(vcpu, state);
11697 return 1;
11698 } else {
11699 vcpu->run->exit_reason = reason;
11700 return 0;
11701 }
11702 }
11703
kvm_emulate_halt_noskip(struct kvm_vcpu * vcpu)11704 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
11705 {
11706 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
11707 }
11708 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt_noskip);
11709
kvm_emulate_halt(struct kvm_vcpu * vcpu)11710 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
11711 {
11712 int ret = kvm_skip_emulated_instruction(vcpu);
11713 /*
11714 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
11715 * KVM_EXIT_DEBUG here.
11716 */
11717 return kvm_emulate_halt_noskip(vcpu) && ret;
11718 }
11719 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt);
11720
handle_fastpath_hlt(struct kvm_vcpu * vcpu)11721 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
11722 {
11723 if (!kvm_emulate_halt(vcpu))
11724 return EXIT_FASTPATH_EXIT_USERSPACE;
11725
11726 if (kvm_vcpu_running(vcpu))
11727 return EXIT_FASTPATH_REENTER_GUEST;
11728
11729 return EXIT_FASTPATH_EXIT_HANDLED;
11730 }
11731 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_hlt);
11732
kvm_emulate_ap_reset_hold(struct kvm_vcpu * vcpu)11733 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
11734 {
11735 int ret = kvm_skip_emulated_instruction(vcpu);
11736
11737 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
11738 KVM_EXIT_AP_RESET_HOLD) && ret;
11739 }
11740 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_ap_reset_hold);
11741
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)11742 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
11743 {
11744 return kvm_vcpu_apicv_active(vcpu) &&
11745 kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
11746 }
11747
kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu * vcpu)11748 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
11749 {
11750 return vcpu->arch.preempted_in_kernel;
11751 }
11752
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)11753 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11754 {
11755 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11756 return true;
11757
11758 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11759 #ifdef CONFIG_KVM_SMM
11760 kvm_test_request(KVM_REQ_SMI, vcpu) ||
11761 #endif
11762 kvm_test_request(KVM_REQ_EVENT, vcpu))
11763 return true;
11764
11765 return kvm_arch_dy_has_pending_interrupt(vcpu);
11766 }
11767
complete_emulated_io(struct kvm_vcpu * vcpu)11768 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11769 {
11770 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11771 }
11772
complete_emulated_pio(struct kvm_vcpu * vcpu)11773 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11774 {
11775 BUG_ON(!vcpu->arch.pio.count);
11776
11777 return complete_emulated_io(vcpu);
11778 }
11779
11780 /*
11781 * Implements the following, as a state machine:
11782 *
11783 * read:
11784 * for each fragment
11785 * for each mmio piece in the fragment
11786 * write gpa, len
11787 * exit
11788 * copy data
11789 * execute insn
11790 *
11791 * write:
11792 * for each fragment
11793 * for each mmio piece in the fragment
11794 * write gpa, len
11795 * copy data
11796 * exit
11797 */
complete_emulated_mmio(struct kvm_vcpu * vcpu)11798 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11799 {
11800 struct kvm_run *run = vcpu->run;
11801 struct kvm_mmio_fragment *frag;
11802 unsigned len;
11803
11804 BUG_ON(!vcpu->mmio_needed);
11805
11806 /* Complete previous fragment */
11807 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11808 len = min(8u, frag->len);
11809 if (!vcpu->mmio_is_write)
11810 memcpy(frag->data, run->mmio.data, len);
11811
11812 if (frag->len <= 8) {
11813 /* Switch to the next fragment. */
11814 frag++;
11815 vcpu->mmio_cur_fragment++;
11816 } else {
11817 /* Go forward to the next mmio piece. */
11818 frag->data += len;
11819 frag->gpa += len;
11820 frag->len -= len;
11821 }
11822
11823 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11824 vcpu->mmio_needed = 0;
11825
11826 /* FIXME: return into emulator if single-stepping. */
11827 if (vcpu->mmio_is_write)
11828 return 1;
11829 vcpu->mmio_read_completed = 1;
11830 return complete_emulated_io(vcpu);
11831 }
11832
11833 run->exit_reason = KVM_EXIT_MMIO;
11834 run->mmio.phys_addr = frag->gpa;
11835 if (vcpu->mmio_is_write)
11836 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11837 run->mmio.len = min(8u, frag->len);
11838 run->mmio.is_write = vcpu->mmio_is_write;
11839 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11840 return 0;
11841 }
11842
11843 /* Swap (qemu) user FPU context for the guest FPU context. */
kvm_load_guest_fpu(struct kvm_vcpu * vcpu)11844 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11845 {
11846 if (KVM_BUG_ON(vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
11847 return;
11848
11849 /* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11850 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11851 trace_kvm_fpu(1);
11852 }
11853
11854 /* When vcpu_run ends, restore user space FPU context. */
kvm_put_guest_fpu(struct kvm_vcpu * vcpu)11855 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11856 {
11857 if (KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
11858 return;
11859
11860 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11861 ++vcpu->stat.fpu_reload;
11862 trace_kvm_fpu(0);
11863 }
11864
kvm_x86_vcpu_pre_run(struct kvm_vcpu * vcpu)11865 static int kvm_x86_vcpu_pre_run(struct kvm_vcpu *vcpu)
11866 {
11867 /*
11868 * SIPI_RECEIVED is obsolete; KVM leaves the vCPU in Wait-For-SIPI and
11869 * tracks the pending SIPI separately. SIPI_RECEIVED is still accepted
11870 * by KVM_SET_VCPU_EVENTS for backwards compatibility, but should be
11871 * converted to INIT_RECEIVED.
11872 */
11873 if (WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED))
11874 return -EINVAL;
11875
11876 /*
11877 * Disallow running the vCPU if userspace forced it into an impossible
11878 * MP_STATE, e.g. if the vCPU is in WFS but SIPI is blocked.
11879 */
11880 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED &&
11881 !kvm_apic_init_sipi_allowed(vcpu))
11882 return -EINVAL;
11883
11884 return kvm_x86_call(vcpu_pre_run)(vcpu);
11885 }
11886
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)11887 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
11888 {
11889 struct kvm_queued_exception *ex = &vcpu->arch.exception;
11890 struct kvm_run *kvm_run = vcpu->run;
11891 u64 sync_valid_fields;
11892 int r;
11893
11894 r = kvm_mmu_post_init_vm(vcpu->kvm);
11895 if (r)
11896 return r;
11897
11898 vcpu_load(vcpu);
11899 kvm_sigset_activate(vcpu);
11900 kvm_run->flags = 0;
11901 kvm_load_guest_fpu(vcpu);
11902
11903 kvm_vcpu_srcu_read_lock(vcpu);
11904 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
11905 if (!vcpu->wants_to_run) {
11906 r = -EINTR;
11907 goto out;
11908 }
11909
11910 /*
11911 * Don't bother switching APIC timer emulation from the
11912 * hypervisor timer to the software timer, the only way for the
11913 * APIC timer to be active is if userspace stuffed vCPU state,
11914 * i.e. put the vCPU into a nonsensical state. Only an INIT
11915 * will transition the vCPU out of UNINITIALIZED (without more
11916 * state stuffing from userspace), which will reset the local
11917 * APIC and thus cancel the timer or drop the IRQ (if the timer
11918 * already expired).
11919 */
11920 kvm_vcpu_srcu_read_unlock(vcpu);
11921 kvm_vcpu_block(vcpu);
11922 kvm_vcpu_srcu_read_lock(vcpu);
11923
11924 if (kvm_apic_accept_events(vcpu) < 0) {
11925 r = 0;
11926 goto out;
11927 }
11928 r = -EAGAIN;
11929 if (signal_pending(current)) {
11930 r = -EINTR;
11931 kvm_run->exit_reason = KVM_EXIT_INTR;
11932 ++vcpu->stat.signal_exits;
11933 }
11934 goto out;
11935 }
11936
11937 sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
11938 if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
11939 (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
11940 r = -EINVAL;
11941 goto out;
11942 }
11943
11944 if (kvm_run->kvm_dirty_regs) {
11945 r = sync_regs(vcpu);
11946 if (r != 0)
11947 goto out;
11948 }
11949
11950 /* re-sync apic's tpr */
11951 if (!lapic_in_kernel(vcpu)) {
11952 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11953 r = -EINVAL;
11954 goto out;
11955 }
11956 }
11957
11958 /*
11959 * If userspace set a pending exception and L2 is active, convert it to
11960 * a pending VM-Exit if L1 wants to intercept the exception.
11961 */
11962 if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11963 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11964 ex->error_code)) {
11965 kvm_queue_exception_vmexit(vcpu, ex->vector,
11966 ex->has_error_code, ex->error_code,
11967 ex->has_payload, ex->payload);
11968 ex->injected = false;
11969 ex->pending = false;
11970 }
11971 vcpu->arch.exception_from_userspace = false;
11972
11973 if (unlikely(vcpu->arch.complete_userspace_io)) {
11974 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11975 vcpu->arch.complete_userspace_io = NULL;
11976 r = cui(vcpu);
11977 if (r <= 0)
11978 goto out;
11979 } else {
11980 WARN_ON_ONCE(vcpu->arch.pio.count);
11981 WARN_ON_ONCE(vcpu->mmio_needed);
11982 }
11983
11984 if (!vcpu->wants_to_run) {
11985 r = -EINTR;
11986 goto out;
11987 }
11988
11989 r = kvm_x86_vcpu_pre_run(vcpu);
11990 if (r <= 0)
11991 goto out;
11992
11993 r = vcpu_run(vcpu);
11994
11995 out:
11996 kvm_put_guest_fpu(vcpu);
11997 if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
11998 store_regs(vcpu);
11999 post_kvm_run_save(vcpu);
12000 kvm_vcpu_srcu_read_unlock(vcpu);
12001
12002 kvm_sigset_deactivate(vcpu);
12003 vcpu_put(vcpu);
12004 return r;
12005 }
12006
__get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12007 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12008 {
12009 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
12010 /*
12011 * We are here if userspace calls get_regs() in the middle of
12012 * instruction emulation. Registers state needs to be copied
12013 * back from emulation context to vcpu. Userspace shouldn't do
12014 * that usually, but some bad designed PV devices (vmware
12015 * backdoor interface) need this to work
12016 */
12017 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
12018 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
12019 }
12020 regs->rax = kvm_rax_read(vcpu);
12021 regs->rbx = kvm_rbx_read(vcpu);
12022 regs->rcx = kvm_rcx_read(vcpu);
12023 regs->rdx = kvm_rdx_read(vcpu);
12024 regs->rsi = kvm_rsi_read(vcpu);
12025 regs->rdi = kvm_rdi_read(vcpu);
12026 regs->rsp = kvm_rsp_read(vcpu);
12027 regs->rbp = kvm_rbp_read(vcpu);
12028 #ifdef CONFIG_X86_64
12029 regs->r8 = kvm_r8_read(vcpu);
12030 regs->r9 = kvm_r9_read(vcpu);
12031 regs->r10 = kvm_r10_read(vcpu);
12032 regs->r11 = kvm_r11_read(vcpu);
12033 regs->r12 = kvm_r12_read(vcpu);
12034 regs->r13 = kvm_r13_read(vcpu);
12035 regs->r14 = kvm_r14_read(vcpu);
12036 regs->r15 = kvm_r15_read(vcpu);
12037 #endif
12038
12039 regs->rip = kvm_rip_read(vcpu);
12040 regs->rflags = kvm_get_rflags(vcpu);
12041 }
12042
kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12043 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12044 {
12045 if (vcpu->kvm->arch.has_protected_state &&
12046 vcpu->arch.guest_state_protected)
12047 return -EINVAL;
12048
12049 vcpu_load(vcpu);
12050 __get_regs(vcpu, regs);
12051 vcpu_put(vcpu);
12052 return 0;
12053 }
12054
__set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12055 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12056 {
12057 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
12058 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
12059
12060 kvm_rax_write(vcpu, regs->rax);
12061 kvm_rbx_write(vcpu, regs->rbx);
12062 kvm_rcx_write(vcpu, regs->rcx);
12063 kvm_rdx_write(vcpu, regs->rdx);
12064 kvm_rsi_write(vcpu, regs->rsi);
12065 kvm_rdi_write(vcpu, regs->rdi);
12066 kvm_rsp_write(vcpu, regs->rsp);
12067 kvm_rbp_write(vcpu, regs->rbp);
12068 #ifdef CONFIG_X86_64
12069 kvm_r8_write(vcpu, regs->r8);
12070 kvm_r9_write(vcpu, regs->r9);
12071 kvm_r10_write(vcpu, regs->r10);
12072 kvm_r11_write(vcpu, regs->r11);
12073 kvm_r12_write(vcpu, regs->r12);
12074 kvm_r13_write(vcpu, regs->r13);
12075 kvm_r14_write(vcpu, regs->r14);
12076 kvm_r15_write(vcpu, regs->r15);
12077 #endif
12078
12079 kvm_rip_write(vcpu, regs->rip);
12080 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
12081
12082 vcpu->arch.exception.pending = false;
12083 vcpu->arch.exception_vmexit.pending = false;
12084
12085 kvm_make_request(KVM_REQ_EVENT, vcpu);
12086 }
12087
kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12088 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12089 {
12090 if (vcpu->kvm->arch.has_protected_state &&
12091 vcpu->arch.guest_state_protected)
12092 return -EINVAL;
12093
12094 vcpu_load(vcpu);
12095 __set_regs(vcpu, regs);
12096 vcpu_put(vcpu);
12097 return 0;
12098 }
12099
__get_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12100 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12101 {
12102 struct desc_ptr dt;
12103
12104 if (vcpu->arch.guest_state_protected)
12105 goto skip_protected_regs;
12106
12107 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12108 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12109 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12110 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12111 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12112 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12113
12114 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12115 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12116
12117 kvm_x86_call(get_idt)(vcpu, &dt);
12118 sregs->idt.limit = dt.size;
12119 sregs->idt.base = dt.address;
12120 kvm_x86_call(get_gdt)(vcpu, &dt);
12121 sregs->gdt.limit = dt.size;
12122 sregs->gdt.base = dt.address;
12123
12124 sregs->cr2 = vcpu->arch.cr2;
12125 sregs->cr3 = kvm_read_cr3(vcpu);
12126
12127 skip_protected_regs:
12128 sregs->cr0 = kvm_read_cr0(vcpu);
12129 sregs->cr4 = kvm_read_cr4(vcpu);
12130 sregs->cr8 = kvm_get_cr8(vcpu);
12131 sregs->efer = vcpu->arch.efer;
12132 sregs->apic_base = vcpu->arch.apic_base;
12133 }
12134
__get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12135 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12136 {
12137 __get_sregs_common(vcpu, sregs);
12138
12139 if (vcpu->arch.guest_state_protected)
12140 return;
12141
12142 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
12143 set_bit(vcpu->arch.interrupt.nr,
12144 (unsigned long *)sregs->interrupt_bitmap);
12145 }
12146
__get_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12147 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12148 {
12149 int i;
12150
12151 __get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
12152
12153 if (vcpu->arch.guest_state_protected)
12154 return;
12155
12156 if (is_pae_paging(vcpu)) {
12157 for (i = 0 ; i < 4 ; i++)
12158 sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
12159 sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
12160 }
12161 }
12162
kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12163 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
12164 struct kvm_sregs *sregs)
12165 {
12166 if (vcpu->kvm->arch.has_protected_state &&
12167 vcpu->arch.guest_state_protected)
12168 return -EINVAL;
12169
12170 vcpu_load(vcpu);
12171 __get_sregs(vcpu, sregs);
12172 vcpu_put(vcpu);
12173 return 0;
12174 }
12175
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)12176 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
12177 struct kvm_mp_state *mp_state)
12178 {
12179 int r;
12180
12181 vcpu_load(vcpu);
12182 kvm_vcpu_srcu_read_lock(vcpu);
12183
12184 r = kvm_apic_accept_events(vcpu);
12185 if (r < 0)
12186 goto out;
12187 r = 0;
12188
12189 if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
12190 vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
12191 vcpu->arch.pv.pv_unhalted)
12192 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
12193 else
12194 mp_state->mp_state = vcpu->arch.mp_state;
12195
12196 out:
12197 kvm_vcpu_srcu_read_unlock(vcpu);
12198 vcpu_put(vcpu);
12199 return r;
12200 }
12201
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)12202 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
12203 struct kvm_mp_state *mp_state)
12204 {
12205 int ret = -EINVAL;
12206
12207 vcpu_load(vcpu);
12208
12209 switch (mp_state->mp_state) {
12210 case KVM_MP_STATE_UNINITIALIZED:
12211 case KVM_MP_STATE_HALTED:
12212 case KVM_MP_STATE_AP_RESET_HOLD:
12213 case KVM_MP_STATE_INIT_RECEIVED:
12214 case KVM_MP_STATE_SIPI_RECEIVED:
12215 if (!lapic_in_kernel(vcpu))
12216 goto out;
12217 break;
12218
12219 case KVM_MP_STATE_RUNNABLE:
12220 break;
12221
12222 default:
12223 goto out;
12224 }
12225
12226 /*
12227 * SIPI_RECEIVED is obsolete and no longer used internally; KVM instead
12228 * leaves the vCPU in INIT_RECIEVED (Wait-For-SIPI) and pends the SIPI.
12229 * Translate SIPI_RECEIVED as appropriate for backwards compatibility.
12230 */
12231 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
12232 mp_state->mp_state = KVM_MP_STATE_INIT_RECEIVED;
12233 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
12234 }
12235
12236 kvm_set_mp_state(vcpu, mp_state->mp_state);
12237 kvm_make_request(KVM_REQ_EVENT, vcpu);
12238
12239 ret = 0;
12240 out:
12241 vcpu_put(vcpu);
12242 return ret;
12243 }
12244
kvm_task_switch(struct kvm_vcpu * vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code)12245 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
12246 int reason, bool has_error_code, u32 error_code)
12247 {
12248 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
12249 int ret;
12250
12251 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_CET)) {
12252 u64 u_cet, s_cet;
12253
12254 /*
12255 * Check both User and Supervisor on task switches as inter-
12256 * privilege level task switches are impacted by CET at both
12257 * the current privilege level and the new privilege level, and
12258 * that information is not known at this time. The expectation
12259 * is that the guest won't require emulation of task switches
12260 * while using IBT or Shadow Stacks.
12261 */
12262 if (__kvm_emulate_msr_read(vcpu, MSR_IA32_U_CET, &u_cet) ||
12263 __kvm_emulate_msr_read(vcpu, MSR_IA32_S_CET, &s_cet))
12264 goto unhandled_task_switch;
12265
12266 if ((u_cet | s_cet) & (CET_ENDBR_EN | CET_SHSTK_EN))
12267 goto unhandled_task_switch;
12268 }
12269
12270 init_emulate_ctxt(vcpu);
12271
12272 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
12273 has_error_code, error_code);
12274
12275 /*
12276 * Report an error userspace if MMIO is needed, as KVM doesn't support
12277 * MMIO during a task switch (or any other complex operation).
12278 */
12279 if (ret || vcpu->mmio_needed)
12280 goto unhandled_task_switch;
12281
12282 kvm_rip_write(vcpu, ctxt->eip);
12283 kvm_set_rflags(vcpu, ctxt->eflags);
12284 return 1;
12285
12286 unhandled_task_switch:
12287 vcpu->mmio_needed = false;
12288 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
12289 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
12290 vcpu->run->internal.ndata = 0;
12291 return 0;
12292 }
12293 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_task_switch);
12294
kvm_is_valid_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12295 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12296 {
12297 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
12298 /*
12299 * When EFER.LME and CR0.PG are set, the processor is in
12300 * 64-bit mode (though maybe in a 32-bit code segment).
12301 * CR4.PAE and EFER.LMA must be set.
12302 */
12303 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
12304 return false;
12305 if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
12306 return false;
12307 } else {
12308 /*
12309 * Not in 64-bit mode: EFER.LMA is clear and the code
12310 * segment cannot be 64-bit.
12311 */
12312 if (sregs->efer & EFER_LMA || sregs->cs.l)
12313 return false;
12314 }
12315
12316 return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
12317 kvm_is_valid_cr0(vcpu, sregs->cr0);
12318 }
12319
__set_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs,int * mmu_reset_needed,bool update_pdptrs)12320 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
12321 int *mmu_reset_needed, bool update_pdptrs)
12322 {
12323 int idx;
12324 struct desc_ptr dt;
12325
12326 if (!kvm_is_valid_sregs(vcpu, sregs))
12327 return -EINVAL;
12328
12329 if (kvm_apic_set_base(vcpu, sregs->apic_base, true))
12330 return -EINVAL;
12331
12332 if (vcpu->arch.guest_state_protected)
12333 return 0;
12334
12335 dt.size = sregs->idt.limit;
12336 dt.address = sregs->idt.base;
12337 kvm_x86_call(set_idt)(vcpu, &dt);
12338 dt.size = sregs->gdt.limit;
12339 dt.address = sregs->gdt.base;
12340 kvm_x86_call(set_gdt)(vcpu, &dt);
12341
12342 vcpu->arch.cr2 = sregs->cr2;
12343 *mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
12344 vcpu->arch.cr3 = sregs->cr3;
12345 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12346 kvm_x86_call(post_set_cr3)(vcpu, sregs->cr3);
12347
12348 kvm_set_cr8(vcpu, sregs->cr8);
12349
12350 *mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
12351 kvm_x86_call(set_efer)(vcpu, sregs->efer);
12352
12353 *mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
12354 kvm_x86_call(set_cr0)(vcpu, sregs->cr0);
12355
12356 *mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
12357 kvm_x86_call(set_cr4)(vcpu, sregs->cr4);
12358
12359 if (update_pdptrs) {
12360 idx = srcu_read_lock(&vcpu->kvm->srcu);
12361 if (is_pae_paging(vcpu)) {
12362 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
12363 *mmu_reset_needed = 1;
12364 }
12365 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12366 }
12367
12368 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12369 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12370 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12371 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12372 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12373 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12374
12375 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12376 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12377
12378 update_cr8_intercept(vcpu);
12379
12380 /* Older userspace won't unhalt the vcpu on reset. */
12381 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
12382 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
12383 !is_protmode(vcpu))
12384 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12385
12386 return 0;
12387 }
12388
__set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12389 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12390 {
12391 int pending_vec, max_bits;
12392 int mmu_reset_needed = 0;
12393 int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
12394
12395 if (ret)
12396 return ret;
12397
12398 if (mmu_reset_needed) {
12399 kvm_mmu_reset_context(vcpu);
12400 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12401 }
12402
12403 max_bits = KVM_NR_INTERRUPTS;
12404 pending_vec = find_first_bit(
12405 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
12406
12407 if (pending_vec < max_bits) {
12408 kvm_queue_interrupt(vcpu, pending_vec, false);
12409 pr_debug("Set back pending irq %d\n", pending_vec);
12410 kvm_make_request(KVM_REQ_EVENT, vcpu);
12411 }
12412 return 0;
12413 }
12414
__set_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12415 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12416 {
12417 int mmu_reset_needed = 0;
12418 bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
12419 bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
12420 !(sregs2->efer & EFER_LMA);
12421 int i, ret;
12422
12423 if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
12424 return -EINVAL;
12425
12426 if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
12427 return -EINVAL;
12428
12429 ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
12430 &mmu_reset_needed, !valid_pdptrs);
12431 if (ret)
12432 return ret;
12433
12434 if (valid_pdptrs) {
12435 for (i = 0; i < 4 ; i++)
12436 kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
12437
12438 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
12439 mmu_reset_needed = 1;
12440 vcpu->arch.pdptrs_from_userspace = true;
12441 }
12442 if (mmu_reset_needed) {
12443 kvm_mmu_reset_context(vcpu);
12444 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12445 }
12446 return 0;
12447 }
12448
kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12449 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
12450 struct kvm_sregs *sregs)
12451 {
12452 int ret;
12453
12454 if (vcpu->kvm->arch.has_protected_state &&
12455 vcpu->arch.guest_state_protected)
12456 return -EINVAL;
12457
12458 vcpu_load(vcpu);
12459 ret = __set_sregs(vcpu, sregs);
12460 vcpu_put(vcpu);
12461 return ret;
12462 }
12463
kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm * kvm)12464 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
12465 {
12466 bool set = false;
12467 struct kvm_vcpu *vcpu;
12468 unsigned long i;
12469
12470 if (!enable_apicv)
12471 return;
12472
12473 down_write(&kvm->arch.apicv_update_lock);
12474
12475 kvm_for_each_vcpu(i, vcpu, kvm) {
12476 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
12477 set = true;
12478 break;
12479 }
12480 }
12481 __kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
12482 up_write(&kvm->arch.apicv_update_lock);
12483 }
12484
kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu * vcpu,struct kvm_guest_debug * dbg)12485 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
12486 struct kvm_guest_debug *dbg)
12487 {
12488 unsigned long rflags;
12489 int i, r;
12490
12491 if (vcpu->arch.guest_state_protected)
12492 return -EINVAL;
12493
12494 vcpu_load(vcpu);
12495
12496 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
12497 r = -EBUSY;
12498 if (kvm_is_exception_pending(vcpu))
12499 goto out;
12500 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
12501 kvm_queue_exception(vcpu, DB_VECTOR);
12502 else
12503 kvm_queue_exception(vcpu, BP_VECTOR);
12504 }
12505
12506 /*
12507 * Read rflags as long as potentially injected trace flags are still
12508 * filtered out.
12509 */
12510 rflags = kvm_get_rflags(vcpu);
12511
12512 vcpu->guest_debug = dbg->control;
12513 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
12514 vcpu->guest_debug = 0;
12515
12516 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
12517 for (i = 0; i < KVM_NR_DB_REGS; ++i)
12518 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
12519 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
12520 } else {
12521 for (i = 0; i < KVM_NR_DB_REGS; i++)
12522 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
12523 }
12524 kvm_update_dr7(vcpu);
12525
12526 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12527 vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
12528
12529 /*
12530 * Trigger an rflags update that will inject or remove the trace
12531 * flags.
12532 */
12533 kvm_set_rflags(vcpu, rflags);
12534
12535 kvm_x86_call(update_exception_bitmap)(vcpu);
12536
12537 kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12538
12539 r = 0;
12540
12541 out:
12542 vcpu_put(vcpu);
12543 return r;
12544 }
12545
12546 /*
12547 * Translate a guest virtual address to a guest physical address.
12548 */
kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu * vcpu,struct kvm_translation * tr)12549 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12550 struct kvm_translation *tr)
12551 {
12552 unsigned long vaddr = tr->linear_address;
12553 gpa_t gpa;
12554 int idx;
12555
12556 vcpu_load(vcpu);
12557
12558 idx = srcu_read_lock(&vcpu->kvm->srcu);
12559 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
12560 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12561 tr->physical_address = gpa;
12562 tr->valid = gpa != INVALID_GPA;
12563 tr->writeable = 1;
12564 tr->usermode = 0;
12565
12566 vcpu_put(vcpu);
12567 return 0;
12568 }
12569
kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12570 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12571 {
12572 struct fxregs_state *fxsave;
12573
12574 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12575 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12576
12577 vcpu_load(vcpu);
12578
12579 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12580 memcpy(fpu->fpr, fxsave->st_space, 128);
12581 fpu->fcw = fxsave->cwd;
12582 fpu->fsw = fxsave->swd;
12583 fpu->ftwx = fxsave->twd;
12584 fpu->last_opcode = fxsave->fop;
12585 fpu->last_ip = fxsave->rip;
12586 fpu->last_dp = fxsave->rdp;
12587 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
12588
12589 vcpu_put(vcpu);
12590 return 0;
12591 }
12592
kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12593 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12594 {
12595 struct fxregs_state *fxsave;
12596
12597 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12598 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12599
12600 vcpu_load(vcpu);
12601
12602 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12603
12604 memcpy(fxsave->st_space, fpu->fpr, 128);
12605 fxsave->cwd = fpu->fcw;
12606 fxsave->swd = fpu->fsw;
12607 fxsave->twd = fpu->ftwx;
12608 fxsave->fop = fpu->last_opcode;
12609 fxsave->rip = fpu->last_ip;
12610 fxsave->rdp = fpu->last_dp;
12611 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
12612
12613 vcpu_put(vcpu);
12614 return 0;
12615 }
12616
store_regs(struct kvm_vcpu * vcpu)12617 static void store_regs(struct kvm_vcpu *vcpu)
12618 {
12619 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12620
12621 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12622 __get_regs(vcpu, &vcpu->run->s.regs.regs);
12623
12624 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12625 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12626
12627 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12628 kvm_vcpu_ioctl_x86_get_vcpu_events(
12629 vcpu, &vcpu->run->s.regs.events);
12630 }
12631
sync_regs(struct kvm_vcpu * vcpu)12632 static int sync_regs(struct kvm_vcpu *vcpu)
12633 {
12634 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12635 __set_regs(vcpu, &vcpu->run->s.regs.regs);
12636 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12637 }
12638
12639 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
12640 struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12641
12642 if (__set_sregs(vcpu, &sregs))
12643 return -EINVAL;
12644
12645 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12646 }
12647
12648 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
12649 struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12650
12651 if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
12652 return -EINVAL;
12653
12654 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12655 }
12656
12657 return 0;
12658 }
12659
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)12660 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
12661 {
12662 if (kvm_check_tsc_unstable() && kvm->created_vcpus)
12663 pr_warn_once("SMP vm created on host with unstable TSC; "
12664 "guest TSC will not be reliable\n");
12665
12666 if (!kvm->arch.max_vcpu_ids)
12667 kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12668
12669 if (id >= kvm->arch.max_vcpu_ids)
12670 return -EINVAL;
12671
12672 return kvm_x86_call(vcpu_precreate)(kvm);
12673 }
12674
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)12675 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
12676 {
12677 struct page *page;
12678 int r;
12679
12680 vcpu->arch.last_vmentry_cpu = -1;
12681 vcpu->arch.regs_avail = ~0;
12682 vcpu->arch.regs_dirty = ~0;
12683
12684 kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
12685
12686 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
12687 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12688 else
12689 kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);
12690
12691 r = kvm_mmu_create(vcpu);
12692 if (r < 0)
12693 return r;
12694
12695 r = kvm_create_lapic(vcpu);
12696 if (r < 0)
12697 goto fail_mmu_destroy;
12698
12699 r = -ENOMEM;
12700
12701 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
12702 if (!page)
12703 goto fail_free_lapic;
12704 vcpu->arch.pio_data = page_address(page);
12705
12706 vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
12707 GFP_KERNEL_ACCOUNT);
12708 vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12709 GFP_KERNEL_ACCOUNT);
12710 if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
12711 goto fail_free_mce_banks;
12712 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12713
12714 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12715 GFP_KERNEL_ACCOUNT))
12716 goto fail_free_mce_banks;
12717
12718 if (!alloc_emulate_ctxt(vcpu))
12719 goto free_wbinvd_dirty_mask;
12720
12721 if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
12722 pr_err("failed to allocate vcpu's fpu\n");
12723 goto free_emulate_ctxt;
12724 }
12725
12726 kvm_async_pf_hash_reset(vcpu);
12727
12728 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) {
12729 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12730 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12731 vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12732 }
12733 kvm_pmu_init(vcpu);
12734
12735 vcpu->arch.pending_external_vector = -1;
12736 vcpu->arch.preempted_in_kernel = false;
12737
12738 #if IS_ENABLED(CONFIG_HYPERV)
12739 vcpu->arch.hv_root_tdp = INVALID_PAGE;
12740 #endif
12741
12742 r = kvm_x86_call(vcpu_create)(vcpu);
12743 if (r)
12744 goto free_guest_fpu;
12745
12746 kvm_xen_init_vcpu(vcpu);
12747 vcpu_load(vcpu);
12748 kvm_vcpu_after_set_cpuid(vcpu);
12749 kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12750 kvm_vcpu_reset(vcpu, false);
12751 kvm_init_mmu(vcpu);
12752 vcpu_put(vcpu);
12753 return 0;
12754
12755 free_guest_fpu:
12756 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12757 free_emulate_ctxt:
12758 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12759 free_wbinvd_dirty_mask:
12760 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12761 fail_free_mce_banks:
12762 kfree(vcpu->arch.mce_banks);
12763 kfree(vcpu->arch.mci_ctl2_banks);
12764 free_page((unsigned long)vcpu->arch.pio_data);
12765 fail_free_lapic:
12766 kvm_free_lapic(vcpu);
12767 fail_mmu_destroy:
12768 kvm_mmu_destroy(vcpu);
12769 return r;
12770 }
12771
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)12772 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12773 {
12774 if (mutex_lock_killable(&vcpu->mutex))
12775 return;
12776 vcpu_load(vcpu);
12777 kvm_synchronize_tsc(vcpu, NULL);
12778 vcpu_put(vcpu);
12779
12780 /* poll control enabled by default */
12781 vcpu->arch.msr_kvm_poll_control = 1;
12782
12783 mutex_unlock(&vcpu->mutex);
12784 }
12785
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)12786 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12787 {
12788 int idx, cpu;
12789
12790 kvm_clear_async_pf_completion_queue(vcpu);
12791 kvm_mmu_unload(vcpu);
12792
12793 kvmclock_reset(vcpu);
12794
12795 for_each_possible_cpu(cpu)
12796 cmpxchg(per_cpu_ptr(&last_vcpu, cpu), vcpu, NULL);
12797
12798 kvm_x86_call(vcpu_free)(vcpu);
12799
12800 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12801 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12802 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12803
12804 kvm_xen_destroy_vcpu(vcpu);
12805 kvm_hv_vcpu_uninit(vcpu);
12806 kvm_pmu_destroy(vcpu);
12807 kfree(vcpu->arch.mce_banks);
12808 kfree(vcpu->arch.mci_ctl2_banks);
12809 kvm_free_lapic(vcpu);
12810 idx = srcu_read_lock(&vcpu->kvm->srcu);
12811 kvm_mmu_destroy(vcpu);
12812 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12813 free_page((unsigned long)vcpu->arch.pio_data);
12814 kvfree(vcpu->arch.cpuid_entries);
12815 }
12816
kvm_xstate_reset(struct kvm_vcpu * vcpu,bool init_event)12817 static void kvm_xstate_reset(struct kvm_vcpu *vcpu, bool init_event)
12818 {
12819 struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12820 u64 xfeatures_mask;
12821 bool fpu_in_use;
12822 int i;
12823
12824 /*
12825 * Guest FPU state is zero allocated and so doesn't need to be manually
12826 * cleared on RESET, i.e. during vCPU creation.
12827 */
12828 if (!init_event || !fpstate)
12829 return;
12830
12831 /*
12832 * On INIT, only select XSTATE components are zeroed, most components
12833 * are unchanged. Currently, the only components that are zeroed and
12834 * supported by KVM are MPX and CET related.
12835 */
12836 xfeatures_mask = (kvm_caps.supported_xcr0 | kvm_caps.supported_xss) &
12837 (XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR |
12838 XFEATURE_MASK_CET_ALL);
12839 if (!xfeatures_mask)
12840 return;
12841
12842 BUILD_BUG_ON(sizeof(xfeatures_mask) * BITS_PER_BYTE <= XFEATURE_MAX);
12843
12844 /*
12845 * Unload guest FPU state (if necessary) before zeroing XSTATE fields
12846 * as the kernel can only modify the state when its resident in memory,
12847 * i.e. when it's not loaded into hardware.
12848 *
12849 * WARN if the vCPU's desire to run, i.e. whether or not its in KVM_RUN,
12850 * doesn't match the loaded/in-use state of the FPU, as KVM_RUN is the
12851 * only path that can trigger INIT emulation _and_ loads FPU state, and
12852 * KVM_RUN should _always_ load FPU state.
12853 */
12854 WARN_ON_ONCE(vcpu->wants_to_run != fpstate->in_use);
12855 fpu_in_use = fpstate->in_use;
12856 if (fpu_in_use)
12857 kvm_put_guest_fpu(vcpu);
12858 for_each_set_bit(i, (unsigned long *)&xfeatures_mask, XFEATURE_MAX)
12859 fpstate_clear_xstate_component(fpstate, i);
12860 if (fpu_in_use)
12861 kvm_load_guest_fpu(vcpu);
12862 }
12863
kvm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)12864 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
12865 {
12866 struct kvm_cpuid_entry2 *cpuid_0x1;
12867 unsigned long old_cr0 = kvm_read_cr0(vcpu);
12868 unsigned long new_cr0;
12869
12870 /*
12871 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12872 * to handle side effects. RESET emulation hits those flows and relies
12873 * on emulated/virtualized registers, including those that are loaded
12874 * into hardware, to be zeroed at vCPU creation. Use CRs as a sentinel
12875 * to detect improper or missing initialization.
12876 */
12877 WARN_ON_ONCE(!init_event &&
12878 (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
12879
12880 /*
12881 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12882 * possible to INIT the vCPU while L2 is active. Force the vCPU back
12883 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12884 * bits), i.e. virtualization is disabled.
12885 */
12886 if (is_guest_mode(vcpu))
12887 kvm_leave_nested(vcpu);
12888
12889 kvm_lapic_reset(vcpu, init_event);
12890
12891 WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
12892 vcpu->arch.hflags = 0;
12893
12894 vcpu->arch.smi_pending = 0;
12895 vcpu->arch.smi_count = 0;
12896 atomic_set(&vcpu->arch.nmi_queued, 0);
12897 vcpu->arch.nmi_pending = 0;
12898 vcpu->arch.nmi_injected = false;
12899 kvm_clear_interrupt_queue(vcpu);
12900 kvm_clear_exception_queue(vcpu);
12901
12902 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
12903 kvm_update_dr0123(vcpu);
12904 vcpu->arch.dr6 = DR6_ACTIVE_LOW;
12905 vcpu->arch.dr7 = DR7_FIXED_1;
12906 kvm_update_dr7(vcpu);
12907
12908 vcpu->arch.cr2 = 0;
12909
12910 kvm_make_request(KVM_REQ_EVENT, vcpu);
12911 vcpu->arch.apf.msr_en_val = 0;
12912 vcpu->arch.apf.msr_int_val = 0;
12913 vcpu->arch.st.msr_val = 0;
12914
12915 kvmclock_reset(vcpu);
12916
12917 kvm_clear_async_pf_completion_queue(vcpu);
12918 kvm_async_pf_hash_reset(vcpu);
12919 vcpu->arch.apf.halted = false;
12920
12921 kvm_xstate_reset(vcpu, init_event);
12922
12923 if (!init_event) {
12924 vcpu->arch.smbase = 0x30000;
12925
12926 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
12927
12928 vcpu->arch.msr_misc_features_enables = 0;
12929 vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12930 MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
12931
12932 __kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12933 kvm_msr_write(vcpu, MSR_IA32_XSS, 0);
12934 }
12935
12936 /* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
12937 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
12938 kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
12939
12940 /*
12941 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12942 * if no CPUID match is found. Note, it's impossible to get a match at
12943 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
12944 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12945 * on RESET. But, go through the motions in case that's ever remedied.
12946 */
12947 cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
12948 kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
12949
12950 kvm_x86_call(vcpu_reset)(vcpu, init_event);
12951
12952 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12953 kvm_rip_write(vcpu, 0xfff0);
12954
12955 vcpu->arch.cr3 = 0;
12956 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12957
12958 /*
12959 * CR0.CD/NW are set on RESET, preserved on INIT. Note, some versions
12960 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12961 * (or qualify) that with a footnote stating that CD/NW are preserved.
12962 */
12963 new_cr0 = X86_CR0_ET;
12964 if (init_event)
12965 new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12966 else
12967 new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12968
12969 kvm_x86_call(set_cr0)(vcpu, new_cr0);
12970 kvm_x86_call(set_cr4)(vcpu, 0);
12971 kvm_x86_call(set_efer)(vcpu, 0);
12972 kvm_x86_call(update_exception_bitmap)(vcpu);
12973
12974 /*
12975 * On the standard CR0/CR4/EFER modification paths, there are several
12976 * complex conditions determining whether the MMU has to be reset and/or
12977 * which PCIDs have to be flushed. However, CR0.WP and the paging-related
12978 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12979 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12980 * CR0 will be '0' prior to RESET). So we only need to check CR0.PG here.
12981 */
12982 if (old_cr0 & X86_CR0_PG) {
12983 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12984 kvm_mmu_reset_context(vcpu);
12985 }
12986
12987 /*
12988 * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
12989 * APM states the TLBs are untouched by INIT, but it also states that
12990 * the TLBs are flushed on "External initialization of the processor."
12991 * Flush the guest TLB regardless of vendor, there is no meaningful
12992 * benefit in relying on the guest to flush the TLB immediately after
12993 * INIT. A spurious TLB flush is benign and likely negligible from a
12994 * performance perspective.
12995 */
12996 if (init_event)
12997 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12998 }
12999 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_reset);
13000
kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)13001 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
13002 {
13003 struct kvm_segment cs;
13004
13005 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
13006 cs.selector = vector << 8;
13007 cs.base = vector << 12;
13008 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
13009 kvm_rip_write(vcpu, 0);
13010 }
13011 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_deliver_sipi_vector);
13012
kvm_arch_enable_virtualization(void)13013 void kvm_arch_enable_virtualization(void)
13014 {
13015 cpu_emergency_register_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
13016 }
13017
kvm_arch_disable_virtualization(void)13018 void kvm_arch_disable_virtualization(void)
13019 {
13020 cpu_emergency_unregister_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
13021 }
13022
kvm_arch_enable_virtualization_cpu(void)13023 int kvm_arch_enable_virtualization_cpu(void)
13024 {
13025 struct kvm *kvm;
13026 struct kvm_vcpu *vcpu;
13027 unsigned long i;
13028 int ret;
13029 u64 local_tsc;
13030 u64 max_tsc = 0;
13031 bool stable, backwards_tsc = false;
13032
13033 kvm_user_return_msr_cpu_online();
13034
13035 ret = kvm_x86_check_processor_compatibility();
13036 if (ret)
13037 return ret;
13038
13039 ret = kvm_x86_call(enable_virtualization_cpu)();
13040 if (ret != 0)
13041 return ret;
13042
13043 local_tsc = rdtsc();
13044 stable = !kvm_check_tsc_unstable();
13045 list_for_each_entry(kvm, &vm_list, vm_list) {
13046 kvm_for_each_vcpu(i, vcpu, kvm) {
13047 if (!stable && vcpu->cpu == smp_processor_id())
13048 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
13049 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
13050 backwards_tsc = true;
13051 if (vcpu->arch.last_host_tsc > max_tsc)
13052 max_tsc = vcpu->arch.last_host_tsc;
13053 }
13054 }
13055 }
13056
13057 /*
13058 * Sometimes, even reliable TSCs go backwards. This happens on
13059 * platforms that reset TSC during suspend or hibernate actions, but
13060 * maintain synchronization. We must compensate. Fortunately, we can
13061 * detect that condition here, which happens early in CPU bringup,
13062 * before any KVM threads can be running. Unfortunately, we can't
13063 * bring the TSCs fully up to date with real time, as we aren't yet far
13064 * enough into CPU bringup that we know how much real time has actually
13065 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
13066 * variables that haven't been updated yet.
13067 *
13068 * So we simply find the maximum observed TSC above, then record the
13069 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
13070 * the adjustment will be applied. Note that we accumulate
13071 * adjustments, in case multiple suspend cycles happen before some VCPU
13072 * gets a chance to run again. In the event that no KVM threads get a
13073 * chance to run, we will miss the entire elapsed period, as we'll have
13074 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
13075 * loose cycle time. This isn't too big a deal, since the loss will be
13076 * uniform across all VCPUs (not to mention the scenario is extremely
13077 * unlikely). It is possible that a second hibernate recovery happens
13078 * much faster than a first, causing the observed TSC here to be
13079 * smaller; this would require additional padding adjustment, which is
13080 * why we set last_host_tsc to the local tsc observed here.
13081 *
13082 * N.B. - this code below runs only on platforms with reliable TSC,
13083 * as that is the only way backwards_tsc is set above. Also note
13084 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
13085 * have the same delta_cyc adjustment applied if backwards_tsc
13086 * is detected. Note further, this adjustment is only done once,
13087 * as we reset last_host_tsc on all VCPUs to stop this from being
13088 * called multiple times (one for each physical CPU bringup).
13089 *
13090 * Platforms with unreliable TSCs don't have to deal with this, they
13091 * will be compensated by the logic in vcpu_load, which sets the TSC to
13092 * catchup mode. This will catchup all VCPUs to real time, but cannot
13093 * guarantee that they stay in perfect synchronization.
13094 */
13095 if (backwards_tsc) {
13096 u64 delta_cyc = max_tsc - local_tsc;
13097 list_for_each_entry(kvm, &vm_list, vm_list) {
13098 kvm->arch.backwards_tsc_observed = true;
13099 kvm_for_each_vcpu(i, vcpu, kvm) {
13100 vcpu->arch.tsc_offset_adjustment += delta_cyc;
13101 vcpu->arch.last_host_tsc = local_tsc;
13102 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
13103 }
13104
13105 /*
13106 * We have to disable TSC offset matching.. if you were
13107 * booting a VM while issuing an S4 host suspend....
13108 * you may have some problem. Solving this issue is
13109 * left as an exercise to the reader.
13110 */
13111 kvm->arch.last_tsc_nsec = 0;
13112 kvm->arch.last_tsc_write = 0;
13113 }
13114
13115 }
13116 return 0;
13117 }
13118
kvm_arch_disable_virtualization_cpu(void)13119 void kvm_arch_disable_virtualization_cpu(void)
13120 {
13121 kvm_x86_call(disable_virtualization_cpu)();
13122
13123 /*
13124 * Leave the user-return notifiers as-is when disabling virtualization
13125 * for reboot, i.e. when disabling via IPI function call, and instead
13126 * pin kvm.ko (if it's a module) to defend against use-after-free (in
13127 * the *very* unlikely scenario module unload is racing with reboot).
13128 * On a forced reboot, tasks aren't frozen before shutdown, and so KVM
13129 * could be actively modifying user-return MSR state when the IPI to
13130 * disable virtualization arrives. Handle the extreme edge case here
13131 * instead of trying to account for it in the normal flows.
13132 */
13133 if (in_task() || WARN_ON_ONCE(!kvm_rebooting))
13134 drop_user_return_notifiers();
13135 else
13136 __module_get(THIS_MODULE);
13137 }
13138
kvm_vcpu_is_reset_bsp(struct kvm_vcpu * vcpu)13139 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
13140 {
13141 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
13142 }
13143 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_is_reset_bsp);
13144
kvm_vcpu_is_bsp(struct kvm_vcpu * vcpu)13145 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
13146 {
13147 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
13148 }
13149
kvm_arch_free_vm(struct kvm * kvm)13150 void kvm_arch_free_vm(struct kvm *kvm)
13151 {
13152 #if IS_ENABLED(CONFIG_HYPERV)
13153 kfree(kvm->arch.hv_pa_pg);
13154 #endif
13155 __kvm_arch_free_vm(kvm);
13156 }
13157
13158
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)13159 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
13160 {
13161 int ret;
13162 unsigned long flags;
13163
13164 if (!kvm_is_vm_type_supported(type))
13165 return -EINVAL;
13166
13167 kvm->arch.vm_type = type;
13168 kvm->arch.has_private_mem =
13169 (type == KVM_X86_SW_PROTECTED_VM);
13170 /* Decided by the vendor code for other VM types. */
13171 kvm->arch.pre_fault_allowed =
13172 type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
13173 kvm->arch.disabled_quirks = kvm_caps.inapplicable_quirks & kvm_caps.supported_quirks;
13174
13175 ret = kvm_page_track_init(kvm);
13176 if (ret)
13177 goto out;
13178
13179 ret = kvm_mmu_init_vm(kvm);
13180 if (ret)
13181 goto out_cleanup_page_track;
13182
13183 ret = kvm_x86_call(vm_init)(kvm);
13184 if (ret)
13185 goto out_uninit_mmu;
13186
13187 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
13188
13189 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
13190 mutex_init(&kvm->arch.apic_map_lock);
13191 seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
13192 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
13193
13194 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
13195 pvclock_update_vm_gtod_copy(kvm);
13196 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
13197
13198 kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
13199 kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
13200 kvm->arch.guest_can_read_msr_platform_info = true;
13201 kvm->arch.enable_pmu = enable_pmu;
13202
13203 #if IS_ENABLED(CONFIG_HYPERV)
13204 spin_lock_init(&kvm->arch.hv_root_tdp_lock);
13205 kvm->arch.hv_root_tdp = INVALID_PAGE;
13206 #endif
13207
13208 kvm_apicv_init(kvm);
13209 kvm_hv_init_vm(kvm);
13210 kvm_xen_init_vm(kvm);
13211
13212 if (ignore_msrs && !report_ignored_msrs) {
13213 pr_warn_once("Running KVM with ignore_msrs=1 and report_ignored_msrs=0 is not a\n"
13214 "a supported configuration. Lying to the guest about the existence of MSRs\n"
13215 "may cause the guest operating system to hang or produce errors. If a guest\n"
13216 "does not run without ignore_msrs=1, please report it to kvm@vger.kernel.org.\n");
13217 }
13218
13219 once_init(&kvm->arch.nx_once);
13220 return 0;
13221
13222 out_uninit_mmu:
13223 kvm_mmu_uninit_vm(kvm);
13224 out_cleanup_page_track:
13225 kvm_page_track_cleanup(kvm);
13226 out:
13227 return ret;
13228 }
13229
13230 /**
13231 * __x86_set_memory_region: Setup KVM internal memory slot
13232 *
13233 * @kvm: the kvm pointer to the VM.
13234 * @id: the slot ID to setup.
13235 * @gpa: the GPA to install the slot (unused when @size == 0).
13236 * @size: the size of the slot. Set to zero to uninstall a slot.
13237 *
13238 * This function helps to setup a KVM internal memory slot. Specify
13239 * @size > 0 to install a new slot, while @size == 0 to uninstall a
13240 * slot. The return code can be one of the following:
13241 *
13242 * HVA: on success (uninstall will return a bogus HVA)
13243 * -errno: on error
13244 *
13245 * The caller should always use IS_ERR() to check the return value
13246 * before use. Note, the KVM internal memory slots are guaranteed to
13247 * remain valid and unchanged until the VM is destroyed, i.e., the
13248 * GPA->HVA translation will not change. However, the HVA is a user
13249 * address, i.e. its accessibility is not guaranteed, and must be
13250 * accessed via __copy_{to,from}_user().
13251 */
__x86_set_memory_region(struct kvm * kvm,int id,gpa_t gpa,u32 size)13252 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
13253 u32 size)
13254 {
13255 int i, r;
13256 unsigned long hva, old_npages;
13257 struct kvm_memslots *slots = kvm_memslots(kvm);
13258 struct kvm_memory_slot *slot;
13259
13260 lockdep_assert_held(&kvm->slots_lock);
13261
13262 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
13263 return ERR_PTR_USR(-EINVAL);
13264
13265 slot = id_to_memslot(slots, id);
13266 if (size) {
13267 if (slot && slot->npages)
13268 return ERR_PTR_USR(-EEXIST);
13269
13270 /*
13271 * MAP_SHARED to prevent internal slot pages from being moved
13272 * by fork()/COW.
13273 */
13274 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
13275 MAP_SHARED | MAP_ANONYMOUS, 0);
13276 if (IS_ERR_VALUE(hva))
13277 return (void __user *)hva;
13278 } else {
13279 if (!slot || !slot->npages)
13280 return NULL;
13281
13282 old_npages = slot->npages;
13283 hva = slot->userspace_addr;
13284 }
13285
13286 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
13287 struct kvm_userspace_memory_region2 m;
13288
13289 m.slot = id | (i << 16);
13290 m.flags = 0;
13291 m.guest_phys_addr = gpa;
13292 m.userspace_addr = hva;
13293 m.memory_size = size;
13294 r = kvm_set_internal_memslot(kvm, &m);
13295 if (r < 0)
13296 return ERR_PTR_USR(r);
13297 }
13298
13299 if (!size)
13300 vm_munmap(hva, old_npages * PAGE_SIZE);
13301
13302 return (void __user *)hva;
13303 }
13304 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__x86_set_memory_region);
13305
kvm_arch_pre_destroy_vm(struct kvm * kvm)13306 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
13307 {
13308 /*
13309 * Stop all background workers and kthreads before destroying vCPUs, as
13310 * iterating over vCPUs in a different task while vCPUs are being freed
13311 * is unsafe, i.e. will lead to use-after-free. The PIT also needs to
13312 * be stopped before IRQ routing is freed.
13313 */
13314 #ifdef CONFIG_KVM_IOAPIC
13315 kvm_free_pit(kvm);
13316 #endif
13317
13318 kvm_mmu_pre_destroy_vm(kvm);
13319 static_call_cond(kvm_x86_vm_pre_destroy)(kvm);
13320 }
13321
kvm_arch_destroy_vm(struct kvm * kvm)13322 void kvm_arch_destroy_vm(struct kvm *kvm)
13323 {
13324 if (current->mm == kvm->mm) {
13325 /*
13326 * Free memory regions allocated on behalf of userspace,
13327 * unless the memory map has changed due to process exit
13328 * or fd copying.
13329 */
13330 mutex_lock(&kvm->slots_lock);
13331 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
13332 0, 0);
13333 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
13334 0, 0);
13335 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
13336 mutex_unlock(&kvm->slots_lock);
13337 }
13338 kvm_destroy_vcpus(kvm);
13339 kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
13340 #ifdef CONFIG_KVM_IOAPIC
13341 kvm_pic_destroy(kvm);
13342 kvm_ioapic_destroy(kvm);
13343 #endif
13344 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
13345 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
13346 kvm_mmu_uninit_vm(kvm);
13347 kvm_page_track_cleanup(kvm);
13348 kvm_xen_destroy_vm(kvm);
13349 kvm_hv_destroy_vm(kvm);
13350 kvm_x86_call(vm_destroy)(kvm);
13351 }
13352
memslot_rmap_free(struct kvm_memory_slot * slot)13353 static void memslot_rmap_free(struct kvm_memory_slot *slot)
13354 {
13355 int i;
13356
13357 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13358 vfree(slot->arch.rmap[i]);
13359 slot->arch.rmap[i] = NULL;
13360 }
13361 }
13362
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)13363 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
13364 {
13365 int i;
13366
13367 memslot_rmap_free(slot);
13368
13369 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13370 vfree(slot->arch.lpage_info[i - 1]);
13371 slot->arch.lpage_info[i - 1] = NULL;
13372 }
13373
13374 kvm_page_track_free_memslot(slot);
13375 }
13376
memslot_rmap_alloc(struct kvm_memory_slot * slot,unsigned long npages)13377 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
13378 {
13379 const int sz = sizeof(*slot->arch.rmap[0]);
13380 int i;
13381
13382 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13383 int level = i + 1;
13384 int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13385
13386 if (slot->arch.rmap[i])
13387 continue;
13388
13389 slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
13390 if (!slot->arch.rmap[i]) {
13391 memslot_rmap_free(slot);
13392 return -ENOMEM;
13393 }
13394 }
13395
13396 return 0;
13397 }
13398
kvm_alloc_memslot_metadata(struct kvm * kvm,struct kvm_memory_slot * slot)13399 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
13400 struct kvm_memory_slot *slot)
13401 {
13402 unsigned long npages = slot->npages;
13403 int i, r;
13404
13405 /*
13406 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
13407 * old arrays will be freed by kvm_set_memory_region() if installing
13408 * the new memslot is successful.
13409 */
13410 memset(&slot->arch, 0, sizeof(slot->arch));
13411
13412 if (kvm_memslots_have_rmaps(kvm)) {
13413 r = memslot_rmap_alloc(slot, npages);
13414 if (r)
13415 return r;
13416 }
13417
13418 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13419 struct kvm_lpage_info *linfo;
13420 unsigned long ugfn;
13421 int lpages;
13422 int level = i + 1;
13423
13424 lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13425
13426 linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
13427 if (!linfo)
13428 goto out_free;
13429
13430 slot->arch.lpage_info[i - 1] = linfo;
13431
13432 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
13433 linfo[0].disallow_lpage = 1;
13434 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
13435 linfo[lpages - 1].disallow_lpage = 1;
13436 ugfn = slot->userspace_addr >> PAGE_SHIFT;
13437 /*
13438 * If the gfn and userspace address are not aligned wrt each
13439 * other, disable large page support for this slot.
13440 */
13441 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
13442 unsigned long j;
13443
13444 for (j = 0; j < lpages; ++j)
13445 linfo[j].disallow_lpage = 1;
13446 }
13447 }
13448
13449 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
13450 kvm_mmu_init_memslot_memory_attributes(kvm, slot);
13451 #endif
13452
13453 if (kvm_page_track_create_memslot(kvm, slot, npages))
13454 goto out_free;
13455
13456 return 0;
13457
13458 out_free:
13459 memslot_rmap_free(slot);
13460
13461 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13462 vfree(slot->arch.lpage_info[i - 1]);
13463 slot->arch.lpage_info[i - 1] = NULL;
13464 }
13465 return -ENOMEM;
13466 }
13467
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)13468 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
13469 {
13470 struct kvm_vcpu *vcpu;
13471 unsigned long i;
13472
13473 /*
13474 * memslots->generation has been incremented.
13475 * mmio generation may have reached its maximum value.
13476 */
13477 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
13478
13479 /* Force re-initialization of steal_time cache */
13480 kvm_for_each_vcpu(i, vcpu, kvm)
13481 kvm_vcpu_kick(vcpu);
13482 }
13483
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)13484 int kvm_arch_prepare_memory_region(struct kvm *kvm,
13485 const struct kvm_memory_slot *old,
13486 struct kvm_memory_slot *new,
13487 enum kvm_mr_change change)
13488 {
13489 /*
13490 * KVM doesn't support moving memslots when there are external page
13491 * trackers attached to the VM, i.e. if KVMGT is in use.
13492 */
13493 if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
13494 return -EINVAL;
13495
13496 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
13497 if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
13498 return -EINVAL;
13499
13500 if (kvm_is_gfn_alias(kvm, new->base_gfn + new->npages - 1))
13501 return -EINVAL;
13502
13503 return kvm_alloc_memslot_metadata(kvm, new);
13504 }
13505
13506 if (change == KVM_MR_FLAGS_ONLY)
13507 memcpy(&new->arch, &old->arch, sizeof(old->arch));
13508 else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
13509 return -EIO;
13510
13511 return 0;
13512 }
13513
13514
kvm_mmu_update_cpu_dirty_logging(struct kvm * kvm,bool enable)13515 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
13516 {
13517 int nr_slots;
13518
13519 if (!kvm->arch.cpu_dirty_log_size)
13520 return;
13521
13522 nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
13523 if ((enable && nr_slots == 1) || !nr_slots)
13524 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
13525 }
13526
kvm_mmu_slot_apply_flags(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13527 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
13528 struct kvm_memory_slot *old,
13529 const struct kvm_memory_slot *new,
13530 enum kvm_mr_change change)
13531 {
13532 u32 old_flags = old ? old->flags : 0;
13533 u32 new_flags = new ? new->flags : 0;
13534 bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
13535
13536 /*
13537 * Update CPU dirty logging if dirty logging is being toggled. This
13538 * applies to all operations.
13539 */
13540 if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
13541 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
13542
13543 /*
13544 * Nothing more to do for RO slots (which can't be dirtied and can't be
13545 * made writable) or CREATE/MOVE/DELETE of a slot.
13546 *
13547 * For a memslot with dirty logging disabled:
13548 * CREATE: No dirty mappings will already exist.
13549 * MOVE/DELETE: The old mappings will already have been cleaned up by
13550 * kvm_arch_flush_shadow_memslot()
13551 *
13552 * For a memslot with dirty logging enabled:
13553 * CREATE: No shadow pages exist, thus nothing to write-protect
13554 * and no dirty bits to clear.
13555 * MOVE/DELETE: The old mappings will already have been cleaned up by
13556 * kvm_arch_flush_shadow_memslot().
13557 */
13558 if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
13559 return;
13560
13561 /*
13562 * READONLY and non-flags changes were filtered out above, and the only
13563 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13564 * logging isn't being toggled on or off.
13565 */
13566 if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
13567 return;
13568
13569 if (!log_dirty_pages) {
13570 /*
13571 * Recover huge page mappings in the slot now that dirty logging
13572 * is disabled, i.e. now that KVM does not have to track guest
13573 * writes at 4KiB granularity.
13574 *
13575 * Dirty logging might be disabled by userspace if an ongoing VM
13576 * live migration is cancelled and the VM must continue running
13577 * on the source.
13578 */
13579 kvm_mmu_recover_huge_pages(kvm, new);
13580 } else {
13581 /*
13582 * Initially-all-set does not require write protecting any page,
13583 * because they're all assumed to be dirty.
13584 */
13585 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13586 return;
13587
13588 if (READ_ONCE(eager_page_split))
13589 kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13590
13591 if (kvm->arch.cpu_dirty_log_size) {
13592 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13593 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13594 } else {
13595 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
13596 }
13597
13598 /*
13599 * Unconditionally flush the TLBs after enabling dirty logging.
13600 * A flush is almost always going to be necessary (see below),
13601 * and unconditionally flushing allows the helpers to omit
13602 * the subtly complex checks when removing write access.
13603 *
13604 * Do the flush outside of mmu_lock to reduce the amount of
13605 * time mmu_lock is held. Flushing after dropping mmu_lock is
13606 * safe as KVM only needs to guarantee the slot is fully
13607 * write-protected before returning to userspace, i.e. before
13608 * userspace can consume the dirty status.
13609 *
13610 * Flushing outside of mmu_lock requires KVM to be careful when
13611 * making decisions based on writable status of an SPTE, e.g. a
13612 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13613 *
13614 * Specifically, KVM also write-protects guest page tables to
13615 * monitor changes when using shadow paging, and must guarantee
13616 * no CPUs can write to those page before mmu_lock is dropped.
13617 * Because CPUs may have stale TLB entries at this point, a
13618 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13619 *
13620 * KVM also allows making SPTES writable outside of mmu_lock,
13621 * e.g. to allow dirty logging without taking mmu_lock.
13622 *
13623 * To handle these scenarios, KVM uses a separate software-only
13624 * bit (MMU-writable) to track if a SPTE is !writable due to
13625 * a guest page table being write-protected (KVM clears the
13626 * MMU-writable flag when write-protecting for shadow paging).
13627 *
13628 * The use of MMU-writable is also the primary motivation for
13629 * the unconditional flush. Because KVM must guarantee that a
13630 * CPU doesn't contain stale, writable TLB entries for a
13631 * !MMU-writable SPTE, KVM must flush if it encounters any
13632 * MMU-writable SPTE regardless of whether the actual hardware
13633 * writable bit was set. I.e. KVM is almost guaranteed to need
13634 * to flush, while unconditionally flushing allows the "remove
13635 * write access" helpers to ignore MMU-writable entirely.
13636 *
13637 * See is_writable_pte() for more details (the case involving
13638 * access-tracked SPTEs is particularly relevant).
13639 */
13640 kvm_flush_remote_tlbs_memslot(kvm, new);
13641 }
13642 }
13643
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13644 void kvm_arch_commit_memory_region(struct kvm *kvm,
13645 struct kvm_memory_slot *old,
13646 const struct kvm_memory_slot *new,
13647 enum kvm_mr_change change)
13648 {
13649 if (change == KVM_MR_DELETE)
13650 kvm_page_track_delete_slot(kvm, old);
13651
13652 if (!kvm->arch.n_requested_mmu_pages &&
13653 (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13654 unsigned long nr_mmu_pages;
13655
13656 nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13657 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13658 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13659 }
13660
13661 kvm_mmu_slot_apply_flags(kvm, old, new, change);
13662
13663 /* Free the arrays associated with the old memslot. */
13664 if (change == KVM_MR_MOVE)
13665 kvm_arch_free_memslot(kvm, old);
13666 }
13667
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)13668 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13669 {
13670 WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13671
13672 if (vcpu->arch.guest_state_protected)
13673 return true;
13674
13675 return kvm_x86_call(get_cpl)(vcpu) == 0;
13676 }
13677
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)13678 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13679 {
13680 WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13681
13682 if (vcpu->arch.guest_state_protected)
13683 return 0;
13684
13685 return kvm_rip_read(vcpu);
13686 }
13687
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)13688 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13689 {
13690 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13691 }
13692
kvm_arch_interrupt_allowed(struct kvm_vcpu * vcpu)13693 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13694 {
13695 return kvm_x86_call(interrupt_allowed)(vcpu, false);
13696 }
13697
kvm_get_linear_rip(struct kvm_vcpu * vcpu)13698 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13699 {
13700 /* Can't read the RIP when guest state is protected, just return 0 */
13701 if (vcpu->arch.guest_state_protected)
13702 return 0;
13703
13704 if (is_64_bit_mode(vcpu))
13705 return kvm_rip_read(vcpu);
13706 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13707 kvm_rip_read(vcpu));
13708 }
13709 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_linear_rip);
13710
kvm_is_linear_rip(struct kvm_vcpu * vcpu,unsigned long linear_rip)13711 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13712 {
13713 return kvm_get_linear_rip(vcpu) == linear_rip;
13714 }
13715 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_is_linear_rip);
13716
kvm_get_rflags(struct kvm_vcpu * vcpu)13717 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13718 {
13719 unsigned long rflags;
13720
13721 rflags = kvm_x86_call(get_rflags)(vcpu);
13722 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13723 rflags &= ~X86_EFLAGS_TF;
13724 return rflags;
13725 }
13726 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_rflags);
13727
__kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13728 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13729 {
13730 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13731 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13732 rflags |= X86_EFLAGS_TF;
13733 kvm_x86_call(set_rflags)(vcpu, rflags);
13734 }
13735
kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13736 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13737 {
13738 __kvm_set_rflags(vcpu, rflags);
13739 kvm_make_request(KVM_REQ_EVENT, vcpu);
13740 }
13741 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_rflags);
13742
kvm_async_pf_hash_fn(gfn_t gfn)13743 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13744 {
13745 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13746
13747 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13748 }
13749
kvm_async_pf_next_probe(u32 key)13750 static inline u32 kvm_async_pf_next_probe(u32 key)
13751 {
13752 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13753 }
13754
kvm_add_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13755 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13756 {
13757 u32 key = kvm_async_pf_hash_fn(gfn);
13758
13759 while (vcpu->arch.apf.gfns[key] != ~0)
13760 key = kvm_async_pf_next_probe(key);
13761
13762 vcpu->arch.apf.gfns[key] = gfn;
13763 }
13764
kvm_async_pf_gfn_slot(struct kvm_vcpu * vcpu,gfn_t gfn)13765 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13766 {
13767 int i;
13768 u32 key = kvm_async_pf_hash_fn(gfn);
13769
13770 for (i = 0; i < ASYNC_PF_PER_VCPU &&
13771 (vcpu->arch.apf.gfns[key] != gfn &&
13772 vcpu->arch.apf.gfns[key] != ~0); i++)
13773 key = kvm_async_pf_next_probe(key);
13774
13775 return key;
13776 }
13777
kvm_find_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13778 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13779 {
13780 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13781 }
13782
kvm_del_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13783 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13784 {
13785 u32 i, j, k;
13786
13787 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13788
13789 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13790 return;
13791
13792 while (true) {
13793 vcpu->arch.apf.gfns[i] = ~0;
13794 do {
13795 j = kvm_async_pf_next_probe(j);
13796 if (vcpu->arch.apf.gfns[j] == ~0)
13797 return;
13798 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13799 /*
13800 * k lies cyclically in ]i,j]
13801 * | i.k.j |
13802 * |....j i.k.| or |.k..j i...|
13803 */
13804 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13805 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13806 i = j;
13807 }
13808 }
13809
apf_put_user_notpresent(struct kvm_vcpu * vcpu)13810 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13811 {
13812 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13813
13814 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13815 sizeof(reason));
13816 }
13817
apf_put_user_ready(struct kvm_vcpu * vcpu,u32 token)13818 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13819 {
13820 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13821
13822 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13823 &token, offset, sizeof(token));
13824 }
13825
apf_pageready_slot_free(struct kvm_vcpu * vcpu)13826 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13827 {
13828 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13829 u32 val;
13830
13831 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13832 &val, offset, sizeof(val)))
13833 return false;
13834
13835 return !val;
13836 }
13837
kvm_can_deliver_async_pf(struct kvm_vcpu * vcpu)13838 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13839 {
13840
13841 if (!kvm_pv_async_pf_enabled(vcpu))
13842 return false;
13843
13844 if (!vcpu->arch.apf.send_always &&
13845 (vcpu->arch.guest_state_protected || !kvm_x86_call(get_cpl)(vcpu)))
13846 return false;
13847
13848 if (is_guest_mode(vcpu)) {
13849 /*
13850 * L1 needs to opt into the special #PF vmexits that are
13851 * used to deliver async page faults.
13852 */
13853 return vcpu->arch.apf.delivery_as_pf_vmexit;
13854 } else {
13855 /*
13856 * Play it safe in case the guest temporarily disables paging.
13857 * The real mode IDT in particular is unlikely to have a #PF
13858 * exception setup.
13859 */
13860 return is_paging(vcpu);
13861 }
13862 }
13863
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)13864 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13865 {
13866 if (unlikely(!lapic_in_kernel(vcpu) ||
13867 kvm_event_needs_reinjection(vcpu) ||
13868 kvm_is_exception_pending(vcpu)))
13869 return false;
13870
13871 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13872 return false;
13873
13874 /*
13875 * If interrupts are off we cannot even use an artificial
13876 * halt state.
13877 */
13878 return kvm_arch_interrupt_allowed(vcpu);
13879 }
13880
kvm_arch_async_page_not_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13881 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
13882 struct kvm_async_pf *work)
13883 {
13884 struct x86_exception fault;
13885
13886 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
13887 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
13888
13889 if (kvm_can_deliver_async_pf(vcpu) &&
13890 !apf_put_user_notpresent(vcpu)) {
13891 fault.vector = PF_VECTOR;
13892 fault.error_code_valid = true;
13893 fault.error_code = 0;
13894 fault.nested_page_fault = false;
13895 fault.address = work->arch.token;
13896 fault.async_page_fault = true;
13897 kvm_inject_page_fault(vcpu, &fault);
13898 return true;
13899 } else {
13900 /*
13901 * It is not possible to deliver a paravirtualized asynchronous
13902 * page fault, but putting the guest in an artificial halt state
13903 * can be beneficial nevertheless: if an interrupt arrives, we
13904 * can deliver it timely and perhaps the guest will schedule
13905 * another process. When the instruction that triggered a page
13906 * fault is retried, hopefully the page will be ready in the host.
13907 */
13908 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
13909 return false;
13910 }
13911 }
13912
kvm_arch_async_page_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13913 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13914 struct kvm_async_pf *work)
13915 {
13916 struct kvm_lapic_irq irq = {
13917 .delivery_mode = APIC_DM_FIXED,
13918 .vector = vcpu->arch.apf.vec
13919 };
13920
13921 if (work->wakeup_all)
13922 work->arch.token = ~0; /* broadcast wakeup */
13923 else
13924 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
13925 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
13926
13927 if ((work->wakeup_all || work->notpresent_injected) &&
13928 kvm_pv_async_pf_enabled(vcpu) &&
13929 !apf_put_user_ready(vcpu, work->arch.token)) {
13930 WRITE_ONCE(vcpu->arch.apf.pageready_pending, true);
13931 kvm_apic_set_irq(vcpu, &irq, NULL);
13932 }
13933
13934 vcpu->arch.apf.halted = false;
13935 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
13936 }
13937
kvm_arch_async_page_present_queued(struct kvm_vcpu * vcpu)13938 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13939 {
13940 kvm_make_request(KVM_REQ_APF_READY, vcpu);
13941
13942 /* Pairs with smp_store_mb() in kvm_set_msr_common(). */
13943 smp_mb__after_atomic();
13944
13945 if (!READ_ONCE(vcpu->arch.apf.pageready_pending))
13946 kvm_vcpu_kick(vcpu);
13947 }
13948
kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu * vcpu)13949 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
13950 {
13951 if (!kvm_pv_async_pf_enabled(vcpu))
13952 return true;
13953 else
13954 return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
13955 }
13956
kvm_noncoherent_dma_assignment_start_or_stop(struct kvm * kvm)13957 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
13958 {
13959 /*
13960 * Non-coherent DMA assignment and de-assignment may affect whether or
13961 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
13962 * due to toggling the "ignore PAT" bit. Zap all SPTEs when the first
13963 * (or last) non-coherent device is (un)registered to so that new SPTEs
13964 * with the correct "ignore guest PAT" setting are created.
13965 *
13966 * If KVM always honors guest PAT, however, there is nothing to do.
13967 */
13968 if (kvm_check_has_quirk(kvm, KVM_X86_QUIRK_IGNORE_GUEST_PAT))
13969 kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
13970 }
13971
kvm_arch_register_noncoherent_dma(struct kvm * kvm)13972 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13973 {
13974 if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
13975 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13976 }
13977
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)13978 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13979 {
13980 if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
13981 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13982 }
13983
kvm_arch_has_noncoherent_dma(struct kvm * kvm)13984 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13985 {
13986 return atomic_read(&kvm->arch.noncoherent_dma_count);
13987 }
13988 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_arch_has_noncoherent_dma);
13989
kvm_arch_no_poll(struct kvm_vcpu * vcpu)13990 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13991 {
13992 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13993 }
13994
13995 #ifdef CONFIG_KVM_GUEST_MEMFD
13996 /*
13997 * KVM doesn't yet support initializing guest_memfd memory as shared for VMs
13998 * with private memory (the private vs. shared tracking needs to be moved into
13999 * guest_memfd).
14000 */
kvm_arch_supports_gmem_init_shared(struct kvm * kvm)14001 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm)
14002 {
14003 return !kvm_arch_has_private_mem(kvm);
14004 }
14005
14006 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
kvm_arch_gmem_prepare(struct kvm * kvm,gfn_t gfn,kvm_pfn_t pfn,int max_order)14007 int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
14008 {
14009 return kvm_x86_call(gmem_prepare)(kvm, pfn, gfn, max_order);
14010 }
14011 #endif
14012
14013 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
kvm_arch_gmem_invalidate(kvm_pfn_t start,kvm_pfn_t end)14014 void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
14015 {
14016 kvm_x86_call(gmem_invalidate)(start, end);
14017 }
14018 #endif
14019 #endif
14020
kvm_spec_ctrl_test_value(u64 value)14021 int kvm_spec_ctrl_test_value(u64 value)
14022 {
14023 /*
14024 * test that setting IA32_SPEC_CTRL to given value
14025 * is allowed by the host processor
14026 */
14027
14028 u64 saved_value;
14029 unsigned long flags;
14030 int ret = 0;
14031
14032 local_irq_save(flags);
14033
14034 if (rdmsrq_safe(MSR_IA32_SPEC_CTRL, &saved_value))
14035 ret = 1;
14036 else if (wrmsrq_safe(MSR_IA32_SPEC_CTRL, value))
14037 ret = 1;
14038 else
14039 wrmsrq(MSR_IA32_SPEC_CTRL, saved_value);
14040
14041 local_irq_restore(flags);
14042
14043 return ret;
14044 }
14045 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_spec_ctrl_test_value);
14046
kvm_fixup_and_inject_pf_error(struct kvm_vcpu * vcpu,gva_t gva,u16 error_code)14047 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
14048 {
14049 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
14050 struct x86_exception fault;
14051 u64 access = error_code &
14052 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
14053
14054 if (!(error_code & PFERR_PRESENT_MASK) ||
14055 mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
14056 /*
14057 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
14058 * tables probably do not match the TLB. Just proceed
14059 * with the error code that the processor gave.
14060 */
14061 fault.vector = PF_VECTOR;
14062 fault.error_code_valid = true;
14063 fault.error_code = error_code;
14064 fault.nested_page_fault = false;
14065 fault.address = gva;
14066 fault.async_page_fault = false;
14067 }
14068 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
14069 }
14070 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fixup_and_inject_pf_error);
14071
14072 /*
14073 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
14074 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
14075 * indicates whether exit to userspace is needed.
14076 */
kvm_handle_memory_failure(struct kvm_vcpu * vcpu,int r,struct x86_exception * e)14077 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
14078 struct x86_exception *e)
14079 {
14080 if (r == X86EMUL_PROPAGATE_FAULT) {
14081 if (KVM_BUG_ON(!e, vcpu->kvm))
14082 return -EIO;
14083
14084 kvm_inject_emulated_page_fault(vcpu, e);
14085 return 1;
14086 }
14087
14088 /*
14089 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
14090 * while handling a VMX instruction KVM could've handled the request
14091 * correctly by exiting to userspace and performing I/O but there
14092 * doesn't seem to be a real use-case behind such requests, just return
14093 * KVM_EXIT_INTERNAL_ERROR for now.
14094 */
14095 kvm_prepare_emulation_failure_exit(vcpu);
14096
14097 return 0;
14098 }
14099 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_memory_failure);
14100
kvm_handle_invpcid(struct kvm_vcpu * vcpu,unsigned long type,gva_t gva)14101 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
14102 {
14103 bool pcid_enabled;
14104 struct x86_exception e;
14105 struct {
14106 u64 pcid;
14107 u64 gla;
14108 } operand;
14109 int r;
14110
14111 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
14112 if (r != X86EMUL_CONTINUE)
14113 return kvm_handle_memory_failure(vcpu, r, &e);
14114
14115 if (operand.pcid >> 12 != 0) {
14116 kvm_inject_gp(vcpu, 0);
14117 return 1;
14118 }
14119
14120 pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
14121
14122 switch (type) {
14123 case INVPCID_TYPE_INDIV_ADDR:
14124 /*
14125 * LAM doesn't apply to addresses that are inputs to TLB
14126 * invalidation.
14127 */
14128 if ((!pcid_enabled && (operand.pcid != 0)) ||
14129 is_noncanonical_invlpg_address(operand.gla, vcpu)) {
14130 kvm_inject_gp(vcpu, 0);
14131 return 1;
14132 }
14133 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
14134 return kvm_skip_emulated_instruction(vcpu);
14135
14136 case INVPCID_TYPE_SINGLE_CTXT:
14137 if (!pcid_enabled && (operand.pcid != 0)) {
14138 kvm_inject_gp(vcpu, 0);
14139 return 1;
14140 }
14141
14142 kvm_invalidate_pcid(vcpu, operand.pcid);
14143 return kvm_skip_emulated_instruction(vcpu);
14144
14145 case INVPCID_TYPE_ALL_NON_GLOBAL:
14146 /*
14147 * Currently, KVM doesn't mark global entries in the shadow
14148 * page tables, so a non-global flush just degenerates to a
14149 * global flush. If needed, we could optimize this later by
14150 * keeping track of global entries in shadow page tables.
14151 */
14152
14153 fallthrough;
14154 case INVPCID_TYPE_ALL_INCL_GLOBAL:
14155 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
14156 return kvm_skip_emulated_instruction(vcpu);
14157
14158 default:
14159 kvm_inject_gp(vcpu, 0);
14160 return 1;
14161 }
14162 }
14163 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invpcid);
14164
complete_sev_es_emulated_mmio(struct kvm_vcpu * vcpu)14165 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
14166 {
14167 struct kvm_run *run = vcpu->run;
14168 struct kvm_mmio_fragment *frag;
14169 unsigned int len;
14170
14171 BUG_ON(!vcpu->mmio_needed);
14172
14173 /* Complete previous fragment */
14174 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
14175 len = min(8u, frag->len);
14176 if (!vcpu->mmio_is_write)
14177 memcpy(frag->data, run->mmio.data, len);
14178
14179 if (frag->len <= 8) {
14180 /* Switch to the next fragment. */
14181 frag++;
14182 vcpu->mmio_cur_fragment++;
14183 } else {
14184 /* Go forward to the next mmio piece. */
14185 frag->data += len;
14186 frag->gpa += len;
14187 frag->len -= len;
14188 }
14189
14190 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
14191 vcpu->mmio_needed = 0;
14192
14193 // VMG change, at this point, we're always done
14194 // RIP has already been advanced
14195 return 1;
14196 }
14197
14198 // More MMIO is needed
14199 run->mmio.phys_addr = frag->gpa;
14200 run->mmio.len = min(8u, frag->len);
14201 run->mmio.is_write = vcpu->mmio_is_write;
14202 if (run->mmio.is_write)
14203 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
14204 run->exit_reason = KVM_EXIT_MMIO;
14205
14206 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14207
14208 return 0;
14209 }
14210
kvm_sev_es_mmio_write(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)14211 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
14212 void *data)
14213 {
14214 int handled;
14215 struct kvm_mmio_fragment *frag;
14216
14217 if (!data)
14218 return -EINVAL;
14219
14220 handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
14221 if (handled == bytes)
14222 return 1;
14223
14224 bytes -= handled;
14225 gpa += handled;
14226 data += handled;
14227
14228 /*TODO: Check if need to increment number of frags */
14229 frag = vcpu->mmio_fragments;
14230 vcpu->mmio_nr_fragments = 1;
14231 frag->len = bytes;
14232 frag->gpa = gpa;
14233 frag->data = data;
14234
14235 vcpu->mmio_needed = 1;
14236 vcpu->mmio_cur_fragment = 0;
14237
14238 vcpu->run->mmio.phys_addr = gpa;
14239 vcpu->run->mmio.len = min(8u, frag->len);
14240 vcpu->run->mmio.is_write = 1;
14241 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
14242 vcpu->run->exit_reason = KVM_EXIT_MMIO;
14243
14244 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14245
14246 return 0;
14247 }
14248 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_mmio_write);
14249
kvm_sev_es_mmio_read(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)14250 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
14251 void *data)
14252 {
14253 int handled;
14254 struct kvm_mmio_fragment *frag;
14255
14256 if (!data)
14257 return -EINVAL;
14258
14259 handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
14260 if (handled == bytes)
14261 return 1;
14262
14263 bytes -= handled;
14264 gpa += handled;
14265 data += handled;
14266
14267 /*TODO: Check if need to increment number of frags */
14268 frag = vcpu->mmio_fragments;
14269 vcpu->mmio_nr_fragments = 1;
14270 frag->len = bytes;
14271 frag->gpa = gpa;
14272 frag->data = data;
14273
14274 vcpu->mmio_needed = 1;
14275 vcpu->mmio_cur_fragment = 0;
14276
14277 vcpu->run->mmio.phys_addr = gpa;
14278 vcpu->run->mmio.len = min(8u, frag->len);
14279 vcpu->run->mmio.is_write = 0;
14280 vcpu->run->exit_reason = KVM_EXIT_MMIO;
14281
14282 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14283
14284 return 0;
14285 }
14286 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_mmio_read);
14287
advance_sev_es_emulated_pio(struct kvm_vcpu * vcpu,unsigned count,int size)14288 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
14289 {
14290 vcpu->arch.sev_pio_count -= count;
14291 vcpu->arch.sev_pio_data += count * size;
14292 }
14293
14294 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14295 unsigned int port);
14296
complete_sev_es_emulated_outs(struct kvm_vcpu * vcpu)14297 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
14298 {
14299 int size = vcpu->arch.pio.size;
14300 int port = vcpu->arch.pio.port;
14301
14302 vcpu->arch.pio.count = 0;
14303 if (vcpu->arch.sev_pio_count)
14304 return kvm_sev_es_outs(vcpu, size, port);
14305 return 1;
14306 }
14307
kvm_sev_es_outs(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14308 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14309 unsigned int port)
14310 {
14311 for (;;) {
14312 unsigned int count =
14313 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14314 int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
14315
14316 /* memcpy done already by emulator_pio_out. */
14317 advance_sev_es_emulated_pio(vcpu, count, size);
14318 if (!ret)
14319 break;
14320
14321 /* Emulation done by the kernel. */
14322 if (!vcpu->arch.sev_pio_count)
14323 return 1;
14324 }
14325
14326 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
14327 return 0;
14328 }
14329
14330 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14331 unsigned int port);
14332
complete_sev_es_emulated_ins(struct kvm_vcpu * vcpu)14333 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
14334 {
14335 unsigned count = vcpu->arch.pio.count;
14336 int size = vcpu->arch.pio.size;
14337 int port = vcpu->arch.pio.port;
14338
14339 complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
14340 advance_sev_es_emulated_pio(vcpu, count, size);
14341 if (vcpu->arch.sev_pio_count)
14342 return kvm_sev_es_ins(vcpu, size, port);
14343 return 1;
14344 }
14345
kvm_sev_es_ins(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14346 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14347 unsigned int port)
14348 {
14349 for (;;) {
14350 unsigned int count =
14351 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14352 if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
14353 break;
14354
14355 /* Emulation done by the kernel. */
14356 advance_sev_es_emulated_pio(vcpu, count, size);
14357 if (!vcpu->arch.sev_pio_count)
14358 return 1;
14359 }
14360
14361 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
14362 return 0;
14363 }
14364
kvm_sev_es_string_io(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port,void * data,unsigned int count,int in)14365 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
14366 unsigned int port, void *data, unsigned int count,
14367 int in)
14368 {
14369 vcpu->arch.sev_pio_data = data;
14370 vcpu->arch.sev_pio_count = count;
14371 return in ? kvm_sev_es_ins(vcpu, size, port)
14372 : kvm_sev_es_outs(vcpu, size, port);
14373 }
14374 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_string_io);
14375
14376 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
14377 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
14378 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_mmio);
14379 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
14380 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
14381 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
14382 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
14383 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
14384 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
14385 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
14386 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
14387 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
14388 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
14389 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
14390 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
14391 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
14392 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
14393 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
14394 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
14395 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
14396 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
14397 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
14398 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
14399 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
14400 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
14401 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
14402 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
14403 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
14404 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
14405 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
14406
kvm_x86_init(void)14407 static int __init kvm_x86_init(void)
14408 {
14409 kvm_init_xstate_sizes();
14410
14411 kvm_mmu_x86_module_init();
14412 mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
14413 return 0;
14414 }
14415 module_init(kvm_x86_init);
14416
kvm_x86_exit(void)14417 static void __exit kvm_x86_exit(void)
14418 {
14419 WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
14420 }
14421 module_exit(kvm_x86_exit);
14422