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 <asm/virt.h>
87
88 #include <clocksource/hyperv_timer.h>
89
90 #define CREATE_TRACE_POINTS
91 #include "trace.h"
92
93 #define MAX_IO_MSRS 256
94
95 /*
96 * Note, kvm_caps fields should *never* have default values, all fields must be
97 * recomputed from scratch during vendor module load, e.g. to account for a
98 * vendor module being reloaded with different module parameters.
99 */
100 struct kvm_caps kvm_caps __read_mostly;
101 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_caps);
102
103 struct kvm_host_values kvm_host __read_mostly;
104 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_host);
105
106 #define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
107
108 #define emul_to_vcpu(ctxt) \
109 ((struct kvm_vcpu *)(ctxt)->vcpu)
110
111 /* EFER defaults:
112 * - enable syscall per default because its emulated by KVM
113 * - enable LME and LMA per default on 64 bit KVM
114 */
115 #ifdef CONFIG_X86_64
116 static
117 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
118 #else
119 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
120 #endif
121
122 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
123
124 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
125
126 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
127 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK | \
128 KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST | \
129 KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST)
130
131 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
132 static void process_nmi(struct kvm_vcpu *vcpu);
133 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
134 static void store_regs(struct kvm_vcpu *vcpu);
135 static int sync_regs(struct kvm_vcpu *vcpu);
136 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
137
138 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
139 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
140
141 static DEFINE_MUTEX(vendor_module_lock);
142 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu);
143 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu);
144
145 struct kvm_x86_ops kvm_x86_ops __read_mostly;
146
147 #define KVM_X86_OP(func) \
148 DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
149 *(((struct kvm_x86_ops *)0)->func));
150 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
151 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
152 #include <asm/kvm-x86-ops.h>
153 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
154 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
155
156 static bool __read_mostly ignore_msrs = 0;
157 module_param(ignore_msrs, bool, 0644);
158
159 bool __read_mostly report_ignored_msrs = true;
160 module_param(report_ignored_msrs, bool, 0644);
161 EXPORT_SYMBOL_FOR_KVM_INTERNAL(report_ignored_msrs);
162
163 unsigned int min_timer_period_us = 200;
164 module_param(min_timer_period_us, uint, 0644);
165
166 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
167 static u32 __read_mostly tsc_tolerance_ppm = 250;
168 module_param(tsc_tolerance_ppm, uint, 0644);
169
170 bool __read_mostly enable_vmware_backdoor = false;
171 module_param(enable_vmware_backdoor, bool, 0444);
172 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_vmware_backdoor);
173
174 /*
175 * Flags to manipulate forced emulation behavior (any non-zero value will
176 * enable forced emulation).
177 */
178 #define KVM_FEP_CLEAR_RFLAGS_RF BIT(1)
179 static int __read_mostly force_emulation_prefix;
180 module_param(force_emulation_prefix, int, 0644);
181
182 int __read_mostly pi_inject_timer = -1;
183 module_param(pi_inject_timer, bint, 0644);
184
185 /* Enable/disable PMU virtualization */
186 bool __read_mostly enable_pmu = true;
187 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_pmu);
188 module_param(enable_pmu, bool, 0444);
189
190 /* Enable/disabled mediated PMU virtualization. */
191 bool __read_mostly enable_mediated_pmu;
192 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_mediated_pmu);
193
194 bool __read_mostly eager_page_split = true;
195 module_param(eager_page_split, bool, 0644);
196
197 /* Enable/disable SMT_RSB bug mitigation */
198 static bool __read_mostly mitigate_smt_rsb;
199 module_param(mitigate_smt_rsb, bool, 0444);
200
201 /*
202 * Restoring the host value for MSRs that are only consumed when running in
203 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
204 * returns to userspace, i.e. the kernel can run with the guest's value.
205 */
206 #define KVM_MAX_NR_USER_RETURN_MSRS 16
207
208 struct kvm_user_return_msrs {
209 struct user_return_notifier urn;
210 bool registered;
211 struct kvm_user_return_msr_values {
212 u64 host;
213 u64 curr;
214 } values[KVM_MAX_NR_USER_RETURN_MSRS];
215 };
216
217 u32 __read_mostly kvm_nr_uret_msrs;
218 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_nr_uret_msrs);
219 static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
220 static DEFINE_PER_CPU(struct kvm_user_return_msrs, user_return_msrs);
221
222 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
223 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
224 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
225 | XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
226
227 #define XFEATURE_MASK_CET_ALL (XFEATURE_MASK_CET_USER | XFEATURE_MASK_CET_KERNEL)
228 /*
229 * Note, KVM supports exposing PT to the guest, but does not support context
230 * switching PT via XSTATE (KVM's PT virtualization relies on perf; swapping
231 * PT via guest XSTATE would clobber perf state), i.e. KVM doesn't support
232 * IA32_XSS[bit 8] (guests can/must use RDMSR/WRMSR to save/restore PT MSRs).
233 */
234 #define KVM_SUPPORTED_XSS (XFEATURE_MASK_CET_ALL)
235
236 bool __read_mostly allow_smaller_maxphyaddr = 0;
237 EXPORT_SYMBOL_FOR_KVM_INTERNAL(allow_smaller_maxphyaddr);
238
239 bool __read_mostly enable_apicv = true;
240 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_apicv);
241
242 bool __read_mostly enable_ipiv = true;
243 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_ipiv);
244
245 bool __read_mostly enable_device_posted_irqs = true;
246 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_device_posted_irqs);
247
248 const struct kvm_stats_desc kvm_vm_stats_desc[] = {
249 KVM_GENERIC_VM_STATS(),
250 STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
251 STATS_DESC_COUNTER(VM, mmu_pte_write),
252 STATS_DESC_COUNTER(VM, mmu_pde_zapped),
253 STATS_DESC_COUNTER(VM, mmu_flooded),
254 STATS_DESC_COUNTER(VM, mmu_recycled),
255 STATS_DESC_COUNTER(VM, mmu_cache_miss),
256 STATS_DESC_ICOUNTER(VM, mmu_unsync),
257 STATS_DESC_ICOUNTER(VM, pages_4k),
258 STATS_DESC_ICOUNTER(VM, pages_2m),
259 STATS_DESC_ICOUNTER(VM, pages_1g),
260 STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
261 STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
262 STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
263 };
264
265 const struct kvm_stats_header kvm_vm_stats_header = {
266 .name_size = KVM_STATS_NAME_SIZE,
267 .num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
268 .id_offset = sizeof(struct kvm_stats_header),
269 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
270 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
271 sizeof(kvm_vm_stats_desc),
272 };
273
274 const struct kvm_stats_desc kvm_vcpu_stats_desc[] = {
275 KVM_GENERIC_VCPU_STATS(),
276 STATS_DESC_COUNTER(VCPU, pf_taken),
277 STATS_DESC_COUNTER(VCPU, pf_fixed),
278 STATS_DESC_COUNTER(VCPU, pf_emulate),
279 STATS_DESC_COUNTER(VCPU, pf_spurious),
280 STATS_DESC_COUNTER(VCPU, pf_fast),
281 STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
282 STATS_DESC_COUNTER(VCPU, pf_guest),
283 STATS_DESC_COUNTER(VCPU, tlb_flush),
284 STATS_DESC_COUNTER(VCPU, invlpg),
285 STATS_DESC_COUNTER(VCPU, exits),
286 STATS_DESC_COUNTER(VCPU, io_exits),
287 STATS_DESC_COUNTER(VCPU, mmio_exits),
288 STATS_DESC_COUNTER(VCPU, signal_exits),
289 STATS_DESC_COUNTER(VCPU, irq_window_exits),
290 STATS_DESC_COUNTER(VCPU, nmi_window_exits),
291 STATS_DESC_COUNTER(VCPU, l1d_flush),
292 STATS_DESC_COUNTER(VCPU, halt_exits),
293 STATS_DESC_COUNTER(VCPU, request_irq_exits),
294 STATS_DESC_COUNTER(VCPU, irq_exits),
295 STATS_DESC_COUNTER(VCPU, host_state_reload),
296 STATS_DESC_COUNTER(VCPU, fpu_reload),
297 STATS_DESC_COUNTER(VCPU, insn_emulation),
298 STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
299 STATS_DESC_COUNTER(VCPU, hypercalls),
300 STATS_DESC_COUNTER(VCPU, irq_injections),
301 STATS_DESC_COUNTER(VCPU, nmi_injections),
302 STATS_DESC_COUNTER(VCPU, req_event),
303 STATS_DESC_COUNTER(VCPU, nested_run),
304 STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
305 STATS_DESC_COUNTER(VCPU, directed_yield_successful),
306 STATS_DESC_COUNTER(VCPU, preemption_reported),
307 STATS_DESC_COUNTER(VCPU, preemption_other),
308 STATS_DESC_IBOOLEAN(VCPU, guest_mode),
309 STATS_DESC_COUNTER(VCPU, notify_window_exits),
310 };
311
312 const struct kvm_stats_header kvm_vcpu_stats_header = {
313 .name_size = KVM_STATS_NAME_SIZE,
314 .num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
315 .id_offset = sizeof(struct kvm_stats_header),
316 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
317 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
318 sizeof(kvm_vcpu_stats_desc),
319 };
320
321 static struct kmem_cache *x86_emulator_cache;
322
323 /*
324 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features) track
325 * the set of MSRs that KVM exposes to userspace through KVM_GET_MSRS,
326 * KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST. msrs_to_save holds MSRs that
327 * require host support, i.e. should be probed via RDMSR. emulated_msrs holds
328 * MSRs that KVM emulates without strictly requiring host support.
329 * msr_based_features holds MSRs that enumerate features, i.e. are effectively
330 * CPUID leafs. Note, msr_based_features isn't mutually exclusive with
331 * msrs_to_save and emulated_msrs.
332 */
333
334 static const u32 msrs_to_save_base[] = {
335 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
336 MSR_STAR,
337 #ifdef CONFIG_X86_64
338 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
339 #endif
340 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
341 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
342 MSR_IA32_SPEC_CTRL, MSR_IA32_TSX_CTRL,
343 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
344 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
345 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
346 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
347 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
348 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
349 MSR_IA32_UMWAIT_CONTROL,
350
351 MSR_IA32_XFD, MSR_IA32_XFD_ERR, MSR_IA32_XSS,
352
353 MSR_IA32_U_CET, MSR_IA32_S_CET,
354 MSR_IA32_PL0_SSP, MSR_IA32_PL1_SSP, MSR_IA32_PL2_SSP,
355 MSR_IA32_PL3_SSP, MSR_IA32_INT_SSP_TAB,
356 MSR_IA32_DEBUGCTLMSR,
357 MSR_IA32_LASTBRANCHFROMIP, MSR_IA32_LASTBRANCHTOIP,
358 MSR_IA32_LASTINTFROMIP, MSR_IA32_LASTINTTOIP,
359 };
360
361 static const u32 msrs_to_save_pmu[] = {
362 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
363 MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
364 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
365 MSR_CORE_PERF_GLOBAL_CTRL,
366 MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
367
368 /* This part of MSRs should match KVM_MAX_NR_INTEL_GP_COUNTERS. */
369 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
370 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
371 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
372 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
373 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
374 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
375 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
376 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
377
378 MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
379 MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
380
381 /* This part of MSRs should match KVM_MAX_NR_AMD_GP_COUNTERS. */
382 MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
383 MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
384 MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
385 MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
386
387 MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
388 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
389 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
390 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET,
391 };
392
393 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_base) +
394 ARRAY_SIZE(msrs_to_save_pmu)];
395 static unsigned num_msrs_to_save;
396
397 static const u32 emulated_msrs_all[] = {
398 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
399 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
400
401 #ifdef CONFIG_KVM_HYPERV
402 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
403 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
404 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
405 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
406 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
407 HV_X64_MSR_RESET,
408 HV_X64_MSR_VP_INDEX,
409 HV_X64_MSR_VP_RUNTIME,
410 HV_X64_MSR_SCONTROL,
411 HV_X64_MSR_STIMER0_CONFIG,
412 HV_X64_MSR_VP_ASSIST_PAGE,
413 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
414 HV_X64_MSR_TSC_EMULATION_STATUS, HV_X64_MSR_TSC_INVARIANT_CONTROL,
415 HV_X64_MSR_SYNDBG_OPTIONS,
416 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
417 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
418 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
419 #endif
420
421 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
422 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
423
424 MSR_IA32_TSC_ADJUST,
425 MSR_IA32_TSC_DEADLINE,
426 MSR_IA32_ARCH_CAPABILITIES,
427 MSR_IA32_PERF_CAPABILITIES,
428 MSR_IA32_MISC_ENABLE,
429 MSR_IA32_MCG_STATUS,
430 MSR_IA32_MCG_CTL,
431 MSR_IA32_MCG_EXT_CTL,
432 MSR_IA32_SMBASE,
433 MSR_SMI_COUNT,
434 MSR_PLATFORM_INFO,
435 MSR_MISC_FEATURES_ENABLES,
436 MSR_AMD64_VIRT_SPEC_CTRL,
437 MSR_AMD64_TSC_RATIO,
438 MSR_IA32_POWER_CTL,
439 MSR_IA32_UCODE_REV,
440
441 /*
442 * KVM always supports the "true" VMX control MSRs, even if the host
443 * does not. The VMX MSRs as a whole are considered "emulated" as KVM
444 * doesn't strictly require them to exist in the host (ignoring that
445 * KVM would refuse to load in the first place if the core set of MSRs
446 * aren't supported).
447 */
448 MSR_IA32_VMX_BASIC,
449 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
450 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
451 MSR_IA32_VMX_TRUE_EXIT_CTLS,
452 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
453 MSR_IA32_VMX_MISC,
454 MSR_IA32_VMX_CR0_FIXED0,
455 MSR_IA32_VMX_CR4_FIXED0,
456 MSR_IA32_VMX_VMCS_ENUM,
457 MSR_IA32_VMX_PROCBASED_CTLS2,
458 MSR_IA32_VMX_EPT_VPID_CAP,
459 MSR_IA32_VMX_VMFUNC,
460
461 MSR_K7_HWCR,
462 MSR_KVM_POLL_CONTROL,
463 };
464
465 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
466 static unsigned num_emulated_msrs;
467
468 /*
469 * List of MSRs that control the existence of MSR-based features, i.e. MSRs
470 * that are effectively CPUID leafs. VMX MSRs are also included in the set of
471 * feature MSRs, but are handled separately to allow expedited lookups.
472 */
473 static const u32 msr_based_features_all_except_vmx[] = {
474 MSR_AMD64_DE_CFG,
475 MSR_IA32_UCODE_REV,
476 MSR_IA32_ARCH_CAPABILITIES,
477 MSR_IA32_PERF_CAPABILITIES,
478 MSR_PLATFORM_INFO,
479 };
480
481 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all_except_vmx) +
482 (KVM_LAST_EMULATED_VMX_MSR - KVM_FIRST_EMULATED_VMX_MSR + 1)];
483 static unsigned int num_msr_based_features;
484
485 /*
486 * All feature MSRs except uCode revID, which tracks the currently loaded uCode
487 * patch, are immutable once the vCPU model is defined.
488 */
kvm_is_immutable_feature_msr(u32 msr)489 static bool kvm_is_immutable_feature_msr(u32 msr)
490 {
491 int i;
492
493 if (msr >= KVM_FIRST_EMULATED_VMX_MSR && msr <= KVM_LAST_EMULATED_VMX_MSR)
494 return true;
495
496 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++) {
497 if (msr == msr_based_features_all_except_vmx[i])
498 return msr != MSR_IA32_UCODE_REV;
499 }
500
501 return false;
502 }
503
kvm_is_advertised_msr(u32 msr_index)504 static bool kvm_is_advertised_msr(u32 msr_index)
505 {
506 unsigned int i;
507
508 for (i = 0; i < num_msrs_to_save; i++) {
509 if (msrs_to_save[i] == msr_index)
510 return true;
511 }
512
513 for (i = 0; i < num_emulated_msrs; i++) {
514 if (emulated_msrs[i] == msr_index)
515 return true;
516 }
517
518 return false;
519 }
520
521 typedef int (*msr_access_t)(struct kvm_vcpu *vcpu, u32 index, u64 *data,
522 bool host_initiated);
523
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)524 static __always_inline int kvm_do_msr_access(struct kvm_vcpu *vcpu, u32 msr,
525 u64 *data, bool host_initiated,
526 enum kvm_msr_access rw,
527 msr_access_t msr_access_fn)
528 {
529 const char *op = rw == MSR_TYPE_W ? "wrmsr" : "rdmsr";
530 int ret;
531
532 BUILD_BUG_ON(rw != MSR_TYPE_R && rw != MSR_TYPE_W);
533
534 /*
535 * Zero the data on read failures to avoid leaking stack data to the
536 * guest and/or userspace, e.g. if the failure is ignored below.
537 */
538 ret = msr_access_fn(vcpu, msr, data, host_initiated);
539 if (ret && rw == MSR_TYPE_R)
540 *data = 0;
541
542 if (ret != KVM_MSR_RET_UNSUPPORTED)
543 return ret;
544
545 /*
546 * Userspace is allowed to read MSRs, and write '0' to MSRs, that KVM
547 * advertises to userspace, even if an MSR isn't fully supported.
548 * Simply check that @data is '0', which covers both the write '0' case
549 * and all reads (in which case @data is zeroed on failure; see above).
550 */
551 if (host_initiated && !*data && kvm_is_advertised_msr(msr))
552 return 0;
553
554 if (!ignore_msrs) {
555 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
556 op, msr, *data);
557 return ret;
558 }
559
560 if (report_ignored_msrs)
561 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n", op, msr, *data);
562
563 return 0;
564 }
565
kvm_alloc_emulator_cache(void)566 static struct kmem_cache *kvm_alloc_emulator_cache(void)
567 {
568 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
569 unsigned int size = sizeof(struct x86_emulate_ctxt);
570
571 return kmem_cache_create_usercopy("x86_emulator", size,
572 __alignof__(struct x86_emulate_ctxt),
573 SLAB_ACCOUNT, useroffset,
574 size - useroffset, NULL);
575 }
576
577 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
578
kvm_async_pf_hash_reset(struct kvm_vcpu * vcpu)579 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
580 {
581 int i;
582 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
583 vcpu->arch.apf.gfns[i] = ~0;
584 }
585
kvm_destroy_user_return_msrs(void)586 static void kvm_destroy_user_return_msrs(void)
587 {
588 int cpu;
589
590 for_each_possible_cpu(cpu)
591 WARN_ON_ONCE(per_cpu(user_return_msrs, cpu).registered);
592
593 kvm_nr_uret_msrs = 0;
594 }
595
kvm_on_user_return(struct user_return_notifier * urn)596 static void kvm_on_user_return(struct user_return_notifier *urn)
597 {
598 unsigned slot;
599 struct kvm_user_return_msrs *msrs
600 = container_of(urn, struct kvm_user_return_msrs, urn);
601 struct kvm_user_return_msr_values *values;
602
603 msrs->registered = false;
604 user_return_notifier_unregister(urn);
605
606 for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
607 values = &msrs->values[slot];
608 if (values->host != values->curr) {
609 wrmsrq(kvm_uret_msrs_list[slot], values->host);
610 values->curr = values->host;
611 }
612 }
613 }
614
kvm_probe_user_return_msr(u32 msr)615 static int kvm_probe_user_return_msr(u32 msr)
616 {
617 u64 val;
618 int ret;
619
620 preempt_disable();
621 ret = rdmsrq_safe(msr, &val);
622 if (ret)
623 goto out;
624 ret = wrmsrq_safe(msr, val);
625 out:
626 preempt_enable();
627 return ret;
628 }
629
kvm_add_user_return_msr(u32 msr)630 int kvm_add_user_return_msr(u32 msr)
631 {
632 BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
633
634 if (kvm_probe_user_return_msr(msr))
635 return -1;
636
637 kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
638 return kvm_nr_uret_msrs++;
639 }
640 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_add_user_return_msr);
641
kvm_find_user_return_msr(u32 msr)642 int kvm_find_user_return_msr(u32 msr)
643 {
644 int i;
645
646 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
647 if (kvm_uret_msrs_list[i] == msr)
648 return i;
649 }
650 return -1;
651 }
652 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_find_user_return_msr);
653
kvm_user_return_msr_cpu_online(void)654 static void kvm_user_return_msr_cpu_online(void)
655 {
656 struct kvm_user_return_msrs *msrs = this_cpu_ptr(&user_return_msrs);
657 u64 value;
658 int i;
659
660 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
661 rdmsrq_safe(kvm_uret_msrs_list[i], &value);
662 msrs->values[i].host = value;
663 msrs->values[i].curr = value;
664 }
665 }
666
kvm_user_return_register_notifier(struct kvm_user_return_msrs * msrs)667 static void kvm_user_return_register_notifier(struct kvm_user_return_msrs *msrs)
668 {
669 if (!msrs->registered) {
670 msrs->urn.on_user_return = kvm_on_user_return;
671 user_return_notifier_register(&msrs->urn);
672 msrs->registered = true;
673 }
674 }
675
kvm_set_user_return_msr(unsigned slot,u64 value,u64 mask)676 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
677 {
678 struct kvm_user_return_msrs *msrs = this_cpu_ptr(&user_return_msrs);
679 int err;
680
681 value = (value & mask) | (msrs->values[slot].host & ~mask);
682 if (value == msrs->values[slot].curr)
683 return 0;
684 err = wrmsrq_safe(kvm_uret_msrs_list[slot], value);
685 if (err)
686 return 1;
687
688 msrs->values[slot].curr = value;
689 kvm_user_return_register_notifier(msrs);
690 return 0;
691 }
692 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_user_return_msr);
693
kvm_get_user_return_msr(unsigned int slot)694 u64 kvm_get_user_return_msr(unsigned int slot)
695 {
696 return this_cpu_ptr(&user_return_msrs)->values[slot].curr;
697 }
698 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_user_return_msr);
699
drop_user_return_notifiers(void)700 static void drop_user_return_notifiers(void)
701 {
702 struct kvm_user_return_msrs *msrs = this_cpu_ptr(&user_return_msrs);
703
704 if (msrs->registered)
705 kvm_on_user_return(&msrs->urn);
706 }
707
708 /*
709 * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
710 *
711 * Hardware virtualization extension instructions may fault if a reboot turns
712 * off virtualization while processes are running. Usually after catching the
713 * fault we just panic; during reboot instead the instruction is ignored.
714 */
kvm_spurious_fault(void)715 noinstr void kvm_spurious_fault(void)
716 {
717 /* Fault while not rebooting. We want the trace. */
718 BUG_ON(!virt_rebooting);
719 }
720 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_spurious_fault);
721
722 #define EXCPT_BENIGN 0
723 #define EXCPT_CONTRIBUTORY 1
724 #define EXCPT_PF 2
725
exception_class(int vector)726 static int exception_class(int vector)
727 {
728 switch (vector) {
729 case PF_VECTOR:
730 return EXCPT_PF;
731 case DE_VECTOR:
732 case TS_VECTOR:
733 case NP_VECTOR:
734 case SS_VECTOR:
735 case GP_VECTOR:
736 return EXCPT_CONTRIBUTORY;
737 default:
738 break;
739 }
740 return EXCPT_BENIGN;
741 }
742
743 #define EXCPT_FAULT 0
744 #define EXCPT_TRAP 1
745 #define EXCPT_ABORT 2
746 #define EXCPT_INTERRUPT 3
747 #define EXCPT_DB 4
748
exception_type(int vector)749 static int exception_type(int vector)
750 {
751 unsigned int mask;
752
753 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
754 return EXCPT_INTERRUPT;
755
756 mask = 1 << vector;
757
758 /*
759 * #DBs can be trap-like or fault-like, the caller must check other CPU
760 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
761 */
762 if (mask & (1 << DB_VECTOR))
763 return EXCPT_DB;
764
765 if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
766 return EXCPT_TRAP;
767
768 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
769 return EXCPT_ABORT;
770
771 /* Reserved exceptions will result in fault */
772 return EXCPT_FAULT;
773 }
774
kvm_deliver_exception_payload(struct kvm_vcpu * vcpu,struct kvm_queued_exception * ex)775 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
776 struct kvm_queued_exception *ex)
777 {
778 if (!ex->has_payload)
779 return;
780
781 switch (ex->vector) {
782 case DB_VECTOR:
783 /*
784 * "Certain debug exceptions may clear bit 0-3. The
785 * remaining contents of the DR6 register are never
786 * cleared by the processor".
787 */
788 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
789 /*
790 * In order to reflect the #DB exception payload in guest
791 * dr6, three components need to be considered: active low
792 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
793 * DR6_BS and DR6_BT)
794 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
795 * In the target guest dr6:
796 * FIXED_1 bits should always be set.
797 * Active low bits should be cleared if 1-setting in payload.
798 * Active high bits should be set if 1-setting in payload.
799 *
800 * Note, the payload is compatible with the pending debug
801 * exceptions/exit qualification under VMX, that active_low bits
802 * are active high in payload.
803 * So they need to be flipped for DR6.
804 */
805 vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
806 vcpu->arch.dr6 |= ex->payload;
807 vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
808
809 /*
810 * The #DB payload is defined as compatible with the 'pending
811 * debug exceptions' field under VMX, not DR6. While bit 12 is
812 * defined in the 'pending debug exceptions' field (enabled
813 * breakpoint), it is reserved and must be zero in DR6.
814 */
815 vcpu->arch.dr6 &= ~BIT(12);
816 break;
817 case PF_VECTOR:
818 vcpu->arch.cr2 = ex->payload;
819 break;
820 }
821
822 ex->has_payload = false;
823 ex->payload = 0;
824 }
825 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_deliver_exception_payload);
826
kvm_queue_exception_vmexit(struct kvm_vcpu * vcpu,unsigned int vector,bool has_error_code,u32 error_code,bool has_payload,unsigned long payload)827 static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
828 bool has_error_code, u32 error_code,
829 bool has_payload, unsigned long payload)
830 {
831 struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
832
833 ex->vector = vector;
834 ex->injected = false;
835 ex->pending = true;
836 ex->has_error_code = has_error_code;
837 ex->error_code = error_code;
838 ex->has_payload = has_payload;
839 ex->payload = payload;
840 }
841
kvm_multiple_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error,u32 error_code,bool has_payload,unsigned long payload)842 static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
843 bool has_error, u32 error_code,
844 bool has_payload, unsigned long payload)
845 {
846 u32 prev_nr;
847 int class1, class2;
848
849 kvm_make_request(KVM_REQ_EVENT, vcpu);
850
851 /*
852 * If the exception is destined for L2, morph it to a VM-Exit if L1
853 * wants to intercept the exception.
854 */
855 if (is_guest_mode(vcpu) &&
856 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
857 kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
858 has_payload, payload);
859 return;
860 }
861
862 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
863 queue:
864 vcpu->arch.exception.pending = true;
865 vcpu->arch.exception.injected = false;
866
867 vcpu->arch.exception.has_error_code = has_error;
868 vcpu->arch.exception.vector = nr;
869 vcpu->arch.exception.error_code = error_code;
870 vcpu->arch.exception.has_payload = has_payload;
871 vcpu->arch.exception.payload = payload;
872 return;
873 }
874
875 /* to check exception */
876 prev_nr = vcpu->arch.exception.vector;
877 if (prev_nr == DF_VECTOR) {
878 /* triple fault -> shutdown */
879 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
880 return;
881 }
882 class1 = exception_class(prev_nr);
883 class2 = exception_class(nr);
884 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
885 (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
886 /*
887 * Synthesize #DF. Clear the previously injected or pending
888 * exception so as not to incorrectly trigger shutdown.
889 */
890 vcpu->arch.exception.injected = false;
891 vcpu->arch.exception.pending = false;
892
893 kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
894 } else {
895 /* replace previous exception with a new one in a hope
896 that instruction re-execution will regenerate lost
897 exception */
898 goto queue;
899 }
900 }
901
kvm_queue_exception(struct kvm_vcpu * vcpu,unsigned nr)902 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
903 {
904 kvm_multiple_exception(vcpu, nr, false, 0, false, 0);
905 }
906 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception);
907
908
kvm_queue_exception_p(struct kvm_vcpu * vcpu,unsigned nr,unsigned long payload)909 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
910 unsigned long payload)
911 {
912 kvm_multiple_exception(vcpu, nr, false, 0, true, payload);
913 }
914 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_p);
915
kvm_queue_exception_e_p(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code,unsigned long payload)916 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
917 u32 error_code, unsigned long payload)
918 {
919 kvm_multiple_exception(vcpu, nr, true, error_code, true, payload);
920 }
921
kvm_requeue_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error_code,u32 error_code)922 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
923 bool has_error_code, u32 error_code)
924 {
925
926 /*
927 * On VM-Entry, an exception can be pending if and only if event
928 * injection was blocked by nested_run_pending. In that case, however,
929 * vcpu_enter_guest() requests an immediate exit, and the guest
930 * shouldn't proceed far enough to need reinjection.
931 */
932 WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
933
934 /*
935 * Do not check for interception when injecting an event for L2, as the
936 * exception was checked for intercept when it was original queued, and
937 * re-checking is incorrect if _L1_ injected the exception, in which
938 * case it's exempt from interception.
939 */
940 kvm_make_request(KVM_REQ_EVENT, vcpu);
941
942 vcpu->arch.exception.injected = true;
943 vcpu->arch.exception.has_error_code = has_error_code;
944 vcpu->arch.exception.vector = nr;
945 vcpu->arch.exception.error_code = error_code;
946 vcpu->arch.exception.has_payload = false;
947 vcpu->arch.exception.payload = 0;
948 }
949 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_requeue_exception);
950
kvm_complete_insn_gp(struct kvm_vcpu * vcpu,int err)951 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
952 {
953 if (err)
954 kvm_inject_gp(vcpu, 0);
955 else
956 return kvm_skip_emulated_instruction(vcpu);
957
958 return 1;
959 }
960 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_complete_insn_gp);
961
complete_emulated_insn_gp(struct kvm_vcpu * vcpu,int err)962 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
963 {
964 if (err) {
965 kvm_inject_gp(vcpu, 0);
966 return 1;
967 }
968
969 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
970 EMULTYPE_COMPLETE_USER_EXIT);
971 }
972
kvm_inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)973 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
974 {
975 ++vcpu->stat.pf_guest;
976
977 /*
978 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
979 * whether or not L1 wants to intercept "regular" #PF.
980 */
981 if (is_guest_mode(vcpu) && fault->async_page_fault)
982 kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
983 true, fault->error_code,
984 true, fault->address);
985 else
986 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
987 fault->address);
988 }
989
kvm_inject_emulated_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)990 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
991 struct x86_exception *fault)
992 {
993 struct kvm_mmu *fault_mmu;
994 WARN_ON_ONCE(fault->vector != PF_VECTOR);
995
996 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
997 vcpu->arch.walk_mmu;
998
999 /*
1000 * Invalidate the TLB entry for the faulting address, if it exists,
1001 * else the access will fault indefinitely (and to emulate hardware).
1002 */
1003 if ((fault->error_code & PFERR_PRESENT_MASK) &&
1004 !(fault->error_code & PFERR_RSVD_MASK))
1005 kvm_mmu_invalidate_addr(vcpu, fault_mmu, fault->address,
1006 KVM_MMU_ROOT_CURRENT);
1007
1008 fault_mmu->inject_page_fault(vcpu, fault);
1009 }
1010 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_emulated_page_fault);
1011
kvm_inject_nmi(struct kvm_vcpu * vcpu)1012 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
1013 {
1014 atomic_inc(&vcpu->arch.nmi_queued);
1015 kvm_make_request(KVM_REQ_NMI, vcpu);
1016 }
1017
kvm_queue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)1018 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
1019 {
1020 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0);
1021 }
1022 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_e);
1023
1024 /*
1025 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
1026 * a #GP and return false.
1027 */
kvm_require_cpl(struct kvm_vcpu * vcpu,int required_cpl)1028 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
1029 {
1030 if (kvm_x86_call(get_cpl)(vcpu) <= required_cpl)
1031 return true;
1032 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
1033 return false;
1034 }
1035
kvm_require_dr(struct kvm_vcpu * vcpu,int dr)1036 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
1037 {
1038 if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
1039 return true;
1040
1041 kvm_queue_exception(vcpu, UD_VECTOR);
1042 return false;
1043 }
1044 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_require_dr);
1045
kvm_pv_async_pf_enabled(struct kvm_vcpu * vcpu)1046 static bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
1047 {
1048 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
1049
1050 return (vcpu->arch.apf.msr_en_val & mask) == mask;
1051 }
1052
pdptr_rsvd_bits(struct kvm_vcpu * vcpu)1053 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
1054 {
1055 return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
1056 }
1057
1058 /*
1059 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
1060 */
load_pdptrs(struct kvm_vcpu * vcpu,unsigned long cr3)1061 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
1062 {
1063 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
1064 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
1065 gpa_t real_gpa;
1066 int i;
1067 int ret;
1068 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
1069
1070 /*
1071 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
1072 * to an L1 GPA.
1073 */
1074 real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
1075 PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
1076 if (real_gpa == INVALID_GPA)
1077 return 0;
1078
1079 /* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
1080 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
1081 cr3 & GENMASK(11, 5), sizeof(pdpte));
1082 if (ret < 0)
1083 return 0;
1084
1085 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
1086 if ((pdpte[i] & PT_PRESENT_MASK) &&
1087 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
1088 return 0;
1089 }
1090 }
1091
1092 /*
1093 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
1094 * Shadow page roots need to be reconstructed instead.
1095 */
1096 if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
1097 kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
1098
1099 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
1100 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
1101 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
1102 vcpu->arch.pdptrs_from_userspace = false;
1103
1104 return 1;
1105 }
1106 EXPORT_SYMBOL_FOR_KVM_INTERNAL(load_pdptrs);
1107
kvm_is_valid_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1108 static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1109 {
1110 #ifdef CONFIG_X86_64
1111 if (cr0 & 0xffffffff00000000UL)
1112 return false;
1113 #endif
1114
1115 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
1116 return false;
1117
1118 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
1119 return false;
1120
1121 return kvm_x86_call(is_valid_cr0)(vcpu, cr0);
1122 }
1123
kvm_post_set_cr0(struct kvm_vcpu * vcpu,unsigned long old_cr0,unsigned long cr0)1124 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
1125 {
1126 /*
1127 * CR0.WP is incorporated into the MMU role, but only for non-nested,
1128 * indirect shadow MMUs. If paging is disabled, no updates are needed
1129 * as there are no permission bits to emulate. If TDP is enabled, the
1130 * MMU's metadata needs to be updated, e.g. so that emulating guest
1131 * translations does the right thing, but there's no need to unload the
1132 * root as CR0.WP doesn't affect SPTEs.
1133 */
1134 if ((cr0 ^ old_cr0) == X86_CR0_WP) {
1135 if (!(cr0 & X86_CR0_PG))
1136 return;
1137
1138 if (tdp_enabled) {
1139 kvm_init_mmu(vcpu);
1140 return;
1141 }
1142 }
1143
1144 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
1145 /*
1146 * Clearing CR0.PG is defined to flush the TLB from the guest's
1147 * perspective.
1148 */
1149 if (!(cr0 & X86_CR0_PG))
1150 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1151 /*
1152 * Check for async #PF completion events when enabling paging,
1153 * as the vCPU may have previously encountered async #PFs (it's
1154 * entirely legal for the guest to toggle paging on/off without
1155 * waiting for the async #PF queue to drain).
1156 */
1157 else if (kvm_pv_async_pf_enabled(vcpu))
1158 kvm_make_request(KVM_REQ_APF_READY, vcpu);
1159 }
1160
1161 if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
1162 kvm_mmu_reset_context(vcpu);
1163 }
1164 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_post_set_cr0);
1165
kvm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1166 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1167 {
1168 unsigned long old_cr0 = kvm_read_cr0(vcpu);
1169
1170 if (!kvm_is_valid_cr0(vcpu, cr0))
1171 return 1;
1172
1173 cr0 |= X86_CR0_ET;
1174
1175 /* Write to CR0 reserved bits are ignored, even on Intel. */
1176 cr0 &= ~CR0_RESERVED_BITS;
1177
1178 #ifdef CONFIG_X86_64
1179 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
1180 (cr0 & X86_CR0_PG)) {
1181 int cs_db, cs_l;
1182
1183 if (!is_pae(vcpu))
1184 return 1;
1185 kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
1186 if (cs_l)
1187 return 1;
1188 }
1189 #endif
1190 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
1191 is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
1192 !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1193 return 1;
1194
1195 if (!(cr0 & X86_CR0_PG) &&
1196 (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
1197 return 1;
1198
1199 if (!(cr0 & X86_CR0_WP) && kvm_is_cr4_bit_set(vcpu, X86_CR4_CET))
1200 return 1;
1201
1202 kvm_x86_call(set_cr0)(vcpu, cr0);
1203
1204 kvm_post_set_cr0(vcpu, old_cr0, cr0);
1205
1206 return 0;
1207 }
1208 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr0);
1209
kvm_lmsw(struct kvm_vcpu * vcpu,unsigned long msw)1210 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
1211 {
1212 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
1213 }
1214 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_lmsw);
1215
kvm_load_xfeatures(struct kvm_vcpu * vcpu,bool load_guest)1216 static void kvm_load_xfeatures(struct kvm_vcpu *vcpu, bool load_guest)
1217 {
1218 if (vcpu->arch.guest_state_protected)
1219 return;
1220
1221 if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE))
1222 return;
1223
1224 if (vcpu->arch.xcr0 != kvm_host.xcr0)
1225 xsetbv(XCR_XFEATURE_ENABLED_MASK,
1226 load_guest ? vcpu->arch.xcr0 : kvm_host.xcr0);
1227
1228 if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1229 vcpu->arch.ia32_xss != kvm_host.xss)
1230 wrmsrq(MSR_IA32_XSS, load_guest ? vcpu->arch.ia32_xss : kvm_host.xss);
1231 }
1232
kvm_load_guest_pkru(struct kvm_vcpu * vcpu)1233 static void kvm_load_guest_pkru(struct kvm_vcpu *vcpu)
1234 {
1235 if (vcpu->arch.guest_state_protected)
1236 return;
1237
1238 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1239 vcpu->arch.pkru != vcpu->arch.host_pkru &&
1240 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1241 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
1242 wrpkru(vcpu->arch.pkru);
1243 }
1244
kvm_load_host_pkru(struct kvm_vcpu * vcpu)1245 static void kvm_load_host_pkru(struct kvm_vcpu *vcpu)
1246 {
1247 if (vcpu->arch.guest_state_protected)
1248 return;
1249
1250 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1251 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1252 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
1253 vcpu->arch.pkru = rdpkru();
1254 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1255 wrpkru(vcpu->arch.host_pkru);
1256 }
1257 }
1258
1259 #ifdef CONFIG_X86_64
kvm_guest_supported_xfd(struct kvm_vcpu * vcpu)1260 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1261 {
1262 return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
1263 }
1264 #endif
1265
__kvm_set_xcr(struct kvm_vcpu * vcpu,u32 index,u64 xcr)1266 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1267 {
1268 u64 xcr0 = xcr;
1269 u64 old_xcr0 = vcpu->arch.xcr0;
1270 u64 valid_bits;
1271
1272 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
1273 if (index != XCR_XFEATURE_ENABLED_MASK)
1274 return 1;
1275 if (!(xcr0 & XFEATURE_MASK_FP))
1276 return 1;
1277 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1278 return 1;
1279
1280 /*
1281 * Do not allow the guest to set bits that we do not support
1282 * saving. However, xcr0 bit 0 is always set, even if the
1283 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1284 */
1285 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
1286 if (xcr0 & ~valid_bits)
1287 return 1;
1288
1289 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1290 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1291 return 1;
1292
1293 if (xcr0 & XFEATURE_MASK_AVX512) {
1294 if (!(xcr0 & XFEATURE_MASK_YMM))
1295 return 1;
1296 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1297 return 1;
1298 }
1299
1300 if ((xcr0 & XFEATURE_MASK_XTILE) &&
1301 ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1302 return 1;
1303
1304 vcpu->arch.xcr0 = xcr0;
1305
1306 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1307 vcpu->arch.cpuid_dynamic_bits_dirty = true;
1308 return 0;
1309 }
1310 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_set_xcr);
1311
kvm_emulate_xsetbv(struct kvm_vcpu * vcpu)1312 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1313 {
1314 /* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
1315 if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
1316 __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1317 kvm_inject_gp(vcpu, 0);
1318 return 1;
1319 }
1320
1321 return kvm_skip_emulated_instruction(vcpu);
1322 }
1323 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_xsetbv);
1324
kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1325 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1326 {
1327 return __kvm_is_valid_cr4(vcpu, cr4) &&
1328 kvm_x86_call(is_valid_cr4)(vcpu, cr4);
1329 }
1330
kvm_post_set_cr4(struct kvm_vcpu * vcpu,unsigned long old_cr4,unsigned long cr4)1331 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1332 {
1333 if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1334 kvm_mmu_reset_context(vcpu);
1335
1336 /*
1337 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1338 * according to the SDM; however, stale prev_roots could be reused
1339 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1340 * free them all. This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1341 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1342 * so fall through.
1343 */
1344 if (!tdp_enabled &&
1345 (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1346 kvm_mmu_unload(vcpu);
1347
1348 /*
1349 * The TLB has to be flushed for all PCIDs if any of the following
1350 * (architecturally required) changes happen:
1351 * - CR4.PCIDE is changed from 1 to 0
1352 * - CR4.PGE is toggled
1353 *
1354 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1355 */
1356 if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1357 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1358 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1359
1360 /*
1361 * The TLB has to be flushed for the current PCID if any of the
1362 * following (architecturally required) changes happen:
1363 * - CR4.SMEP is changed from 0 to 1
1364 * - CR4.PAE is toggled
1365 */
1366 else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1367 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1368 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1369
1370 }
1371 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_post_set_cr4);
1372
kvm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1373 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1374 {
1375 unsigned long old_cr4 = kvm_read_cr4(vcpu);
1376
1377 if (!kvm_is_valid_cr4(vcpu, cr4))
1378 return 1;
1379
1380 if (is_long_mode(vcpu)) {
1381 if (!(cr4 & X86_CR4_PAE))
1382 return 1;
1383 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1384 return 1;
1385 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1386 && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1387 && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1388 return 1;
1389
1390 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1391 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1392 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1393 return 1;
1394 }
1395
1396 if ((cr4 & X86_CR4_CET) && !kvm_is_cr0_bit_set(vcpu, X86_CR0_WP))
1397 return 1;
1398
1399 kvm_x86_call(set_cr4)(vcpu, cr4);
1400
1401 kvm_post_set_cr4(vcpu, old_cr4, cr4);
1402
1403 return 0;
1404 }
1405 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr4);
1406
kvm_invalidate_pcid(struct kvm_vcpu * vcpu,unsigned long pcid)1407 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1408 {
1409 struct kvm_mmu *mmu = vcpu->arch.mmu;
1410 unsigned long roots_to_free = 0;
1411 int i;
1412
1413 /*
1414 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1415 * this is reachable when running EPT=1 and unrestricted_guest=0, and
1416 * also via the emulator. KVM's TDP page tables are not in the scope of
1417 * the invalidation, but the guest's TLB entries need to be flushed as
1418 * the CPU may have cached entries in its TLB for the target PCID.
1419 */
1420 if (unlikely(tdp_enabled)) {
1421 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1422 return;
1423 }
1424
1425 /*
1426 * If neither the current CR3 nor any of the prev_roots use the given
1427 * PCID, then nothing needs to be done here because a resync will
1428 * happen anyway before switching to any other CR3.
1429 */
1430 if (kvm_get_active_pcid(vcpu) == pcid) {
1431 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1432 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1433 }
1434
1435 /*
1436 * If PCID is disabled, there is no need to free prev_roots even if the
1437 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1438 * with PCIDE=0.
1439 */
1440 if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
1441 return;
1442
1443 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1444 if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1445 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1446
1447 kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1448 }
1449
kvm_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)1450 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1451 {
1452 bool skip_tlb_flush = false;
1453 unsigned long pcid = 0;
1454 #ifdef CONFIG_X86_64
1455 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)) {
1456 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1457 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1458 pcid = cr3 & X86_CR3_PCID_MASK;
1459 }
1460 #endif
1461
1462 /* PDPTRs are always reloaded for PAE paging. */
1463 if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1464 goto handle_tlb_flush;
1465
1466 /*
1467 * Do not condition the GPA check on long mode, this helper is used to
1468 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1469 * the current vCPU mode is accurate.
1470 */
1471 if (!kvm_vcpu_is_legal_cr3(vcpu, cr3))
1472 return 1;
1473
1474 if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1475 return 1;
1476
1477 if (cr3 != kvm_read_cr3(vcpu))
1478 kvm_mmu_new_pgd(vcpu, cr3);
1479
1480 vcpu->arch.cr3 = cr3;
1481 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1482 /* Do not call post_set_cr3, we do not get here for confidential guests. */
1483
1484 handle_tlb_flush:
1485 /*
1486 * A load of CR3 that flushes the TLB flushes only the current PCID,
1487 * even if PCID is disabled, in which case PCID=0 is flushed. It's a
1488 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1489 * and it's impossible to use a non-zero PCID when PCID is disabled,
1490 * i.e. only PCID=0 can be relevant.
1491 */
1492 if (!skip_tlb_flush)
1493 kvm_invalidate_pcid(vcpu, pcid);
1494
1495 return 0;
1496 }
1497 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr3);
1498
kvm_set_cr8(struct kvm_vcpu * vcpu,unsigned long cr8)1499 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1500 {
1501 if (cr8 & CR8_RESERVED_BITS)
1502 return 1;
1503 if (lapic_in_kernel(vcpu))
1504 kvm_lapic_set_tpr(vcpu, cr8);
1505 else
1506 vcpu->arch.cr8 = cr8;
1507 return 0;
1508 }
1509 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr8);
1510
kvm_get_cr8(struct kvm_vcpu * vcpu)1511 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1512 {
1513 if (lapic_in_kernel(vcpu))
1514 return kvm_lapic_get_cr8(vcpu);
1515 else
1516 return vcpu->arch.cr8;
1517 }
1518 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_cr8);
1519
kvm_update_dr0123(struct kvm_vcpu * vcpu)1520 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1521 {
1522 int i;
1523
1524 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1525 for (i = 0; i < KVM_NR_DB_REGS; i++)
1526 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1527 }
1528 }
1529
kvm_update_dr7(struct kvm_vcpu * vcpu)1530 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1531 {
1532 unsigned long dr7;
1533
1534 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1535 dr7 = vcpu->arch.guest_debug_dr7;
1536 else
1537 dr7 = vcpu->arch.dr7;
1538 kvm_x86_call(set_dr7)(vcpu, dr7);
1539 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1540 if (dr7 & DR7_BP_EN_MASK)
1541 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1542 }
1543 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_update_dr7);
1544
kvm_dr6_fixed(struct kvm_vcpu * vcpu)1545 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1546 {
1547 u64 fixed = DR6_FIXED_1;
1548
1549 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_RTM))
1550 fixed |= DR6_RTM;
1551
1552 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1553 fixed |= DR6_BUS_LOCK;
1554 return fixed;
1555 }
1556
kvm_set_dr(struct kvm_vcpu * vcpu,int dr,unsigned long val)1557 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1558 {
1559 size_t size = ARRAY_SIZE(vcpu->arch.db);
1560
1561 switch (dr) {
1562 case 0 ... 3:
1563 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1564 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1565 vcpu->arch.eff_db[dr] = val;
1566 break;
1567 case 4:
1568 case 6:
1569 if (!kvm_dr6_valid(val))
1570 return 1; /* #GP */
1571 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1572 break;
1573 case 5:
1574 default: /* 7 */
1575 if (!kvm_dr7_valid(val))
1576 return 1; /* #GP */
1577 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1578 kvm_update_dr7(vcpu);
1579 break;
1580 }
1581
1582 return 0;
1583 }
1584 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_dr);
1585
kvm_get_dr(struct kvm_vcpu * vcpu,int dr)1586 unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr)
1587 {
1588 size_t size = ARRAY_SIZE(vcpu->arch.db);
1589
1590 switch (dr) {
1591 case 0 ... 3:
1592 return vcpu->arch.db[array_index_nospec(dr, size)];
1593 case 4:
1594 case 6:
1595 return vcpu->arch.dr6;
1596 case 5:
1597 default: /* 7 */
1598 return vcpu->arch.dr7;
1599 }
1600 }
1601 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_dr);
1602
kvm_emulate_rdpmc(struct kvm_vcpu * vcpu)1603 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1604 {
1605 u32 pmc = kvm_rcx_read(vcpu);
1606 u64 data;
1607
1608 if (kvm_pmu_rdpmc(vcpu, pmc, &data)) {
1609 kvm_inject_gp(vcpu, 0);
1610 return 1;
1611 }
1612
1613 kvm_rax_write(vcpu, (u32)data);
1614 kvm_rdx_write(vcpu, data >> 32);
1615 return kvm_skip_emulated_instruction(vcpu);
1616 }
1617 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdpmc);
1618
1619 /*
1620 * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1621 * does not yet virtualize. These include:
1622 * 10 - MISC_PACKAGE_CTRLS
1623 * 11 - ENERGY_FILTERING_CTL
1624 * 12 - DOITM
1625 * 18 - FB_CLEAR_CTRL
1626 * 21 - XAPIC_DISABLE_STATUS
1627 * 23 - OVERCLOCKING_STATUS
1628 */
1629
1630 #define KVM_SUPPORTED_ARCH_CAP \
1631 (ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1632 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1633 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1634 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1635 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
1636 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO | ARCH_CAP_ITS_NO)
1637
kvm_get_arch_capabilities(void)1638 static u64 kvm_get_arch_capabilities(void)
1639 {
1640 u64 data = kvm_host.arch_capabilities & KVM_SUPPORTED_ARCH_CAP;
1641
1642 /*
1643 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1644 * the nested hypervisor runs with NX huge pages. If it is not,
1645 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1646 * L1 guests, so it need not worry about its own (L2) guests.
1647 */
1648 data |= ARCH_CAP_PSCHANGE_MC_NO;
1649
1650 /*
1651 * If we're doing cache flushes (either "always" or "cond")
1652 * we will do one whenever the guest does a vmlaunch/vmresume.
1653 * If an outer hypervisor is doing the cache flush for us
1654 * (ARCH_CAP_SKIP_VMENTRY_L1DFLUSH), we can safely pass that
1655 * capability to the guest too, and if EPT is disabled we're not
1656 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1657 * require a nested hypervisor to do a flush of its own.
1658 */
1659 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1660 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1661
1662 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1663 data |= ARCH_CAP_RDCL_NO;
1664 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1665 data |= ARCH_CAP_SSB_NO;
1666 if (!boot_cpu_has_bug(X86_BUG_MDS))
1667 data |= ARCH_CAP_MDS_NO;
1668 if (!boot_cpu_has_bug(X86_BUG_RFDS))
1669 data |= ARCH_CAP_RFDS_NO;
1670 if (!boot_cpu_has_bug(X86_BUG_ITS))
1671 data |= ARCH_CAP_ITS_NO;
1672
1673 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1674 /*
1675 * If RTM=0 because the kernel has disabled TSX, the host might
1676 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1677 * and therefore knows that there cannot be TAA) but keep
1678 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1679 * and we want to allow migrating those guests to tsx=off hosts.
1680 */
1681 data &= ~ARCH_CAP_TAA_NO;
1682 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1683 data |= ARCH_CAP_TAA_NO;
1684 } else {
1685 /*
1686 * Nothing to do here; we emulate TSX_CTRL if present on the
1687 * host so the guest can choose between disabling TSX or
1688 * using VERW to clear CPU buffers.
1689 */
1690 }
1691
1692 if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1693 data |= ARCH_CAP_GDS_NO;
1694
1695 return data;
1696 }
1697
kvm_get_feature_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1698 static int kvm_get_feature_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1699 bool host_initiated)
1700 {
1701 WARN_ON_ONCE(!host_initiated);
1702
1703 switch (index) {
1704 case MSR_IA32_ARCH_CAPABILITIES:
1705 *data = kvm_get_arch_capabilities();
1706 break;
1707 case MSR_IA32_PERF_CAPABILITIES:
1708 *data = kvm_caps.supported_perf_cap;
1709 break;
1710 case MSR_PLATFORM_INFO:
1711 *data = MSR_PLATFORM_INFO_CPUID_FAULT;
1712 break;
1713 case MSR_IA32_UCODE_REV:
1714 rdmsrq_safe(index, data);
1715 break;
1716 default:
1717 return kvm_x86_call(get_feature_msr)(index, data);
1718 }
1719 return 0;
1720 }
1721
do_get_feature_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)1722 static int do_get_feature_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1723 {
1724 return kvm_do_msr_access(vcpu, index, data, true, MSR_TYPE_R,
1725 kvm_get_feature_msr);
1726 }
1727
__kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1728 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1729 {
1730 if (efer & EFER_AUTOIBRS && !guest_cpu_cap_has(vcpu, X86_FEATURE_AUTOIBRS))
1731 return false;
1732
1733 if (efer & EFER_FFXSR && !guest_cpu_cap_has(vcpu, X86_FEATURE_FXSR_OPT))
1734 return false;
1735
1736 if (efer & EFER_SVME && !guest_cpu_cap_has(vcpu, X86_FEATURE_SVM))
1737 return false;
1738
1739 if (efer & (EFER_LME | EFER_LMA) &&
1740 !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1741 return false;
1742
1743 if (efer & EFER_NX && !guest_cpu_cap_has(vcpu, X86_FEATURE_NX))
1744 return false;
1745
1746 return true;
1747
1748 }
kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1749 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1750 {
1751 if (efer & efer_reserved_bits)
1752 return false;
1753
1754 return __kvm_valid_efer(vcpu, efer);
1755 }
1756 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_valid_efer);
1757
set_efer(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1758 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1759 {
1760 u64 old_efer = vcpu->arch.efer;
1761 u64 efer = msr_info->data;
1762 int r;
1763
1764 if (efer & efer_reserved_bits)
1765 return 1;
1766
1767 if (!msr_info->host_initiated) {
1768 if (!__kvm_valid_efer(vcpu, efer))
1769 return 1;
1770
1771 if (is_paging(vcpu) &&
1772 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1773 return 1;
1774 }
1775
1776 efer &= ~EFER_LMA;
1777 efer |= vcpu->arch.efer & EFER_LMA;
1778
1779 r = kvm_x86_call(set_efer)(vcpu, efer);
1780 if (r) {
1781 WARN_ON(r > 0);
1782 return r;
1783 }
1784
1785 if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1786 kvm_mmu_reset_context(vcpu);
1787
1788 if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1789 (efer & EFER_SVME))
1790 kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1791
1792 return 0;
1793 }
1794
kvm_enable_efer_bits(u64 mask)1795 void kvm_enable_efer_bits(u64 mask)
1796 {
1797 efer_reserved_bits &= ~mask;
1798 }
1799 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_enable_efer_bits);
1800
kvm_msr_allowed(struct kvm_vcpu * vcpu,u32 index,u32 type)1801 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1802 {
1803 struct kvm_x86_msr_filter *msr_filter;
1804 struct msr_bitmap_range *ranges;
1805 struct kvm *kvm = vcpu->kvm;
1806 bool allowed;
1807 int idx;
1808 u32 i;
1809
1810 /* x2APIC MSRs do not support filtering. */
1811 if (index >= 0x800 && index <= 0x8ff)
1812 return true;
1813
1814 idx = srcu_read_lock(&kvm->srcu);
1815
1816 msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1817 if (!msr_filter) {
1818 allowed = true;
1819 goto out;
1820 }
1821
1822 allowed = msr_filter->default_allow;
1823 ranges = msr_filter->ranges;
1824
1825 for (i = 0; i < msr_filter->count; i++) {
1826 u32 start = ranges[i].base;
1827 u32 end = start + ranges[i].nmsrs;
1828 u32 flags = ranges[i].flags;
1829 unsigned long *bitmap = ranges[i].bitmap;
1830
1831 if ((index >= start) && (index < end) && (flags & type)) {
1832 allowed = test_bit(index - start, bitmap);
1833 break;
1834 }
1835 }
1836
1837 out:
1838 srcu_read_unlock(&kvm->srcu, idx);
1839
1840 return allowed;
1841 }
1842 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_msr_allowed);
1843
1844 /*
1845 * Write @data into the MSR specified by @index. Select MSR specific fault
1846 * checks are bypassed if @host_initiated is %true.
1847 * Returns 0 on success, non-0 otherwise.
1848 * Assumes vcpu_load() was already called.
1849 */
__kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1850 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1851 bool host_initiated)
1852 {
1853 struct msr_data msr;
1854
1855 switch (index) {
1856 case MSR_FS_BASE:
1857 case MSR_GS_BASE:
1858 case MSR_KERNEL_GS_BASE:
1859 case MSR_CSTAR:
1860 case MSR_LSTAR:
1861 if (is_noncanonical_msr_address(data, vcpu))
1862 return 1;
1863 break;
1864 case MSR_IA32_SYSENTER_EIP:
1865 case MSR_IA32_SYSENTER_ESP:
1866 /*
1867 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1868 * non-canonical address is written on Intel but not on
1869 * AMD (which ignores the top 32-bits, because it does
1870 * not implement 64-bit SYSENTER).
1871 *
1872 * 64-bit code should hence be able to write a non-canonical
1873 * value on AMD. Making the address canonical ensures that
1874 * vmentry does not fail on Intel after writing a non-canonical
1875 * value, and that something deterministic happens if the guest
1876 * invokes 64-bit SYSENTER.
1877 */
1878 data = __canonical_address(data, max_host_virt_addr_bits());
1879 break;
1880 case MSR_TSC_AUX:
1881 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1882 return 1;
1883
1884 if (!host_initiated &&
1885 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1886 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1887 return 1;
1888
1889 /*
1890 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1891 * incomplete and conflicting architectural behavior. Current
1892 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1893 * reserved and always read as zeros. Enforce Intel's reserved
1894 * bits check if the guest CPU is Intel compatible, otherwise
1895 * clear the bits. This ensures cross-vendor migration will
1896 * provide consistent behavior for the guest.
1897 */
1898 if (guest_cpuid_is_intel_compatible(vcpu) && (data >> 32) != 0)
1899 return 1;
1900
1901 data = (u32)data;
1902 break;
1903 case MSR_IA32_U_CET:
1904 case MSR_IA32_S_CET:
1905 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
1906 !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT))
1907 return KVM_MSR_RET_UNSUPPORTED;
1908 if (!kvm_is_valid_u_s_cet(vcpu, data))
1909 return 1;
1910 break;
1911 case MSR_KVM_INTERNAL_GUEST_SSP:
1912 if (!host_initiated)
1913 return 1;
1914 fallthrough;
1915 /*
1916 * Note that the MSR emulation here is flawed when a vCPU
1917 * doesn't support the Intel 64 architecture. The expected
1918 * architectural behavior in this case is that the upper 32
1919 * bits do not exist and should always read '0'. However,
1920 * because the actual hardware on which the virtual CPU is
1921 * running does support Intel 64, XRSTORS/XSAVES in the
1922 * guest could observe behavior that violates the
1923 * architecture. Intercepting XRSTORS/XSAVES for this
1924 * special case isn't deemed worthwhile.
1925 */
1926 case MSR_IA32_PL0_SSP ... MSR_IA32_INT_SSP_TAB:
1927 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
1928 return KVM_MSR_RET_UNSUPPORTED;
1929 /*
1930 * MSR_IA32_INT_SSP_TAB is not present on processors that do
1931 * not support Intel 64 architecture.
1932 */
1933 if (index == MSR_IA32_INT_SSP_TAB && !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1934 return KVM_MSR_RET_UNSUPPORTED;
1935 if (is_noncanonical_msr_address(data, vcpu))
1936 return 1;
1937 /* All SSP MSRs except MSR_IA32_INT_SSP_TAB must be 4-byte aligned */
1938 if (index != MSR_IA32_INT_SSP_TAB && !IS_ALIGNED(data, 4))
1939 return 1;
1940 break;
1941 }
1942
1943 msr.data = data;
1944 msr.index = index;
1945 msr.host_initiated = host_initiated;
1946
1947 return kvm_x86_call(set_msr)(vcpu, &msr);
1948 }
1949
_kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1950 static int _kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1951 bool host_initiated)
1952 {
1953 return __kvm_set_msr(vcpu, index, *data, host_initiated);
1954 }
1955
kvm_set_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1956 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1957 u32 index, u64 data, bool host_initiated)
1958 {
1959 return kvm_do_msr_access(vcpu, index, &data, host_initiated, MSR_TYPE_W,
1960 _kvm_set_msr);
1961 }
1962
1963 /*
1964 * Read the MSR specified by @index into @data. Select MSR specific fault
1965 * checks are bypassed if @host_initiated is %true.
1966 * Returns 0 on success, non-0 otherwise.
1967 * Assumes vcpu_load() was already called.
1968 */
__kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1969 static int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1970 bool host_initiated)
1971 {
1972 struct msr_data msr;
1973 int ret;
1974
1975 switch (index) {
1976 case MSR_TSC_AUX:
1977 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1978 return 1;
1979
1980 if (!host_initiated &&
1981 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1982 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1983 return 1;
1984 break;
1985 case MSR_IA32_U_CET:
1986 case MSR_IA32_S_CET:
1987 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
1988 !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT))
1989 return KVM_MSR_RET_UNSUPPORTED;
1990 break;
1991 case MSR_KVM_INTERNAL_GUEST_SSP:
1992 if (!host_initiated)
1993 return 1;
1994 fallthrough;
1995 case MSR_IA32_PL0_SSP ... MSR_IA32_INT_SSP_TAB:
1996 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
1997 return KVM_MSR_RET_UNSUPPORTED;
1998 break;
1999 }
2000
2001 msr.index = index;
2002 msr.host_initiated = host_initiated;
2003
2004 ret = kvm_x86_call(get_msr)(vcpu, &msr);
2005 if (!ret)
2006 *data = msr.data;
2007 return ret;
2008 }
2009
kvm_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2010 int kvm_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2011 {
2012 return __kvm_set_msr(vcpu, index, data, true);
2013 }
2014
kvm_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2015 int kvm_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2016 {
2017 return __kvm_get_msr(vcpu, index, data, true);
2018 }
2019
kvm_get_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)2020 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
2021 u32 index, u64 *data, bool host_initiated)
2022 {
2023 return kvm_do_msr_access(vcpu, index, data, host_initiated, MSR_TYPE_R,
2024 __kvm_get_msr);
2025 }
2026
__kvm_emulate_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2027 int __kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2028 {
2029 return kvm_get_msr_ignored_check(vcpu, index, data, false);
2030 }
2031 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_emulate_msr_read);
2032
__kvm_emulate_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2033 int __kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2034 {
2035 return kvm_set_msr_ignored_check(vcpu, index, data, false);
2036 }
2037 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_emulate_msr_write);
2038
kvm_emulate_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2039 int kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2040 {
2041 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
2042 return KVM_MSR_RET_FILTERED;
2043
2044 return __kvm_emulate_msr_read(vcpu, index, data);
2045 }
2046 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_read);
2047
kvm_emulate_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2048 int kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2049 {
2050 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
2051 return KVM_MSR_RET_FILTERED;
2052
2053 return __kvm_emulate_msr_write(vcpu, index, data);
2054 }
2055 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_write);
2056
2057
complete_userspace_rdmsr(struct kvm_vcpu * vcpu)2058 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
2059 {
2060 if (!vcpu->run->msr.error) {
2061 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
2062 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
2063 }
2064 }
2065
complete_emulated_msr_access(struct kvm_vcpu * vcpu)2066 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
2067 {
2068 return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
2069 }
2070
complete_emulated_rdmsr(struct kvm_vcpu * vcpu)2071 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
2072 {
2073 complete_userspace_rdmsr(vcpu);
2074 return complete_emulated_msr_access(vcpu);
2075 }
2076
complete_fast_msr_access(struct kvm_vcpu * vcpu)2077 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
2078 {
2079 return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
2080 }
2081
complete_fast_rdmsr(struct kvm_vcpu * vcpu)2082 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
2083 {
2084 complete_userspace_rdmsr(vcpu);
2085 return complete_fast_msr_access(vcpu);
2086 }
2087
complete_fast_rdmsr_imm(struct kvm_vcpu * vcpu)2088 static int complete_fast_rdmsr_imm(struct kvm_vcpu *vcpu)
2089 {
2090 if (!vcpu->run->msr.error)
2091 kvm_register_write(vcpu, vcpu->arch.cui_rdmsr_imm_reg,
2092 vcpu->run->msr.data);
2093
2094 return complete_fast_msr_access(vcpu);
2095 }
2096
kvm_msr_reason(int r)2097 static u64 kvm_msr_reason(int r)
2098 {
2099 switch (r) {
2100 case KVM_MSR_RET_UNSUPPORTED:
2101 return KVM_MSR_EXIT_REASON_UNKNOWN;
2102 case KVM_MSR_RET_FILTERED:
2103 return KVM_MSR_EXIT_REASON_FILTER;
2104 default:
2105 return KVM_MSR_EXIT_REASON_INVAL;
2106 }
2107 }
2108
kvm_msr_user_space(struct kvm_vcpu * vcpu,u32 index,u32 exit_reason,u64 data,int (* completion)(struct kvm_vcpu * vcpu),int r)2109 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
2110 u32 exit_reason, u64 data,
2111 int (*completion)(struct kvm_vcpu *vcpu),
2112 int r)
2113 {
2114 u64 msr_reason = kvm_msr_reason(r);
2115
2116 /* Check if the user wanted to know about this MSR fault */
2117 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2118 return 0;
2119
2120 vcpu->run->exit_reason = exit_reason;
2121 vcpu->run->msr.error = 0;
2122 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2123 vcpu->run->msr.reason = msr_reason;
2124 vcpu->run->msr.index = index;
2125 vcpu->run->msr.data = data;
2126 vcpu->arch.complete_userspace_io = completion;
2127
2128 return 1;
2129 }
2130
__kvm_emulate_rdmsr(struct kvm_vcpu * vcpu,u32 msr,int reg,int (* complete_rdmsr)(struct kvm_vcpu *))2131 static int __kvm_emulate_rdmsr(struct kvm_vcpu *vcpu, u32 msr, int reg,
2132 int (*complete_rdmsr)(struct kvm_vcpu *))
2133 {
2134 u64 data;
2135 int r;
2136
2137 r = kvm_emulate_msr_read(vcpu, msr, &data);
2138
2139 if (!r) {
2140 trace_kvm_msr_read(msr, data);
2141
2142 if (reg < 0) {
2143 kvm_rax_write(vcpu, data & -1u);
2144 kvm_rdx_write(vcpu, (data >> 32) & -1u);
2145 } else {
2146 kvm_register_write(vcpu, reg, data);
2147 }
2148 } else {
2149 /* MSR read failed? See if we should ask user space */
2150 if (kvm_msr_user_space(vcpu, msr, KVM_EXIT_X86_RDMSR, 0,
2151 complete_rdmsr, r))
2152 return 0;
2153 trace_kvm_msr_read_ex(msr);
2154 }
2155
2156 return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2157 }
2158
kvm_emulate_rdmsr(struct kvm_vcpu * vcpu)2159 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2160 {
2161 return __kvm_emulate_rdmsr(vcpu, kvm_rcx_read(vcpu), -1,
2162 complete_fast_rdmsr);
2163 }
2164 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdmsr);
2165
kvm_emulate_rdmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2166 int kvm_emulate_rdmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2167 {
2168 vcpu->arch.cui_rdmsr_imm_reg = reg;
2169
2170 return __kvm_emulate_rdmsr(vcpu, msr, reg, complete_fast_rdmsr_imm);
2171 }
2172 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdmsr_imm);
2173
__kvm_emulate_wrmsr(struct kvm_vcpu * vcpu,u32 msr,u64 data)2174 static int __kvm_emulate_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2175 {
2176 int r;
2177
2178 r = kvm_emulate_msr_write(vcpu, msr, data);
2179 if (!r) {
2180 trace_kvm_msr_write(msr, data);
2181 } else {
2182 /* MSR write failed? See if we should ask user space */
2183 if (kvm_msr_user_space(vcpu, msr, KVM_EXIT_X86_WRMSR, data,
2184 complete_fast_msr_access, r))
2185 return 0;
2186 /* Signal all other negative errors to userspace */
2187 if (r < 0)
2188 return r;
2189 trace_kvm_msr_write_ex(msr, data);
2190 }
2191
2192 return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2193 }
2194
kvm_emulate_wrmsr(struct kvm_vcpu * vcpu)2195 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2196 {
2197 return __kvm_emulate_wrmsr(vcpu, kvm_rcx_read(vcpu),
2198 kvm_read_edx_eax(vcpu));
2199 }
2200 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wrmsr);
2201
kvm_emulate_wrmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2202 int kvm_emulate_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2203 {
2204 return __kvm_emulate_wrmsr(vcpu, msr, kvm_register_read(vcpu, reg));
2205 }
2206 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wrmsr_imm);
2207
kvm_emulate_as_nop(struct kvm_vcpu * vcpu)2208 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2209 {
2210 return kvm_skip_emulated_instruction(vcpu);
2211 }
2212
kvm_emulate_invd(struct kvm_vcpu * vcpu)2213 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2214 {
2215 /* Treat an INVD instruction as a NOP and just skip it. */
2216 return kvm_emulate_as_nop(vcpu);
2217 }
2218 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_invd);
2219
handle_fastpath_invd(struct kvm_vcpu * vcpu)2220 fastpath_t handle_fastpath_invd(struct kvm_vcpu *vcpu)
2221 {
2222 if (!kvm_pmu_is_fastpath_emulation_allowed(vcpu))
2223 return EXIT_FASTPATH_NONE;
2224
2225 if (!kvm_emulate_invd(vcpu))
2226 return EXIT_FASTPATH_EXIT_USERSPACE;
2227
2228 return EXIT_FASTPATH_REENTER_GUEST;
2229 }
2230 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_invd);
2231
kvm_handle_invalid_op(struct kvm_vcpu * vcpu)2232 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2233 {
2234 kvm_queue_exception(vcpu, UD_VECTOR);
2235 return 1;
2236 }
2237 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invalid_op);
2238
2239
kvm_emulate_monitor_mwait(struct kvm_vcpu * vcpu,const char * insn)2240 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2241 {
2242 bool enabled;
2243
2244 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS))
2245 goto emulate_as_nop;
2246
2247 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
2248 enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_MWAIT);
2249 else
2250 enabled = vcpu->arch.ia32_misc_enable_msr & MSR_IA32_MISC_ENABLE_MWAIT;
2251
2252 if (!enabled)
2253 return kvm_handle_invalid_op(vcpu);
2254
2255 emulate_as_nop:
2256 pr_warn_once("%s instruction emulated as NOP!\n", insn);
2257 return kvm_emulate_as_nop(vcpu);
2258 }
kvm_emulate_mwait(struct kvm_vcpu * vcpu)2259 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2260 {
2261 return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2262 }
2263 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_mwait);
2264
kvm_emulate_monitor(struct kvm_vcpu * vcpu)2265 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2266 {
2267 return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2268 }
2269 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_monitor);
2270
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu)2271 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2272 {
2273 xfer_to_guest_mode_prepare();
2274
2275 return READ_ONCE(vcpu->mode) == EXITING_GUEST_MODE ||
2276 kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending();
2277 }
2278
__handle_fastpath_wrmsr(struct kvm_vcpu * vcpu,u32 msr,u64 data)2279 static fastpath_t __handle_fastpath_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2280 {
2281 if (!kvm_pmu_is_fastpath_emulation_allowed(vcpu))
2282 return EXIT_FASTPATH_NONE;
2283
2284 switch (msr) {
2285 case APIC_BASE_MSR + (APIC_ICR >> 4):
2286 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic) ||
2287 kvm_x2apic_icr_write_fast(vcpu->arch.apic, data))
2288 return EXIT_FASTPATH_NONE;
2289 break;
2290 case MSR_IA32_TSC_DEADLINE:
2291 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2292 break;
2293 default:
2294 return EXIT_FASTPATH_NONE;
2295 }
2296
2297 trace_kvm_msr_write(msr, data);
2298
2299 if (!kvm_skip_emulated_instruction(vcpu))
2300 return EXIT_FASTPATH_EXIT_USERSPACE;
2301
2302 return EXIT_FASTPATH_REENTER_GUEST;
2303 }
2304
handle_fastpath_wrmsr(struct kvm_vcpu * vcpu)2305 fastpath_t handle_fastpath_wrmsr(struct kvm_vcpu *vcpu)
2306 {
2307 return __handle_fastpath_wrmsr(vcpu, kvm_rcx_read(vcpu),
2308 kvm_read_edx_eax(vcpu));
2309 }
2310 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr);
2311
handle_fastpath_wrmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2312 fastpath_t handle_fastpath_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2313 {
2314 return __handle_fastpath_wrmsr(vcpu, msr, kvm_register_read(vcpu, reg));
2315 }
2316 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr_imm);
2317
2318 /*
2319 * Adapt set_msr() to msr_io()'s calling convention
2320 */
do_get_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2321 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2322 {
2323 return kvm_get_msr_ignored_check(vcpu, index, data, true);
2324 }
2325
do_set_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2326 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2327 {
2328 u64 val;
2329
2330 /*
2331 * Reject writes to immutable feature MSRs if the vCPU model is frozen,
2332 * as KVM doesn't support modifying the guest vCPU model on the fly,
2333 * e.g. changing the VMX capabilities MSRs while L2 is active is
2334 * nonsensical. Allow writes of the same value, e.g. so that userspace
2335 * can blindly stuff all MSRs when emulating RESET.
2336 */
2337 if (!kvm_can_set_cpuid_and_feature_msrs(vcpu) &&
2338 kvm_is_immutable_feature_msr(index) &&
2339 (do_get_msr(vcpu, index, &val) || *data != val))
2340 return -EINVAL;
2341
2342 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2343 }
2344
2345 #ifdef CONFIG_X86_64
2346 struct pvclock_clock {
2347 int vclock_mode;
2348 u64 cycle_last;
2349 u64 mask;
2350 u32 mult;
2351 u32 shift;
2352 u64 base_cycles;
2353 u64 offset;
2354 };
2355
2356 struct pvclock_gtod_data {
2357 seqcount_t seq;
2358
2359 struct pvclock_clock clock; /* extract of a clocksource struct */
2360 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2361
2362 ktime_t offs_boot;
2363 u64 wall_time_sec;
2364 };
2365
2366 static struct pvclock_gtod_data pvclock_gtod_data;
2367
update_pvclock_gtod(struct timekeeper * tk)2368 static void update_pvclock_gtod(struct timekeeper *tk)
2369 {
2370 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2371
2372 write_seqcount_begin(&vdata->seq);
2373
2374 /* copy pvclock gtod data */
2375 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
2376 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
2377 vdata->clock.mask = tk->tkr_mono.mask;
2378 vdata->clock.mult = tk->tkr_mono.mult;
2379 vdata->clock.shift = tk->tkr_mono.shift;
2380 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
2381 vdata->clock.offset = tk->tkr_mono.base;
2382
2383 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
2384 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
2385 vdata->raw_clock.mask = tk->tkr_raw.mask;
2386 vdata->raw_clock.mult = tk->tkr_raw.mult;
2387 vdata->raw_clock.shift = tk->tkr_raw.shift;
2388 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
2389 vdata->raw_clock.offset = tk->tkr_raw.base;
2390
2391 vdata->wall_time_sec = tk->xtime_sec;
2392
2393 vdata->offs_boot = tk->offs_boot;
2394
2395 write_seqcount_end(&vdata->seq);
2396 }
2397
get_kvmclock_base_ns(void)2398 static s64 get_kvmclock_base_ns(void)
2399 {
2400 /* Count up from boot time, but with the frequency of the raw clock. */
2401 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2402 }
2403 #else
get_kvmclock_base_ns(void)2404 static s64 get_kvmclock_base_ns(void)
2405 {
2406 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
2407 return ktime_get_boottime_ns();
2408 }
2409 #endif
2410
kvm_write_wall_clock(struct kvm * kvm,gpa_t wall_clock,int sec_hi_ofs)2411 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2412 {
2413 int version;
2414 int r;
2415 struct pvclock_wall_clock wc;
2416 u32 wc_sec_hi;
2417 u64 wall_nsec;
2418
2419 if (!wall_clock)
2420 return;
2421
2422 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2423 if (r)
2424 return;
2425
2426 if (version & 1)
2427 ++version; /* first time write, random junk */
2428
2429 ++version;
2430
2431 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2432 return;
2433
2434 wall_nsec = kvm_get_wall_clock_epoch(kvm);
2435
2436 wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
2437 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2438 wc.version = version;
2439
2440 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2441
2442 if (sec_hi_ofs) {
2443 wc_sec_hi = wall_nsec >> 32;
2444 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2445 &wc_sec_hi, sizeof(wc_sec_hi));
2446 }
2447
2448 version++;
2449 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2450 }
2451
kvm_write_system_time(struct kvm_vcpu * vcpu,gpa_t system_time,bool old_msr,bool host_initiated)2452 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2453 bool old_msr, bool host_initiated)
2454 {
2455 struct kvm_arch *ka = &vcpu->kvm->arch;
2456
2457 if (vcpu->vcpu_id == 0 && !host_initiated) {
2458 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2459 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2460
2461 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2462 }
2463
2464 vcpu->arch.time = system_time;
2465 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2466
2467 /* we verify if the enable bit is set... */
2468 if (system_time & 1)
2469 kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
2470 sizeof(struct pvclock_vcpu_time_info));
2471 else
2472 kvm_gpc_deactivate(&vcpu->arch.pv_time);
2473
2474 return;
2475 }
2476
div_frac(uint32_t dividend,uint32_t divisor)2477 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2478 {
2479 do_shl32_div32(dividend, divisor);
2480 return dividend;
2481 }
2482
kvm_get_time_scale(uint64_t scaled_hz,uint64_t base_hz,s8 * pshift,u32 * pmultiplier)2483 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2484 s8 *pshift, u32 *pmultiplier)
2485 {
2486 uint64_t scaled64;
2487 int32_t shift = 0;
2488 uint64_t tps64;
2489 uint32_t tps32;
2490
2491 tps64 = base_hz;
2492 scaled64 = scaled_hz;
2493 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2494 tps64 >>= 1;
2495 shift--;
2496 }
2497
2498 tps32 = (uint32_t)tps64;
2499 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2500 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2501 scaled64 >>= 1;
2502 else
2503 tps32 <<= 1;
2504 shift++;
2505 }
2506
2507 *pshift = shift;
2508 *pmultiplier = div_frac(scaled64, tps32);
2509 }
2510
2511 #ifdef CONFIG_X86_64
2512 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2513 #endif
2514
2515 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2516 static unsigned long max_tsc_khz;
2517
adjust_tsc_khz(u32 khz,s32 ppm)2518 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2519 {
2520 u64 v = (u64)khz * (1000000 + ppm);
2521 do_div(v, 1000000);
2522 return v;
2523 }
2524
2525 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2526
set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz,bool scale)2527 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2528 {
2529 u64 ratio;
2530
2531 /* Guest TSC same frequency as host TSC? */
2532 if (!scale) {
2533 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2534 return 0;
2535 }
2536
2537 /* TSC scaling supported? */
2538 if (!kvm_caps.has_tsc_control) {
2539 if (user_tsc_khz > tsc_khz) {
2540 vcpu->arch.tsc_catchup = 1;
2541 vcpu->arch.tsc_always_catchup = 1;
2542 return 0;
2543 } else {
2544 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2545 return -1;
2546 }
2547 }
2548
2549 /* TSC scaling required - calculate ratio */
2550 ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2551 user_tsc_khz, tsc_khz);
2552
2553 if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2554 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2555 user_tsc_khz);
2556 return -1;
2557 }
2558
2559 kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2560 return 0;
2561 }
2562
kvm_set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz)2563 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2564 {
2565 u32 thresh_lo, thresh_hi;
2566 int use_scaling = 0;
2567
2568 /* tsc_khz can be zero if TSC calibration fails */
2569 if (user_tsc_khz == 0) {
2570 /* set tsc_scaling_ratio to a safe value */
2571 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2572 return -1;
2573 }
2574
2575 /* Compute a scale to convert nanoseconds in TSC cycles */
2576 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2577 &vcpu->arch.virtual_tsc_shift,
2578 &vcpu->arch.virtual_tsc_mult);
2579 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2580
2581 /*
2582 * Compute the variation in TSC rate which is acceptable
2583 * within the range of tolerance and decide if the
2584 * rate being applied is within that bounds of the hardware
2585 * rate. If so, no scaling or compensation need be done.
2586 */
2587 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2588 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2589 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2590 pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2591 user_tsc_khz, thresh_lo, thresh_hi);
2592 use_scaling = 1;
2593 }
2594 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2595 }
2596
compute_guest_tsc(struct kvm_vcpu * vcpu,s64 kernel_ns)2597 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2598 {
2599 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2600 vcpu->arch.virtual_tsc_mult,
2601 vcpu->arch.virtual_tsc_shift);
2602 tsc += vcpu->arch.this_tsc_write;
2603 return tsc;
2604 }
2605
2606 #ifdef CONFIG_X86_64
gtod_is_based_on_tsc(int mode)2607 static inline bool gtod_is_based_on_tsc(int mode)
2608 {
2609 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2610 }
2611 #endif
2612
kvm_track_tsc_matching(struct kvm_vcpu * vcpu,bool new_generation)2613 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
2614 {
2615 #ifdef CONFIG_X86_64
2616 struct kvm_arch *ka = &vcpu->kvm->arch;
2617 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2618
2619 /*
2620 * To use the masterclock, the host clocksource must be based on TSC
2621 * and all vCPUs must have matching TSCs. Note, the count for matching
2622 * vCPUs doesn't include the reference vCPU, hence "+1".
2623 */
2624 bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2625 atomic_read(&vcpu->kvm->online_vcpus)) &&
2626 gtod_is_based_on_tsc(gtod->clock.vclock_mode);
2627
2628 /*
2629 * Request a masterclock update if the masterclock needs to be toggled
2630 * on/off, or when starting a new generation and the masterclock is
2631 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2632 * taken _after_ the new generation is created).
2633 */
2634 if ((ka->use_master_clock && new_generation) ||
2635 (ka->use_master_clock != use_master_clock))
2636 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2637
2638 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2639 atomic_read(&vcpu->kvm->online_vcpus),
2640 ka->use_master_clock, gtod->clock.vclock_mode);
2641 #endif
2642 }
2643
2644 /*
2645 * Multiply tsc by a fixed point number represented by ratio.
2646 *
2647 * The most significant 64-N bits (mult) of ratio represent the
2648 * integral part of the fixed point number; the remaining N bits
2649 * (frac) represent the fractional part, ie. ratio represents a fixed
2650 * point number (mult + frac * 2^(-N)).
2651 *
2652 * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2653 */
__scale_tsc(u64 ratio,u64 tsc)2654 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2655 {
2656 return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2657 }
2658
kvm_scale_tsc(u64 tsc,u64 ratio)2659 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2660 {
2661 u64 _tsc = tsc;
2662
2663 if (ratio != kvm_caps.default_tsc_scaling_ratio)
2664 _tsc = __scale_tsc(ratio, tsc);
2665
2666 return _tsc;
2667 }
2668
kvm_compute_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 target_tsc)2669 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2670 {
2671 u64 tsc;
2672
2673 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2674
2675 return target_tsc - tsc;
2676 }
2677
kvm_read_l1_tsc(struct kvm_vcpu * vcpu,u64 host_tsc)2678 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2679 {
2680 return vcpu->arch.l1_tsc_offset +
2681 kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2682 }
2683 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_l1_tsc);
2684
kvm_calc_nested_tsc_offset(u64 l1_offset,u64 l2_offset,u64 l2_multiplier)2685 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2686 {
2687 u64 nested_offset;
2688
2689 if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2690 nested_offset = l1_offset;
2691 else
2692 nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2693 kvm_caps.tsc_scaling_ratio_frac_bits);
2694
2695 nested_offset += l2_offset;
2696 return nested_offset;
2697 }
2698 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_offset);
2699
kvm_calc_nested_tsc_multiplier(u64 l1_multiplier,u64 l2_multiplier)2700 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2701 {
2702 if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2703 return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2704 kvm_caps.tsc_scaling_ratio_frac_bits);
2705
2706 return l1_multiplier;
2707 }
2708 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_multiplier);
2709
kvm_vcpu_write_tsc_offset(struct kvm_vcpu * vcpu,u64 l1_offset)2710 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2711 {
2712 if (vcpu->arch.guest_tsc_protected)
2713 return;
2714
2715 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2716 vcpu->arch.l1_tsc_offset,
2717 l1_offset);
2718
2719 vcpu->arch.l1_tsc_offset = l1_offset;
2720
2721 /*
2722 * If we are here because L1 chose not to trap WRMSR to TSC then
2723 * according to the spec this should set L1's TSC (as opposed to
2724 * setting L1's offset for L2).
2725 */
2726 if (is_guest_mode(vcpu))
2727 vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2728 l1_offset,
2729 kvm_x86_call(get_l2_tsc_offset)(vcpu),
2730 kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2731 else
2732 vcpu->arch.tsc_offset = l1_offset;
2733
2734 kvm_x86_call(write_tsc_offset)(vcpu);
2735 }
2736
kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu * vcpu,u64 l1_multiplier)2737 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2738 {
2739 vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2740
2741 /* Userspace is changing the multiplier while L2 is active */
2742 if (is_guest_mode(vcpu))
2743 vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2744 l1_multiplier,
2745 kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2746 else
2747 vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2748
2749 if (kvm_caps.has_tsc_control)
2750 kvm_x86_call(write_tsc_multiplier)(vcpu);
2751 }
2752
kvm_check_tsc_unstable(void)2753 static inline bool kvm_check_tsc_unstable(void)
2754 {
2755 #ifdef CONFIG_X86_64
2756 /*
2757 * TSC is marked unstable when we're running on Hyper-V,
2758 * 'TSC page' clocksource is good.
2759 */
2760 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2761 return false;
2762 #endif
2763 return check_tsc_unstable();
2764 }
2765
2766 /*
2767 * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2768 * offset for the vcpu and tracks the TSC matching generation that the vcpu
2769 * participates in.
2770 */
__kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 offset,u64 tsc,u64 ns,bool matched,bool user_set_tsc)2771 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2772 u64 ns, bool matched, bool user_set_tsc)
2773 {
2774 struct kvm *kvm = vcpu->kvm;
2775
2776 lockdep_assert_held(&kvm->arch.tsc_write_lock);
2777
2778 if (vcpu->arch.guest_tsc_protected)
2779 return;
2780
2781 if (user_set_tsc)
2782 vcpu->kvm->arch.user_set_tsc = true;
2783
2784 /*
2785 * We also track th most recent recorded KHZ, write and time to
2786 * allow the matching interval to be extended at each write.
2787 */
2788 kvm->arch.last_tsc_nsec = ns;
2789 kvm->arch.last_tsc_write = tsc;
2790 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2791 kvm->arch.last_tsc_offset = offset;
2792
2793 vcpu->arch.last_guest_tsc = tsc;
2794
2795 kvm_vcpu_write_tsc_offset(vcpu, offset);
2796
2797 if (!matched) {
2798 /*
2799 * We split periods of matched TSC writes into generations.
2800 * For each generation, we track the original measured
2801 * nanosecond time, offset, and write, so if TSCs are in
2802 * sync, we can match exact offset, and if not, we can match
2803 * exact software computation in compute_guest_tsc()
2804 *
2805 * These values are tracked in kvm->arch.cur_xxx variables.
2806 */
2807 kvm->arch.cur_tsc_generation++;
2808 kvm->arch.cur_tsc_nsec = ns;
2809 kvm->arch.cur_tsc_write = tsc;
2810 kvm->arch.cur_tsc_offset = offset;
2811 kvm->arch.nr_vcpus_matched_tsc = 0;
2812 } else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2813 kvm->arch.nr_vcpus_matched_tsc++;
2814 }
2815
2816 /* Keep track of which generation this VCPU has synchronized to */
2817 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2818 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2819 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2820
2821 kvm_track_tsc_matching(vcpu, !matched);
2822 }
2823
kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 * user_value)2824 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
2825 {
2826 u64 data = user_value ? *user_value : 0;
2827 struct kvm *kvm = vcpu->kvm;
2828 u64 offset, ns, elapsed;
2829 unsigned long flags;
2830 bool matched = false;
2831 bool synchronizing = false;
2832
2833 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2834 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2835 ns = get_kvmclock_base_ns();
2836 elapsed = ns - kvm->arch.last_tsc_nsec;
2837
2838 if (vcpu->arch.virtual_tsc_khz) {
2839 if (data == 0) {
2840 /*
2841 * Force synchronization when creating a vCPU, or when
2842 * userspace explicitly writes a zero value.
2843 */
2844 synchronizing = true;
2845 } else if (kvm->arch.user_set_tsc) {
2846 u64 tsc_exp = kvm->arch.last_tsc_write +
2847 nsec_to_cycles(vcpu, elapsed);
2848 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2849 /*
2850 * Here lies UAPI baggage: when a user-initiated TSC write has
2851 * a small delta (1 second) of virtual cycle time against the
2852 * previously set vCPU, we assume that they were intended to be
2853 * in sync and the delta was only due to the racy nature of the
2854 * legacy API.
2855 *
2856 * This trick falls down when restoring a guest which genuinely
2857 * has been running for less time than the 1 second of imprecision
2858 * which we allow for in the legacy API. In this case, the first
2859 * value written by userspace (on any vCPU) should not be subject
2860 * to this 'correction' to make it sync up with values that only
2861 * come from the kernel's default vCPU creation. Make the 1-second
2862 * slop hack only trigger if the user_set_tsc flag is already set.
2863 */
2864 synchronizing = data < tsc_exp + tsc_hz &&
2865 data + tsc_hz > tsc_exp;
2866 }
2867 }
2868
2869
2870 /*
2871 * For a reliable TSC, we can match TSC offsets, and for an unstable
2872 * TSC, we add elapsed time in this computation. We could let the
2873 * compensation code attempt to catch up if we fall behind, but
2874 * it's better to try to match offsets from the beginning.
2875 */
2876 if (synchronizing &&
2877 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2878 if (!kvm_check_tsc_unstable()) {
2879 offset = kvm->arch.cur_tsc_offset;
2880 } else {
2881 u64 delta = nsec_to_cycles(vcpu, elapsed);
2882 data += delta;
2883 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2884 }
2885 matched = true;
2886 }
2887
2888 __kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value);
2889 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2890 }
2891
adjust_tsc_offset_guest(struct kvm_vcpu * vcpu,s64 adjustment)2892 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2893 s64 adjustment)
2894 {
2895 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2896 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2897 }
2898
adjust_tsc_offset_host(struct kvm_vcpu * vcpu,s64 adjustment)2899 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2900 {
2901 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2902 WARN_ON(adjustment < 0);
2903 adjustment = kvm_scale_tsc((u64) adjustment,
2904 vcpu->arch.l1_tsc_scaling_ratio);
2905 adjust_tsc_offset_guest(vcpu, adjustment);
2906 }
2907
2908 #ifdef CONFIG_X86_64
2909
read_tsc(void)2910 static u64 read_tsc(void)
2911 {
2912 u64 ret = (u64)rdtsc_ordered();
2913 u64 last = pvclock_gtod_data.clock.cycle_last;
2914
2915 if (likely(ret >= last))
2916 return ret;
2917
2918 /*
2919 * GCC likes to generate cmov here, but this branch is extremely
2920 * predictable (it's just a function of time and the likely is
2921 * very likely) and there's a data dependence, so force GCC
2922 * to generate a branch instead. I don't barrier() because
2923 * we don't actually need a barrier, and if this function
2924 * ever gets inlined it will generate worse code.
2925 */
2926 asm volatile ("");
2927 return last;
2928 }
2929
vgettsc(struct pvclock_clock * clock,u64 * tsc_timestamp,int * mode)2930 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2931 int *mode)
2932 {
2933 u64 tsc_pg_val;
2934 long v;
2935
2936 switch (clock->vclock_mode) {
2937 case VDSO_CLOCKMODE_HVCLOCK:
2938 if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2939 tsc_timestamp, &tsc_pg_val)) {
2940 /* TSC page valid */
2941 *mode = VDSO_CLOCKMODE_HVCLOCK;
2942 v = (tsc_pg_val - clock->cycle_last) &
2943 clock->mask;
2944 } else {
2945 /* TSC page invalid */
2946 *mode = VDSO_CLOCKMODE_NONE;
2947 }
2948 break;
2949 case VDSO_CLOCKMODE_TSC:
2950 *mode = VDSO_CLOCKMODE_TSC;
2951 *tsc_timestamp = read_tsc();
2952 v = (*tsc_timestamp - clock->cycle_last) &
2953 clock->mask;
2954 break;
2955 default:
2956 *mode = VDSO_CLOCKMODE_NONE;
2957 }
2958
2959 if (*mode == VDSO_CLOCKMODE_NONE)
2960 *tsc_timestamp = v = 0;
2961
2962 return v * clock->mult;
2963 }
2964
2965 /*
2966 * As with get_kvmclock_base_ns(), this counts from boot time, at the
2967 * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2968 */
do_kvmclock_base(s64 * t,u64 * tsc_timestamp)2969 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
2970 {
2971 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2972 unsigned long seq;
2973 int mode;
2974 u64 ns;
2975
2976 do {
2977 seq = read_seqcount_begin(>od->seq);
2978 ns = gtod->raw_clock.base_cycles;
2979 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2980 ns >>= gtod->raw_clock.shift;
2981 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2982 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2983 *t = ns;
2984
2985 return mode;
2986 }
2987
2988 /*
2989 * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2990 * no boot time offset.
2991 */
do_monotonic(s64 * t,u64 * tsc_timestamp)2992 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2993 {
2994 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2995 unsigned long seq;
2996 int mode;
2997 u64 ns;
2998
2999 do {
3000 seq = read_seqcount_begin(>od->seq);
3001 ns = gtod->clock.base_cycles;
3002 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
3003 ns >>= gtod->clock.shift;
3004 ns += ktime_to_ns(gtod->clock.offset);
3005 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
3006 *t = ns;
3007
3008 return mode;
3009 }
3010
do_realtime(struct timespec64 * ts,u64 * tsc_timestamp)3011 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
3012 {
3013 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
3014 unsigned long seq;
3015 int mode;
3016 u64 ns;
3017
3018 do {
3019 seq = read_seqcount_begin(>od->seq);
3020 ts->tv_sec = gtod->wall_time_sec;
3021 ns = gtod->clock.base_cycles;
3022 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
3023 ns >>= gtod->clock.shift;
3024 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
3025
3026 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
3027 ts->tv_nsec = ns;
3028
3029 return mode;
3030 }
3031
3032 /*
3033 * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
3034 * reports the TSC value from which it do so. Returns true if host is
3035 * using TSC based clocksource.
3036 */
kvm_get_time_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)3037 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
3038 {
3039 /* checked again under seqlock below */
3040 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3041 return false;
3042
3043 return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
3044 tsc_timestamp));
3045 }
3046
3047 /*
3048 * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
3049 * so. Returns true if host is using TSC based clocksource.
3050 */
kvm_get_monotonic_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)3051 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
3052 {
3053 /* checked again under seqlock below */
3054 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3055 return false;
3056
3057 return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
3058 tsc_timestamp));
3059 }
3060
3061 /*
3062 * Calculates CLOCK_REALTIME and reports the TSC value from which it did
3063 * so. Returns true if host is using TSC based clocksource.
3064 *
3065 * DO NOT USE this for anything related to migration. You want CLOCK_TAI
3066 * for that.
3067 */
kvm_get_walltime_and_clockread(struct timespec64 * ts,u64 * tsc_timestamp)3068 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
3069 u64 *tsc_timestamp)
3070 {
3071 /* checked again under seqlock below */
3072 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3073 return false;
3074
3075 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
3076 }
3077 #endif
3078
3079 /*
3080 *
3081 * Assuming a stable TSC across physical CPUS, and a stable TSC
3082 * across virtual CPUs, the following condition is possible.
3083 * Each numbered line represents an event visible to both
3084 * CPUs at the next numbered event.
3085 *
3086 * "timespecX" represents host monotonic time. "tscX" represents
3087 * RDTSC value.
3088 *
3089 * VCPU0 on CPU0 | VCPU1 on CPU1
3090 *
3091 * 1. read timespec0,tsc0
3092 * 2. | timespec1 = timespec0 + N
3093 * | tsc1 = tsc0 + M
3094 * 3. transition to guest | transition to guest
3095 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
3096 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
3097 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
3098 *
3099 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
3100 *
3101 * - ret0 < ret1
3102 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
3103 * ...
3104 * - 0 < N - M => M < N
3105 *
3106 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
3107 * always the case (the difference between two distinct xtime instances
3108 * might be smaller then the difference between corresponding TSC reads,
3109 * when updating guest vcpus pvclock areas).
3110 *
3111 * To avoid that problem, do not allow visibility of distinct
3112 * system_timestamp/tsc_timestamp values simultaneously: use a master
3113 * copy of host monotonic time values. Update that master copy
3114 * in lockstep.
3115 *
3116 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
3117 *
3118 */
3119
pvclock_update_vm_gtod_copy(struct kvm * kvm)3120 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
3121 {
3122 #ifdef CONFIG_X86_64
3123 struct kvm_arch *ka = &kvm->arch;
3124 int vclock_mode;
3125 bool host_tsc_clocksource, vcpus_matched;
3126
3127 lockdep_assert_held(&kvm->arch.tsc_write_lock);
3128 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
3129 atomic_read(&kvm->online_vcpus));
3130
3131 /*
3132 * If the host uses TSC clock, then passthrough TSC as stable
3133 * to the guest.
3134 */
3135 host_tsc_clocksource = kvm_get_time_and_clockread(
3136 &ka->master_kernel_ns,
3137 &ka->master_cycle_now);
3138
3139 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
3140 && !ka->backwards_tsc_observed
3141 && !ka->boot_vcpu_runs_old_kvmclock;
3142
3143 if (ka->use_master_clock)
3144 atomic_set(&kvm_guest_has_master_clock, 1);
3145
3146 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
3147 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3148 vcpus_matched);
3149 #endif
3150 }
3151
kvm_make_mclock_inprogress_request(struct kvm * kvm)3152 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
3153 {
3154 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3155 }
3156
__kvm_start_pvclock_update(struct kvm * kvm)3157 static void __kvm_start_pvclock_update(struct kvm *kvm)
3158 {
3159 raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3160 write_seqcount_begin(&kvm->arch.pvclock_sc);
3161 }
3162
kvm_start_pvclock_update(struct kvm * kvm)3163 static void kvm_start_pvclock_update(struct kvm *kvm)
3164 {
3165 kvm_make_mclock_inprogress_request(kvm);
3166
3167 /* no guest entries from this point */
3168 __kvm_start_pvclock_update(kvm);
3169 }
3170
kvm_end_pvclock_update(struct kvm * kvm)3171 static void kvm_end_pvclock_update(struct kvm *kvm)
3172 {
3173 struct kvm_arch *ka = &kvm->arch;
3174 struct kvm_vcpu *vcpu;
3175 unsigned long i;
3176
3177 write_seqcount_end(&ka->pvclock_sc);
3178 raw_spin_unlock_irq(&ka->tsc_write_lock);
3179 kvm_for_each_vcpu(i, vcpu, kvm)
3180 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3181
3182 /* guest entries allowed */
3183 kvm_for_each_vcpu(i, vcpu, kvm)
3184 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
3185 }
3186
kvm_update_masterclock(struct kvm * kvm)3187 static void kvm_update_masterclock(struct kvm *kvm)
3188 {
3189 kvm_hv_request_tsc_page_update(kvm);
3190 kvm_start_pvclock_update(kvm);
3191 pvclock_update_vm_gtod_copy(kvm);
3192 kvm_end_pvclock_update(kvm);
3193 }
3194
3195 /*
3196 * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3197 * per-CPU value (which may be zero if a CPU is going offline). Note, tsc_khz
3198 * can change during boot even if the TSC is constant, as it's possible for KVM
3199 * to be loaded before TSC calibration completes. Ideally, KVM would get a
3200 * notification when calibration completes, but practically speaking calibration
3201 * will complete before userspace is alive enough to create VMs.
3202 */
get_cpu_tsc_khz(void)3203 static unsigned long get_cpu_tsc_khz(void)
3204 {
3205 if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3206 return tsc_khz;
3207 else
3208 return __this_cpu_read(cpu_tsc_khz);
3209 }
3210
3211 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc. */
__get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3212 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3213 {
3214 struct kvm_arch *ka = &kvm->arch;
3215 struct pvclock_vcpu_time_info hv_clock;
3216
3217 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
3218 get_cpu();
3219
3220 data->flags = 0;
3221 if (ka->use_master_clock &&
3222 (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
3223 #ifdef CONFIG_X86_64
3224 struct timespec64 ts;
3225
3226 if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3227 data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3228 data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3229 } else
3230 #endif
3231 data->host_tsc = rdtsc();
3232
3233 data->flags |= KVM_CLOCK_TSC_STABLE;
3234 hv_clock.tsc_timestamp = ka->master_cycle_now;
3235 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3236 kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
3237 &hv_clock.tsc_shift,
3238 &hv_clock.tsc_to_system_mul);
3239 data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3240 } else {
3241 data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3242 }
3243
3244 put_cpu();
3245 }
3246
get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3247 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3248 {
3249 struct kvm_arch *ka = &kvm->arch;
3250 unsigned seq;
3251
3252 do {
3253 seq = read_seqcount_begin(&ka->pvclock_sc);
3254 __get_kvmclock(kvm, data);
3255 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3256 }
3257
get_kvmclock_ns(struct kvm * kvm)3258 u64 get_kvmclock_ns(struct kvm *kvm)
3259 {
3260 struct kvm_clock_data data;
3261
3262 get_kvmclock(kvm, &data);
3263 return data.clock;
3264 }
3265
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)3266 static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
3267 struct kvm_vcpu *vcpu,
3268 struct gfn_to_pfn_cache *gpc,
3269 unsigned int offset)
3270 {
3271 struct pvclock_vcpu_time_info *guest_hv_clock;
3272 struct pvclock_vcpu_time_info hv_clock;
3273 unsigned long flags;
3274
3275 memcpy(&hv_clock, ref_hv_clock, sizeof(hv_clock));
3276
3277 read_lock_irqsave(&gpc->lock, flags);
3278 while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
3279 read_unlock_irqrestore(&gpc->lock, flags);
3280
3281 if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
3282 return;
3283
3284 read_lock_irqsave(&gpc->lock, flags);
3285 }
3286
3287 guest_hv_clock = (void *)(gpc->khva + offset);
3288
3289 /*
3290 * This VCPU is paused, but it's legal for a guest to read another
3291 * VCPU's kvmclock, so we really have to follow the specification where
3292 * it says that version is odd if data is being modified, and even after
3293 * it is consistent.
3294 */
3295
3296 guest_hv_clock->version = hv_clock.version = (guest_hv_clock->version + 1) | 1;
3297 smp_wmb();
3298
3299 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3300 hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3301
3302 memcpy(guest_hv_clock, &hv_clock, sizeof(*guest_hv_clock));
3303
3304 smp_wmb();
3305
3306 guest_hv_clock->version = ++hv_clock.version;
3307
3308 kvm_gpc_mark_dirty_in_slot(gpc);
3309 read_unlock_irqrestore(&gpc->lock, flags);
3310
3311 trace_kvm_pvclock_update(vcpu->vcpu_id, &hv_clock);
3312 }
3313
kvm_guest_time_update(struct kvm_vcpu * v)3314 int kvm_guest_time_update(struct kvm_vcpu *v)
3315 {
3316 struct pvclock_vcpu_time_info hv_clock = {};
3317 unsigned long flags, tgt_tsc_khz;
3318 unsigned seq;
3319 struct kvm_vcpu_arch *vcpu = &v->arch;
3320 struct kvm_arch *ka = &v->kvm->arch;
3321 s64 kernel_ns;
3322 u64 tsc_timestamp, host_tsc;
3323 bool use_master_clock;
3324
3325 kernel_ns = 0;
3326 host_tsc = 0;
3327
3328 /*
3329 * If the host uses TSC clock, then passthrough TSC as stable
3330 * to the guest.
3331 */
3332 do {
3333 seq = read_seqcount_begin(&ka->pvclock_sc);
3334 use_master_clock = ka->use_master_clock;
3335 if (use_master_clock) {
3336 host_tsc = ka->master_cycle_now;
3337 kernel_ns = ka->master_kernel_ns;
3338 }
3339 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3340
3341 /* Keep irq disabled to prevent changes to the clock */
3342 local_irq_save(flags);
3343 tgt_tsc_khz = get_cpu_tsc_khz();
3344 if (unlikely(tgt_tsc_khz == 0)) {
3345 local_irq_restore(flags);
3346 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3347 return 1;
3348 }
3349 if (!use_master_clock) {
3350 host_tsc = rdtsc();
3351 kernel_ns = get_kvmclock_base_ns();
3352 }
3353
3354 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3355
3356 /*
3357 * We may have to catch up the TSC to match elapsed wall clock
3358 * time for two reasons, even if kvmclock is used.
3359 * 1) CPU could have been running below the maximum TSC rate
3360 * 2) Broken TSC compensation resets the base at each VCPU
3361 * entry to avoid unknown leaps of TSC even when running
3362 * again on the same CPU. This may cause apparent elapsed
3363 * time to disappear, and the guest to stand still or run
3364 * very slowly.
3365 */
3366 if (vcpu->tsc_catchup) {
3367 u64 tsc = compute_guest_tsc(v, kernel_ns);
3368 if (tsc > tsc_timestamp) {
3369 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3370 tsc_timestamp = tsc;
3371 }
3372 }
3373
3374 local_irq_restore(flags);
3375
3376 /* With all the info we got, fill in the values */
3377
3378 if (kvm_caps.has_tsc_control) {
3379 tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3380 v->arch.l1_tsc_scaling_ratio);
3381 tgt_tsc_khz = tgt_tsc_khz ? : 1;
3382 }
3383
3384 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3385 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3386 &vcpu->pvclock_tsc_shift,
3387 &vcpu->pvclock_tsc_mul);
3388 vcpu->hw_tsc_khz = tgt_tsc_khz;
3389 }
3390
3391 hv_clock.tsc_shift = vcpu->pvclock_tsc_shift;
3392 hv_clock.tsc_to_system_mul = vcpu->pvclock_tsc_mul;
3393 hv_clock.tsc_timestamp = tsc_timestamp;
3394 hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3395 vcpu->last_guest_tsc = tsc_timestamp;
3396
3397 /* If the host uses TSC clocksource, then it is stable */
3398 hv_clock.flags = 0;
3399 if (use_master_clock)
3400 hv_clock.flags |= PVCLOCK_TSC_STABLE_BIT;
3401
3402 if (vcpu->pv_time.active) {
3403 /*
3404 * GUEST_STOPPED is only supported by kvmclock, and KVM's
3405 * historic behavior is to only process the request if kvmclock
3406 * is active/enabled.
3407 */
3408 if (vcpu->pvclock_set_guest_stopped_request) {
3409 hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3410 vcpu->pvclock_set_guest_stopped_request = false;
3411 }
3412 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->pv_time, 0);
3413
3414 hv_clock.flags &= ~PVCLOCK_GUEST_STOPPED;
3415 }
3416
3417 kvm_hv_setup_tsc_page(v->kvm, &hv_clock);
3418
3419 #ifdef CONFIG_KVM_XEN
3420 /*
3421 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3422 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3423 * This default behaviour led to bugs in some guest kernels which cause
3424 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3425 *
3426 * Note! Clear TSC_STABLE only for Xen clocks, i.e. the order matters!
3427 */
3428 if (ka->xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
3429 hv_clock.flags &= ~PVCLOCK_TSC_STABLE_BIT;
3430
3431 if (vcpu->xen.vcpu_info_cache.active)
3432 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_info_cache,
3433 offsetof(struct compat_vcpu_info, time));
3434 if (vcpu->xen.vcpu_time_info_cache.active)
3435 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_time_info_cache, 0);
3436 #endif
3437 return 0;
3438 }
3439
3440 /*
3441 * The pvclock_wall_clock ABI tells the guest the wall clock time at
3442 * which it started (i.e. its epoch, when its kvmclock was zero).
3443 *
3444 * In fact those clocks are subtly different; wall clock frequency is
3445 * adjusted by NTP and has leap seconds, while the kvmclock is a
3446 * simple function of the TSC without any such adjustment.
3447 *
3448 * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3449 * that and kvmclock, but even that would be subject to change over
3450 * time.
3451 *
3452 * Attempt to calculate the epoch at a given moment using the *same*
3453 * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3454 * wallclock and kvmclock times, and subtracting one from the other.
3455 *
3456 * Fall back to using their values at slightly different moments by
3457 * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3458 */
kvm_get_wall_clock_epoch(struct kvm * kvm)3459 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3460 {
3461 #ifdef CONFIG_X86_64
3462 struct pvclock_vcpu_time_info hv_clock;
3463 struct kvm_arch *ka = &kvm->arch;
3464 unsigned long seq, local_tsc_khz;
3465 struct timespec64 ts;
3466 uint64_t host_tsc;
3467
3468 do {
3469 seq = read_seqcount_begin(&ka->pvclock_sc);
3470
3471 local_tsc_khz = 0;
3472 if (!ka->use_master_clock)
3473 break;
3474
3475 /*
3476 * The TSC read and the call to get_cpu_tsc_khz() must happen
3477 * on the same CPU.
3478 */
3479 get_cpu();
3480
3481 local_tsc_khz = get_cpu_tsc_khz();
3482
3483 if (local_tsc_khz &&
3484 !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3485 local_tsc_khz = 0; /* Fall back to old method */
3486
3487 put_cpu();
3488
3489 /*
3490 * These values must be snapshotted within the seqcount loop.
3491 * After that, it's just mathematics which can happen on any
3492 * CPU at any time.
3493 */
3494 hv_clock.tsc_timestamp = ka->master_cycle_now;
3495 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3496
3497 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3498
3499 /*
3500 * If the conditions were right, and obtaining the wallclock+TSC was
3501 * successful, calculate the KVM clock at the corresponding time and
3502 * subtract one from the other to get the guest's epoch in nanoseconds
3503 * since 1970-01-01.
3504 */
3505 if (local_tsc_khz) {
3506 kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3507 &hv_clock.tsc_shift,
3508 &hv_clock.tsc_to_system_mul);
3509 return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3510 __pvclock_read_cycles(&hv_clock, host_tsc);
3511 }
3512 #endif
3513 return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3514 }
3515
3516 /*
3517 * kvmclock updates which are isolated to a given vcpu, such as
3518 * vcpu->cpu migration, should not allow system_timestamp from
3519 * the rest of the vcpus to remain static.
3520 *
3521 * So in those cases, request a kvmclock update for all vcpus.
3522 * The worst case for a remote vcpu to update its kvmclock
3523 * is then bounded by maximum nohz sleep latency.
3524 */
kvm_gen_kvmclock_update(struct kvm_vcpu * v)3525 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3526 {
3527 unsigned long i;
3528 struct kvm_vcpu *vcpu;
3529 struct kvm *kvm = v->kvm;
3530
3531 kvm_for_each_vcpu(i, vcpu, kvm) {
3532 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3533 kvm_vcpu_kick(vcpu);
3534 }
3535 }
3536
3537 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
is_mci_control_msr(u32 msr)3538 static bool is_mci_control_msr(u32 msr)
3539 {
3540 return (msr & 3) == 0;
3541 }
is_mci_status_msr(u32 msr)3542 static bool is_mci_status_msr(u32 msr)
3543 {
3544 return (msr & 3) == 1;
3545 }
3546
3547 /*
3548 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3549 */
can_set_mci_status(struct kvm_vcpu * vcpu)3550 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3551 {
3552 /* McStatusWrEn enabled? */
3553 if (guest_cpuid_is_amd_compatible(vcpu))
3554 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3555
3556 return false;
3557 }
3558
set_msr_mce(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3559 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3560 {
3561 u64 mcg_cap = vcpu->arch.mcg_cap;
3562 unsigned bank_num = mcg_cap & 0xff;
3563 u32 msr = msr_info->index;
3564 u64 data = msr_info->data;
3565 u32 offset, last_msr;
3566
3567 switch (msr) {
3568 case MSR_IA32_MCG_STATUS:
3569 vcpu->arch.mcg_status = data;
3570 break;
3571 case MSR_IA32_MCG_CTL:
3572 if (!(mcg_cap & MCG_CTL_P) &&
3573 (data || !msr_info->host_initiated))
3574 return 1;
3575 if (data != 0 && data != ~(u64)0)
3576 return 1;
3577 vcpu->arch.mcg_ctl = data;
3578 break;
3579 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3580 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3581 if (msr > last_msr)
3582 return 1;
3583
3584 if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3585 return 1;
3586 /* An attempt to write a 1 to a reserved bit raises #GP */
3587 if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3588 return 1;
3589 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3590 last_msr + 1 - MSR_IA32_MC0_CTL2);
3591 vcpu->arch.mci_ctl2_banks[offset] = data;
3592 break;
3593 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3594 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3595 if (msr > last_msr)
3596 return 1;
3597
3598 /*
3599 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3600 * values are architecturally undefined. But, some Linux
3601 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3602 * issue on AMD K8s, allow bit 10 to be clear when setting all
3603 * other bits in order to avoid an uncaught #GP in the guest.
3604 *
3605 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3606 * single-bit ECC data errors.
3607 */
3608 if (is_mci_control_msr(msr) &&
3609 data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3610 return 1;
3611
3612 /*
3613 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3614 * AMD-based CPUs allow non-zero values, but if and only if
3615 * HWCR[McStatusWrEn] is set.
3616 */
3617 if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3618 data != 0 && !can_set_mci_status(vcpu))
3619 return 1;
3620
3621 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3622 last_msr + 1 - MSR_IA32_MC0_CTL);
3623 vcpu->arch.mce_banks[offset] = data;
3624 break;
3625 default:
3626 return 1;
3627 }
3628 return 0;
3629 }
3630
kvm_pv_enable_async_pf(struct kvm_vcpu * vcpu,u64 data)3631 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3632 {
3633 gpa_t gpa = data & ~0x3f;
3634
3635 /* Bits 4:5 are reserved, Should be zero */
3636 if (data & 0x30)
3637 return 1;
3638
3639 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3640 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3641 return 1;
3642
3643 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3644 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3645 return 1;
3646
3647 if (!lapic_in_kernel(vcpu))
3648 return data ? 1 : 0;
3649
3650 vcpu->arch.apf.msr_en_val = data;
3651
3652 if (!kvm_pv_async_pf_enabled(vcpu)) {
3653 kvm_clear_async_pf_completion_queue(vcpu);
3654 kvm_async_pf_hash_reset(vcpu);
3655 return 0;
3656 }
3657
3658 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3659 sizeof(u64)))
3660 return 1;
3661
3662 vcpu->arch.apf.send_always = (data & KVM_ASYNC_PF_SEND_ALWAYS);
3663 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3664
3665 kvm_async_pf_wakeup_all(vcpu);
3666
3667 return 0;
3668 }
3669
kvm_pv_enable_async_pf_int(struct kvm_vcpu * vcpu,u64 data)3670 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3671 {
3672 /* Bits 8-63 are reserved */
3673 if (data >> 8)
3674 return 1;
3675
3676 if (!lapic_in_kernel(vcpu))
3677 return 1;
3678
3679 vcpu->arch.apf.msr_int_val = data;
3680
3681 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3682
3683 return 0;
3684 }
3685
kvmclock_reset(struct kvm_vcpu * vcpu)3686 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3687 {
3688 kvm_gpc_deactivate(&vcpu->arch.pv_time);
3689 vcpu->arch.time = 0;
3690 }
3691
kvm_vcpu_flush_tlb_all(struct kvm_vcpu * vcpu)3692 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3693 {
3694 ++vcpu->stat.tlb_flush;
3695 kvm_x86_call(flush_tlb_all)(vcpu);
3696
3697 /* Flushing all ASIDs flushes the current ASID... */
3698 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3699 }
3700
kvm_vcpu_flush_tlb_guest(struct kvm_vcpu * vcpu)3701 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3702 {
3703 ++vcpu->stat.tlb_flush;
3704
3705 if (!tdp_enabled) {
3706 /*
3707 * A TLB flush on behalf of the guest is equivalent to
3708 * INVPCID(all), toggling CR4.PGE, etc., which requires
3709 * a forced sync of the shadow page tables. Ensure all the
3710 * roots are synced and the guest TLB in hardware is clean.
3711 */
3712 kvm_mmu_sync_roots(vcpu);
3713 kvm_mmu_sync_prev_roots(vcpu);
3714 }
3715
3716 kvm_x86_call(flush_tlb_guest)(vcpu);
3717
3718 /*
3719 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3720 * grained flushing.
3721 */
3722 kvm_hv_vcpu_purge_flush_tlb(vcpu);
3723 }
3724
3725
kvm_vcpu_flush_tlb_current(struct kvm_vcpu * vcpu)3726 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3727 {
3728 ++vcpu->stat.tlb_flush;
3729 kvm_x86_call(flush_tlb_current)(vcpu);
3730 }
3731
3732 /*
3733 * Service "local" TLB flush requests, which are specific to the current MMU
3734 * context. In addition to the generic event handling in vcpu_enter_guest(),
3735 * TLB flushes that are targeted at an MMU context also need to be serviced
3736 * prior before nested VM-Enter/VM-Exit.
3737 */
kvm_service_local_tlb_flush_requests(struct kvm_vcpu * vcpu)3738 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3739 {
3740 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3741 kvm_vcpu_flush_tlb_current(vcpu);
3742
3743 if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3744 kvm_vcpu_flush_tlb_guest(vcpu);
3745 }
3746 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_service_local_tlb_flush_requests);
3747
record_steal_time(struct kvm_vcpu * vcpu)3748 static void record_steal_time(struct kvm_vcpu *vcpu)
3749 {
3750 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3751 struct kvm_steal_time __user *st;
3752 struct kvm_memslots *slots;
3753 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3754 u64 steal;
3755 u32 version;
3756
3757 if (kvm_xen_msr_enabled(vcpu->kvm)) {
3758 kvm_xen_runstate_set_running(vcpu);
3759 return;
3760 }
3761
3762 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3763 return;
3764
3765 if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3766 return;
3767
3768 slots = kvm_memslots(vcpu->kvm);
3769
3770 if (unlikely(slots->generation != ghc->generation ||
3771 gpa != ghc->gpa ||
3772 kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3773 /* We rely on the fact that it fits in a single page. */
3774 BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3775
3776 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3777 kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3778 return;
3779 }
3780
3781 st = (struct kvm_steal_time __user *)ghc->hva;
3782 /*
3783 * Doing a TLB flush here, on the guest's behalf, can avoid
3784 * expensive IPIs.
3785 */
3786 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3787 u8 st_preempted = 0;
3788 int err = -EFAULT;
3789
3790 if (!user_access_begin(st, sizeof(*st)))
3791 return;
3792
3793 asm volatile("1: xchgb %0, %2\n"
3794 "xor %1, %1\n"
3795 "2:\n"
3796 _ASM_EXTABLE_UA(1b, 2b)
3797 : "+q" (st_preempted),
3798 "+&r" (err),
3799 "+m" (st->preempted));
3800 if (err)
3801 goto out;
3802
3803 user_access_end();
3804
3805 vcpu->arch.st.preempted = 0;
3806
3807 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3808 st_preempted & KVM_VCPU_FLUSH_TLB);
3809 if (st_preempted & KVM_VCPU_FLUSH_TLB)
3810 kvm_vcpu_flush_tlb_guest(vcpu);
3811
3812 if (!user_access_begin(st, sizeof(*st)))
3813 goto dirty;
3814 } else {
3815 if (!user_access_begin(st, sizeof(*st)))
3816 return;
3817
3818 unsafe_put_user(0, &st->preempted, out);
3819 vcpu->arch.st.preempted = 0;
3820 }
3821
3822 unsafe_get_user(version, &st->version, out);
3823 if (version & 1)
3824 version += 1; /* first time write, random junk */
3825
3826 version += 1;
3827 unsafe_put_user(version, &st->version, out);
3828
3829 smp_wmb();
3830
3831 unsafe_get_user(steal, &st->steal, out);
3832 steal += current->sched_info.run_delay -
3833 vcpu->arch.st.last_steal;
3834 vcpu->arch.st.last_steal = current->sched_info.run_delay;
3835 unsafe_put_user(steal, &st->steal, out);
3836
3837 version += 1;
3838 unsafe_put_user(version, &st->version, out);
3839
3840 out:
3841 user_access_end();
3842 dirty:
3843 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3844 }
3845
3846 /*
3847 * Returns true if the MSR in question is managed via XSTATE, i.e. is context
3848 * switched with the rest of guest FPU state.
3849 *
3850 * Note, S_CET is _not_ saved/restored via XSAVES/XRSTORS.
3851 */
is_xstate_managed_msr(struct kvm_vcpu * vcpu,u32 msr)3852 static bool is_xstate_managed_msr(struct kvm_vcpu *vcpu, u32 msr)
3853 {
3854 if (!vcpu)
3855 return false;
3856
3857 switch (msr) {
3858 case MSR_IA32_U_CET:
3859 return guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) ||
3860 guest_cpu_cap_has(vcpu, X86_FEATURE_IBT);
3861 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
3862 return guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK);
3863 default:
3864 return false;
3865 }
3866 }
3867
3868 /*
3869 * Lock (and if necessary, re-load) the guest FPU, i.e. XSTATE, and access an
3870 * MSR that is managed via XSTATE. Note, the caller is responsible for doing
3871 * the initial FPU load, this helper only ensures that guest state is resident
3872 * in hardware (the kernel can load its FPU state in IRQ context).
3873 *
3874 * Note, loading guest values for U_CET and PL[0-3]_SSP while executing in the
3875 * kernel is safe, as U_CET is specific to userspace, and PL[0-3]_SSP are only
3876 * consumed when transitioning to lower privilege levels, i.e. are effectively
3877 * only consumed by userspace as well.
3878 */
kvm_access_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info,int access)3879 static __always_inline void kvm_access_xstate_msr(struct kvm_vcpu *vcpu,
3880 struct msr_data *msr_info,
3881 int access)
3882 {
3883 BUILD_BUG_ON(access != MSR_TYPE_R && access != MSR_TYPE_W);
3884
3885 KVM_BUG_ON(!is_xstate_managed_msr(vcpu, msr_info->index), vcpu->kvm);
3886 KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm);
3887
3888 kvm_fpu_get();
3889 if (access == MSR_TYPE_R)
3890 rdmsrq(msr_info->index, msr_info->data);
3891 else
3892 wrmsrq(msr_info->index, msr_info->data);
3893 kvm_fpu_put();
3894 }
3895
kvm_set_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3896 static void kvm_set_xstate_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3897 {
3898 kvm_access_xstate_msr(vcpu, msr_info, MSR_TYPE_W);
3899 }
3900
kvm_get_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3901 static void kvm_get_xstate_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3902 {
3903 kvm_access_xstate_msr(vcpu, msr_info, MSR_TYPE_R);
3904 }
3905
kvm_set_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3906 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3907 {
3908 u32 msr = msr_info->index;
3909 u64 data = msr_info->data;
3910
3911 /*
3912 * Do not allow host-initiated writes to trigger the Xen hypercall
3913 * page setup; it could incur locking paths which are not expected
3914 * if userspace sets the MSR in an unusual location.
3915 */
3916 if (kvm_xen_is_hypercall_page_msr(vcpu->kvm, msr) &&
3917 !msr_info->host_initiated)
3918 return kvm_xen_write_hypercall_page(vcpu, data);
3919
3920 switch (msr) {
3921 case MSR_AMD64_NB_CFG:
3922 case MSR_IA32_UCODE_WRITE:
3923 case MSR_VM_HSAVE_PA:
3924 case MSR_AMD64_PATCH_LOADER:
3925 case MSR_AMD64_BU_CFG2:
3926 case MSR_AMD64_DC_CFG:
3927 case MSR_AMD64_TW_CFG:
3928 case MSR_F15H_EX_CFG:
3929 break;
3930
3931 case MSR_IA32_UCODE_REV:
3932 if (msr_info->host_initiated)
3933 vcpu->arch.microcode_version = data;
3934 break;
3935 case MSR_IA32_ARCH_CAPABILITIES:
3936 if (!msr_info->host_initiated ||
3937 !guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3938 return KVM_MSR_RET_UNSUPPORTED;
3939 vcpu->arch.arch_capabilities = data;
3940 break;
3941 case MSR_IA32_PERF_CAPABILITIES:
3942 if (!msr_info->host_initiated ||
3943 !guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
3944 return KVM_MSR_RET_UNSUPPORTED;
3945
3946 if (data & ~kvm_caps.supported_perf_cap)
3947 return 1;
3948
3949 /*
3950 * Note, this is not just a performance optimization! KVM
3951 * disallows changing feature MSRs after the vCPU has run; PMU
3952 * refresh will bug the VM if called after the vCPU has run.
3953 */
3954 if (vcpu->arch.perf_capabilities == data)
3955 break;
3956
3957 vcpu->arch.perf_capabilities = data;
3958 kvm_pmu_refresh(vcpu);
3959 kvm_make_request(KVM_REQ_RECALC_INTERCEPTS, vcpu);
3960 break;
3961 case MSR_IA32_PRED_CMD: {
3962 u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3963
3964 if (!msr_info->host_initiated) {
3965 if ((!guest_has_pred_cmd_msr(vcpu)))
3966 return 1;
3967
3968 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3969 !guest_cpu_cap_has(vcpu, X86_FEATURE_AMD_IBPB))
3970 reserved_bits |= PRED_CMD_IBPB;
3971
3972 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SBPB))
3973 reserved_bits |= PRED_CMD_SBPB;
3974 }
3975
3976 if (!boot_cpu_has(X86_FEATURE_IBPB))
3977 reserved_bits |= PRED_CMD_IBPB;
3978
3979 if (!boot_cpu_has(X86_FEATURE_SBPB))
3980 reserved_bits |= PRED_CMD_SBPB;
3981
3982 if (data & reserved_bits)
3983 return 1;
3984
3985 if (!data)
3986 break;
3987
3988 wrmsrq(MSR_IA32_PRED_CMD, data);
3989 break;
3990 }
3991 case MSR_IA32_FLUSH_CMD:
3992 if (!msr_info->host_initiated &&
3993 !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D))
3994 return 1;
3995
3996 if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
3997 return 1;
3998 if (!data)
3999 break;
4000
4001 wrmsrq(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
4002 break;
4003 case MSR_EFER:
4004 return set_efer(vcpu, msr_info);
4005 case MSR_K7_HWCR:
4006 data &= ~(u64)0x40; /* ignore flush filter disable */
4007 data &= ~(u64)0x100; /* ignore ignne emulation enable */
4008 data &= ~(u64)0x8; /* ignore TLB cache disable */
4009
4010 /*
4011 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
4012 * through at least v6.6 whine if TscFreqSel is clear,
4013 * depending on F/M/S.
4014 */
4015 if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
4016 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4017 return 1;
4018 }
4019 vcpu->arch.msr_hwcr = data;
4020 break;
4021 case MSR_FAM10H_MMIO_CONF_BASE:
4022 if (data != 0) {
4023 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4024 return 1;
4025 }
4026 break;
4027 case MSR_IA32_CR_PAT:
4028 if (!kvm_pat_valid(data))
4029 return 1;
4030
4031 vcpu->arch.pat = data;
4032 break;
4033 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4034 case MSR_MTRRdefType:
4035 return kvm_mtrr_set_msr(vcpu, msr, data);
4036 case MSR_IA32_APICBASE:
4037 return kvm_apic_set_base(vcpu, data, msr_info->host_initiated);
4038 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4039 return kvm_x2apic_msr_write(vcpu, msr, data);
4040 case MSR_IA32_TSC_DEADLINE:
4041 kvm_set_lapic_tscdeadline_msr(vcpu, data);
4042 break;
4043 case MSR_IA32_TSC_ADJUST:
4044 if (guest_cpu_cap_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
4045 if (!msr_info->host_initiated) {
4046 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
4047 adjust_tsc_offset_guest(vcpu, adj);
4048 /* Before back to guest, tsc_timestamp must be adjusted
4049 * as well, otherwise guest's percpu pvclock time could jump.
4050 */
4051 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4052 }
4053 vcpu->arch.ia32_tsc_adjust_msr = data;
4054 }
4055 break;
4056 case MSR_IA32_MISC_ENABLE: {
4057 u64 old_val = vcpu->arch.ia32_misc_enable_msr;
4058
4059 if (!msr_info->host_initiated) {
4060 /* RO bits */
4061 if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
4062 return 1;
4063
4064 /* R bits, i.e. writes are ignored, but don't fault. */
4065 data = data & ~MSR_IA32_MISC_ENABLE_EMON;
4066 data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
4067 }
4068
4069 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
4070 ((old_val ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
4071 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_XMM3))
4072 return 1;
4073 vcpu->arch.ia32_misc_enable_msr = data;
4074 vcpu->arch.cpuid_dynamic_bits_dirty = true;
4075 } else {
4076 vcpu->arch.ia32_misc_enable_msr = data;
4077 }
4078 break;
4079 }
4080 case MSR_IA32_SMBASE:
4081 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4082 return 1;
4083 vcpu->arch.smbase = data;
4084 break;
4085 case MSR_IA32_POWER_CTL:
4086 vcpu->arch.msr_ia32_power_ctl = data;
4087 break;
4088 case MSR_IA32_TSC:
4089 if (msr_info->host_initiated) {
4090 kvm_synchronize_tsc(vcpu, &data);
4091 } else if (!vcpu->arch.guest_tsc_protected) {
4092 u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
4093 adjust_tsc_offset_guest(vcpu, adj);
4094 vcpu->arch.ia32_tsc_adjust_msr += adj;
4095 }
4096 break;
4097 case MSR_IA32_XSS:
4098 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4099 return KVM_MSR_RET_UNSUPPORTED;
4100
4101 if (data & ~vcpu->arch.guest_supported_xss)
4102 return 1;
4103 if (vcpu->arch.ia32_xss == data)
4104 break;
4105 vcpu->arch.ia32_xss = data;
4106 vcpu->arch.cpuid_dynamic_bits_dirty = true;
4107 break;
4108 case MSR_SMI_COUNT:
4109 if (!msr_info->host_initiated)
4110 return 1;
4111 vcpu->arch.smi_count = data;
4112 break;
4113 case MSR_KVM_WALL_CLOCK_NEW:
4114 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4115 return KVM_MSR_RET_UNSUPPORTED;
4116
4117 vcpu->kvm->arch.wall_clock = data;
4118 kvm_write_wall_clock(vcpu->kvm, data, 0);
4119 break;
4120 case MSR_KVM_WALL_CLOCK:
4121 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4122 return KVM_MSR_RET_UNSUPPORTED;
4123
4124 vcpu->kvm->arch.wall_clock = data;
4125 kvm_write_wall_clock(vcpu->kvm, data, 0);
4126 break;
4127 case MSR_KVM_SYSTEM_TIME_NEW:
4128 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4129 return KVM_MSR_RET_UNSUPPORTED;
4130
4131 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
4132 break;
4133 case MSR_KVM_SYSTEM_TIME:
4134 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4135 return KVM_MSR_RET_UNSUPPORTED;
4136
4137 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
4138 break;
4139 case MSR_KVM_ASYNC_PF_EN:
4140 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4141 return KVM_MSR_RET_UNSUPPORTED;
4142
4143 if (kvm_pv_enable_async_pf(vcpu, data))
4144 return 1;
4145 break;
4146 case MSR_KVM_ASYNC_PF_INT:
4147 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4148 return KVM_MSR_RET_UNSUPPORTED;
4149
4150 if (kvm_pv_enable_async_pf_int(vcpu, data))
4151 return 1;
4152 break;
4153 case MSR_KVM_ASYNC_PF_ACK:
4154 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4155 return KVM_MSR_RET_UNSUPPORTED;
4156 if (data & 0x1) {
4157 /*
4158 * Pairs with the smp_mb__after_atomic() in
4159 * kvm_arch_async_page_present_queued().
4160 */
4161 smp_store_mb(vcpu->arch.apf.pageready_pending, false);
4162
4163 kvm_check_async_pf_completion(vcpu);
4164 }
4165 break;
4166 case MSR_KVM_STEAL_TIME:
4167 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4168 return KVM_MSR_RET_UNSUPPORTED;
4169
4170 if (unlikely(!sched_info_on()))
4171 return 1;
4172
4173 if (data & KVM_STEAL_RESERVED_MASK)
4174 return 1;
4175
4176 vcpu->arch.st.msr_val = data;
4177
4178 if (!(data & KVM_MSR_ENABLED))
4179 break;
4180
4181 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4182
4183 break;
4184 case MSR_KVM_PV_EOI_EN:
4185 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4186 return KVM_MSR_RET_UNSUPPORTED;
4187
4188 if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
4189 return 1;
4190 break;
4191
4192 case MSR_KVM_POLL_CONTROL:
4193 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4194 return KVM_MSR_RET_UNSUPPORTED;
4195
4196 /* only enable bit supported */
4197 if (data & (-1ULL << 1))
4198 return 1;
4199
4200 vcpu->arch.msr_kvm_poll_control = data;
4201 break;
4202
4203 case MSR_IA32_MCG_CTL:
4204 case MSR_IA32_MCG_STATUS:
4205 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4206 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4207 return set_msr_mce(vcpu, msr_info);
4208
4209 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4210 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4211 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4212 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4213 if (kvm_pmu_is_valid_msr(vcpu, msr))
4214 return kvm_pmu_set_msr(vcpu, msr_info);
4215
4216 if (data)
4217 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4218 break;
4219 case MSR_K7_CLK_CTL:
4220 /*
4221 * Ignore all writes to this no longer documented MSR.
4222 * Writes are only relevant for old K7 processors,
4223 * all pre-dating SVM, but a recommended workaround from
4224 * AMD for these chips. It is possible to specify the
4225 * affected processor models on the command line, hence
4226 * the need to ignore the workaround.
4227 */
4228 break;
4229 #ifdef CONFIG_KVM_HYPERV
4230 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4231 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4232 case HV_X64_MSR_SYNDBG_OPTIONS:
4233 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4234 case HV_X64_MSR_CRASH_CTL:
4235 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4236 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4237 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4238 case HV_X64_MSR_TSC_EMULATION_STATUS:
4239 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4240 return kvm_hv_set_msr_common(vcpu, msr, data,
4241 msr_info->host_initiated);
4242 #endif
4243 case MSR_IA32_BBL_CR_CTL3:
4244 /* Drop writes to this legacy MSR -- see rdmsr
4245 * counterpart for further detail.
4246 */
4247 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4248 break;
4249 case MSR_AMD64_OSVW_ID_LENGTH:
4250 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4251 return 1;
4252 vcpu->arch.osvw.length = data;
4253 break;
4254 case MSR_AMD64_OSVW_STATUS:
4255 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4256 return 1;
4257 vcpu->arch.osvw.status = data;
4258 break;
4259 case MSR_PLATFORM_INFO:
4260 if (!msr_info->host_initiated)
4261 return 1;
4262 vcpu->arch.msr_platform_info = data;
4263 break;
4264 case MSR_MISC_FEATURES_ENABLES:
4265 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4266 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4267 !supports_cpuid_fault(vcpu)))
4268 return 1;
4269 vcpu->arch.msr_misc_features_enables = data;
4270 break;
4271 #ifdef CONFIG_X86_64
4272 case MSR_IA32_XFD:
4273 if (!msr_info->host_initiated &&
4274 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4275 return 1;
4276
4277 if (data & ~kvm_guest_supported_xfd(vcpu))
4278 return 1;
4279
4280 fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4281 break;
4282 case MSR_IA32_XFD_ERR:
4283 if (!msr_info->host_initiated &&
4284 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4285 return 1;
4286
4287 if (data & ~kvm_guest_supported_xfd(vcpu))
4288 return 1;
4289
4290 vcpu->arch.guest_fpu.xfd_err = data;
4291 break;
4292 #endif
4293 case MSR_IA32_U_CET:
4294 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
4295 kvm_set_xstate_msr(vcpu, msr_info);
4296 break;
4297 default:
4298 if (kvm_pmu_is_valid_msr(vcpu, msr))
4299 return kvm_pmu_set_msr(vcpu, msr_info);
4300
4301 return KVM_MSR_RET_UNSUPPORTED;
4302 }
4303 return 0;
4304 }
4305 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_msr_common);
4306
get_msr_mce(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)4307 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
4308 {
4309 u64 data;
4310 u64 mcg_cap = vcpu->arch.mcg_cap;
4311 unsigned bank_num = mcg_cap & 0xff;
4312 u32 offset, last_msr;
4313
4314 switch (msr) {
4315 case MSR_IA32_P5_MC_ADDR:
4316 case MSR_IA32_P5_MC_TYPE:
4317 data = 0;
4318 break;
4319 case MSR_IA32_MCG_CAP:
4320 data = vcpu->arch.mcg_cap;
4321 break;
4322 case MSR_IA32_MCG_CTL:
4323 if (!(mcg_cap & MCG_CTL_P) && !host)
4324 return 1;
4325 data = vcpu->arch.mcg_ctl;
4326 break;
4327 case MSR_IA32_MCG_STATUS:
4328 data = vcpu->arch.mcg_status;
4329 break;
4330 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4331 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4332 if (msr > last_msr)
4333 return 1;
4334
4335 if (!(mcg_cap & MCG_CMCI_P) && !host)
4336 return 1;
4337 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4338 last_msr + 1 - MSR_IA32_MC0_CTL2);
4339 data = vcpu->arch.mci_ctl2_banks[offset];
4340 break;
4341 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4342 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4343 if (msr > last_msr)
4344 return 1;
4345
4346 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4347 last_msr + 1 - MSR_IA32_MC0_CTL);
4348 data = vcpu->arch.mce_banks[offset];
4349 break;
4350 default:
4351 return 1;
4352 }
4353 *pdata = data;
4354 return 0;
4355 }
4356
kvm_get_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4357 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4358 {
4359 switch (msr_info->index) {
4360 case MSR_IA32_PLATFORM_ID:
4361 case MSR_IA32_EBL_CR_POWERON:
4362 case MSR_IA32_LASTBRANCHFROMIP:
4363 case MSR_IA32_LASTBRANCHTOIP:
4364 case MSR_IA32_LASTINTFROMIP:
4365 case MSR_IA32_LASTINTTOIP:
4366 case MSR_AMD64_SYSCFG:
4367 case MSR_K8_TSEG_ADDR:
4368 case MSR_K8_TSEG_MASK:
4369 case MSR_VM_HSAVE_PA:
4370 case MSR_K8_INT_PENDING_MSG:
4371 case MSR_AMD64_NB_CFG:
4372 case MSR_FAM10H_MMIO_CONF_BASE:
4373 case MSR_AMD64_BU_CFG2:
4374 case MSR_IA32_PERF_CTL:
4375 case MSR_AMD64_DC_CFG:
4376 case MSR_AMD64_TW_CFG:
4377 case MSR_F15H_EX_CFG:
4378 /*
4379 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4380 * limit) MSRs. Just return 0, as we do not want to expose the host
4381 * data here. Do not conditionalize this on CPUID, as KVM does not do
4382 * so for existing CPU-specific MSRs.
4383 */
4384 case MSR_RAPL_POWER_UNIT:
4385 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
4386 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
4387 case MSR_PKG_ENERGY_STATUS: /* Total package */
4388 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
4389 msr_info->data = 0;
4390 break;
4391 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4392 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4393 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4394 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4395 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4396 return kvm_pmu_get_msr(vcpu, msr_info);
4397 msr_info->data = 0;
4398 break;
4399 case MSR_IA32_UCODE_REV:
4400 msr_info->data = vcpu->arch.microcode_version;
4401 break;
4402 case MSR_IA32_ARCH_CAPABILITIES:
4403 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4404 return KVM_MSR_RET_UNSUPPORTED;
4405 msr_info->data = vcpu->arch.arch_capabilities;
4406 break;
4407 case MSR_IA32_PERF_CAPABILITIES:
4408 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
4409 return KVM_MSR_RET_UNSUPPORTED;
4410 msr_info->data = vcpu->arch.perf_capabilities;
4411 break;
4412 case MSR_IA32_POWER_CTL:
4413 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4414 break;
4415 case MSR_IA32_TSC: {
4416 /*
4417 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4418 * even when not intercepted. AMD manual doesn't explicitly
4419 * state this but appears to behave the same.
4420 *
4421 * On userspace reads and writes, however, we unconditionally
4422 * return L1's TSC value to ensure backwards-compatible
4423 * behavior for migration.
4424 */
4425 u64 offset, ratio;
4426
4427 if (msr_info->host_initiated) {
4428 offset = vcpu->arch.l1_tsc_offset;
4429 ratio = vcpu->arch.l1_tsc_scaling_ratio;
4430 } else {
4431 offset = vcpu->arch.tsc_offset;
4432 ratio = vcpu->arch.tsc_scaling_ratio;
4433 }
4434
4435 msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4436 break;
4437 }
4438 case MSR_IA32_CR_PAT:
4439 msr_info->data = vcpu->arch.pat;
4440 break;
4441 case MSR_MTRRcap:
4442 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4443 case MSR_MTRRdefType:
4444 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4445 case 0xcd: /* fsb frequency */
4446 msr_info->data = 3;
4447 break;
4448 /*
4449 * MSR_EBC_FREQUENCY_ID
4450 * Conservative value valid for even the basic CPU models.
4451 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4452 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4453 * and 266MHz for model 3, or 4. Set Core Clock
4454 * Frequency to System Bus Frequency Ratio to 1 (bits
4455 * 31:24) even though these are only valid for CPU
4456 * models > 2, however guests may end up dividing or
4457 * multiplying by zero otherwise.
4458 */
4459 case MSR_EBC_FREQUENCY_ID:
4460 msr_info->data = 1 << 24;
4461 break;
4462 case MSR_IA32_APICBASE:
4463 msr_info->data = vcpu->arch.apic_base;
4464 break;
4465 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4466 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4467 case MSR_IA32_TSC_DEADLINE:
4468 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4469 break;
4470 case MSR_IA32_TSC_ADJUST:
4471 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4472 break;
4473 case MSR_IA32_MISC_ENABLE:
4474 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4475 break;
4476 case MSR_IA32_SMBASE:
4477 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4478 return 1;
4479 msr_info->data = vcpu->arch.smbase;
4480 break;
4481 case MSR_SMI_COUNT:
4482 msr_info->data = vcpu->arch.smi_count;
4483 break;
4484 case MSR_IA32_PERF_STATUS:
4485 /* TSC increment by tick */
4486 msr_info->data = 1000ULL;
4487 /* CPU multiplier */
4488 msr_info->data |= (((uint64_t)4ULL) << 40);
4489 break;
4490 case MSR_EFER:
4491 msr_info->data = vcpu->arch.efer;
4492 break;
4493 case MSR_KVM_WALL_CLOCK:
4494 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4495 return KVM_MSR_RET_UNSUPPORTED;
4496
4497 msr_info->data = vcpu->kvm->arch.wall_clock;
4498 break;
4499 case MSR_KVM_WALL_CLOCK_NEW:
4500 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4501 return KVM_MSR_RET_UNSUPPORTED;
4502
4503 msr_info->data = vcpu->kvm->arch.wall_clock;
4504 break;
4505 case MSR_KVM_SYSTEM_TIME:
4506 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4507 return KVM_MSR_RET_UNSUPPORTED;
4508
4509 msr_info->data = vcpu->arch.time;
4510 break;
4511 case MSR_KVM_SYSTEM_TIME_NEW:
4512 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4513 return KVM_MSR_RET_UNSUPPORTED;
4514
4515 msr_info->data = vcpu->arch.time;
4516 break;
4517 case MSR_KVM_ASYNC_PF_EN:
4518 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4519 return KVM_MSR_RET_UNSUPPORTED;
4520
4521 msr_info->data = vcpu->arch.apf.msr_en_val;
4522 break;
4523 case MSR_KVM_ASYNC_PF_INT:
4524 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4525 return KVM_MSR_RET_UNSUPPORTED;
4526
4527 msr_info->data = vcpu->arch.apf.msr_int_val;
4528 break;
4529 case MSR_KVM_ASYNC_PF_ACK:
4530 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4531 return KVM_MSR_RET_UNSUPPORTED;
4532
4533 msr_info->data = 0;
4534 break;
4535 case MSR_KVM_STEAL_TIME:
4536 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4537 return KVM_MSR_RET_UNSUPPORTED;
4538
4539 msr_info->data = vcpu->arch.st.msr_val;
4540 break;
4541 case MSR_KVM_PV_EOI_EN:
4542 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4543 return KVM_MSR_RET_UNSUPPORTED;
4544
4545 msr_info->data = vcpu->arch.pv_eoi.msr_val;
4546 break;
4547 case MSR_KVM_POLL_CONTROL:
4548 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4549 return KVM_MSR_RET_UNSUPPORTED;
4550
4551 msr_info->data = vcpu->arch.msr_kvm_poll_control;
4552 break;
4553 case MSR_IA32_P5_MC_ADDR:
4554 case MSR_IA32_P5_MC_TYPE:
4555 case MSR_IA32_MCG_CAP:
4556 case MSR_IA32_MCG_CTL:
4557 case MSR_IA32_MCG_STATUS:
4558 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4559 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4560 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4561 msr_info->host_initiated);
4562 case MSR_IA32_XSS:
4563 if (!msr_info->host_initiated &&
4564 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4565 return 1;
4566 msr_info->data = vcpu->arch.ia32_xss;
4567 break;
4568 case MSR_K7_CLK_CTL:
4569 /*
4570 * Provide expected ramp-up count for K7. All other
4571 * are set to zero, indicating minimum divisors for
4572 * every field.
4573 *
4574 * This prevents guest kernels on AMD host with CPU
4575 * type 6, model 8 and higher from exploding due to
4576 * the rdmsr failing.
4577 */
4578 msr_info->data = 0x20000000;
4579 break;
4580 #ifdef CONFIG_KVM_HYPERV
4581 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4582 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4583 case HV_X64_MSR_SYNDBG_OPTIONS:
4584 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4585 case HV_X64_MSR_CRASH_CTL:
4586 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4587 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4588 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4589 case HV_X64_MSR_TSC_EMULATION_STATUS:
4590 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4591 return kvm_hv_get_msr_common(vcpu,
4592 msr_info->index, &msr_info->data,
4593 msr_info->host_initiated);
4594 #endif
4595 case MSR_IA32_BBL_CR_CTL3:
4596 /* This legacy MSR exists but isn't fully documented in current
4597 * silicon. It is however accessed by winxp in very narrow
4598 * scenarios where it sets bit #19, itself documented as
4599 * a "reserved" bit. Best effort attempt to source coherent
4600 * read data here should the balance of the register be
4601 * interpreted by the guest:
4602 *
4603 * L2 cache control register 3: 64GB range, 256KB size,
4604 * enabled, latency 0x1, configured
4605 */
4606 msr_info->data = 0xbe702111;
4607 break;
4608 case MSR_AMD64_OSVW_ID_LENGTH:
4609 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4610 return 1;
4611 msr_info->data = vcpu->arch.osvw.length;
4612 break;
4613 case MSR_AMD64_OSVW_STATUS:
4614 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4615 return 1;
4616 msr_info->data = vcpu->arch.osvw.status;
4617 break;
4618 case MSR_PLATFORM_INFO:
4619 if (!msr_info->host_initiated &&
4620 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4621 return 1;
4622 msr_info->data = vcpu->arch.msr_platform_info;
4623 break;
4624 case MSR_MISC_FEATURES_ENABLES:
4625 msr_info->data = vcpu->arch.msr_misc_features_enables;
4626 break;
4627 case MSR_K7_HWCR:
4628 msr_info->data = vcpu->arch.msr_hwcr;
4629 break;
4630 #ifdef CONFIG_X86_64
4631 case MSR_IA32_XFD:
4632 if (!msr_info->host_initiated &&
4633 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4634 return 1;
4635
4636 msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4637 break;
4638 case MSR_IA32_XFD_ERR:
4639 if (!msr_info->host_initiated &&
4640 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4641 return 1;
4642
4643 msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4644 break;
4645 #endif
4646 case MSR_IA32_U_CET:
4647 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
4648 kvm_get_xstate_msr(vcpu, msr_info);
4649 break;
4650 default:
4651 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4652 return kvm_pmu_get_msr(vcpu, msr_info);
4653
4654 return KVM_MSR_RET_UNSUPPORTED;
4655 }
4656 return 0;
4657 }
4658 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_msr_common);
4659
4660 /*
4661 * Read or write a bunch of msrs. All parameters are kernel addresses.
4662 *
4663 * @return number of msrs set successfully.
4664 */
__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))4665 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4666 struct kvm_msr_entry *entries,
4667 int (*do_msr)(struct kvm_vcpu *vcpu,
4668 unsigned index, u64 *data))
4669 {
4670 bool fpu_loaded = false;
4671 int i;
4672
4673 for (i = 0; i < msrs->nmsrs; ++i) {
4674 /*
4675 * If userspace is accessing one or more XSTATE-managed MSRs,
4676 * temporarily load the guest's FPU state so that the guest's
4677 * MSR value(s) is resident in hardware and thus can be accessed
4678 * via RDMSR/WRMSR.
4679 */
4680 if (!fpu_loaded && is_xstate_managed_msr(vcpu, entries[i].index)) {
4681 kvm_load_guest_fpu(vcpu);
4682 fpu_loaded = true;
4683 }
4684 if (do_msr(vcpu, entries[i].index, &entries[i].data))
4685 break;
4686 }
4687 if (fpu_loaded)
4688 kvm_put_guest_fpu(vcpu);
4689
4690 return i;
4691 }
4692
4693 /*
4694 * Read or write a bunch of msrs. Parameters are user addresses.
4695 *
4696 * @return number of msrs set successfully.
4697 */
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)4698 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4699 int (*do_msr)(struct kvm_vcpu *vcpu,
4700 unsigned index, u64 *data),
4701 int writeback)
4702 {
4703 struct kvm_msrs msrs;
4704 struct kvm_msr_entry *entries;
4705 unsigned size;
4706 int r;
4707
4708 r = -EFAULT;
4709 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4710 goto out;
4711
4712 r = -E2BIG;
4713 if (msrs.nmsrs >= MAX_IO_MSRS)
4714 goto out;
4715
4716 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4717 entries = memdup_user(user_msrs->entries, size);
4718 if (IS_ERR(entries)) {
4719 r = PTR_ERR(entries);
4720 goto out;
4721 }
4722
4723 r = __msr_io(vcpu, &msrs, entries, do_msr);
4724
4725 if (writeback && copy_to_user(user_msrs->entries, entries, size))
4726 r = -EFAULT;
4727
4728 kfree(entries);
4729 out:
4730 return r;
4731 }
4732
kvm_can_mwait_in_guest(void)4733 static inline bool kvm_can_mwait_in_guest(void)
4734 {
4735 return boot_cpu_has(X86_FEATURE_MWAIT) &&
4736 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
4737 boot_cpu_has(X86_FEATURE_ARAT);
4738 }
4739
kvm_get_allowed_disable_exits(void)4740 static u64 kvm_get_allowed_disable_exits(void)
4741 {
4742 u64 r = KVM_X86_DISABLE_EXITS_PAUSE;
4743
4744 if (boot_cpu_has(X86_FEATURE_APERFMPERF))
4745 r |= KVM_X86_DISABLE_EXITS_APERFMPERF;
4746
4747 if (!mitigate_smt_rsb) {
4748 r |= KVM_X86_DISABLE_EXITS_HLT |
4749 KVM_X86_DISABLE_EXITS_CSTATE;
4750
4751 if (kvm_can_mwait_in_guest())
4752 r |= KVM_X86_DISABLE_EXITS_MWAIT;
4753 }
4754 return r;
4755 }
4756
4757 #ifdef CONFIG_KVM_HYPERV
kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 __user * cpuid_arg)4758 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4759 struct kvm_cpuid2 __user *cpuid_arg)
4760 {
4761 struct kvm_cpuid2 cpuid;
4762 int r;
4763
4764 r = -EFAULT;
4765 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4766 return r;
4767
4768 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4769 if (r)
4770 return r;
4771
4772 r = -EFAULT;
4773 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4774 return r;
4775
4776 return 0;
4777 }
4778 #endif
4779
kvm_is_vm_type_supported(unsigned long type)4780 static bool kvm_is_vm_type_supported(unsigned long type)
4781 {
4782 return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
4783 }
4784
kvm_sync_valid_fields(struct kvm * kvm)4785 static inline u64 kvm_sync_valid_fields(struct kvm *kvm)
4786 {
4787 return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
4788 }
4789
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)4790 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4791 {
4792 int r = 0;
4793
4794 switch (ext) {
4795 case KVM_CAP_IRQCHIP:
4796 case KVM_CAP_HLT:
4797 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4798 case KVM_CAP_SET_TSS_ADDR:
4799 case KVM_CAP_EXT_CPUID:
4800 case KVM_CAP_EXT_EMUL_CPUID:
4801 case KVM_CAP_CLOCKSOURCE:
4802 #ifdef CONFIG_KVM_IOAPIC
4803 case KVM_CAP_PIT:
4804 case KVM_CAP_PIT2:
4805 case KVM_CAP_PIT_STATE2:
4806 case KVM_CAP_REINJECT_CONTROL:
4807 #endif
4808 case KVM_CAP_NOP_IO_DELAY:
4809 case KVM_CAP_MP_STATE:
4810 case KVM_CAP_USER_NMI:
4811 case KVM_CAP_IRQ_INJECT_STATUS:
4812 case KVM_CAP_IOEVENTFD:
4813 case KVM_CAP_IOEVENTFD_NO_LENGTH:
4814
4815 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4816 case KVM_CAP_VCPU_EVENTS:
4817 #ifdef CONFIG_KVM_HYPERV
4818 case KVM_CAP_HYPERV:
4819 case KVM_CAP_HYPERV_VAPIC:
4820 case KVM_CAP_HYPERV_SPIN:
4821 case KVM_CAP_HYPERV_TIME:
4822 case KVM_CAP_HYPERV_SYNIC:
4823 case KVM_CAP_HYPERV_SYNIC2:
4824 case KVM_CAP_HYPERV_VP_INDEX:
4825 case KVM_CAP_HYPERV_EVENTFD:
4826 case KVM_CAP_HYPERV_TLBFLUSH:
4827 case KVM_CAP_HYPERV_SEND_IPI:
4828 case KVM_CAP_HYPERV_CPUID:
4829 case KVM_CAP_HYPERV_ENFORCE_CPUID:
4830 case KVM_CAP_SYS_HYPERV_CPUID:
4831 #endif
4832 case KVM_CAP_PCI_SEGMENT:
4833 case KVM_CAP_DEBUGREGS:
4834 case KVM_CAP_X86_ROBUST_SINGLESTEP:
4835 case KVM_CAP_XSAVE:
4836 case KVM_CAP_ASYNC_PF:
4837 case KVM_CAP_ASYNC_PF_INT:
4838 case KVM_CAP_GET_TSC_KHZ:
4839 case KVM_CAP_KVMCLOCK_CTRL:
4840 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4841 case KVM_CAP_TSC_DEADLINE_TIMER:
4842 case KVM_CAP_DISABLE_QUIRKS:
4843 case KVM_CAP_SET_BOOT_CPU_ID:
4844 case KVM_CAP_SPLIT_IRQCHIP:
4845 case KVM_CAP_IMMEDIATE_EXIT:
4846 case KVM_CAP_PMU_EVENT_FILTER:
4847 case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
4848 case KVM_CAP_GET_MSR_FEATURES:
4849 case KVM_CAP_MSR_PLATFORM_INFO:
4850 case KVM_CAP_EXCEPTION_PAYLOAD:
4851 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4852 case KVM_CAP_SET_GUEST_DEBUG:
4853 case KVM_CAP_LAST_CPU:
4854 case KVM_CAP_X86_USER_SPACE_MSR:
4855 case KVM_CAP_X86_MSR_FILTER:
4856 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4857 #ifdef CONFIG_X86_SGX_KVM
4858 case KVM_CAP_SGX_ATTRIBUTE:
4859 #endif
4860 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4861 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4862 case KVM_CAP_SREGS2:
4863 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4864 case KVM_CAP_VCPU_ATTRIBUTES:
4865 case KVM_CAP_SYS_ATTRIBUTES:
4866 case KVM_CAP_VAPIC:
4867 case KVM_CAP_ENABLE_CAP:
4868 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4869 case KVM_CAP_IRQFD_RESAMPLE:
4870 case KVM_CAP_MEMORY_FAULT_INFO:
4871 case KVM_CAP_X86_GUEST_MODE:
4872 case KVM_CAP_ONE_REG:
4873 r = 1;
4874 break;
4875 case KVM_CAP_PRE_FAULT_MEMORY:
4876 r = tdp_enabled;
4877 break;
4878 case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
4879 r = kvm ? kvm->arch.apic_bus_cycle_ns : APIC_BUS_CYCLE_NS_DEFAULT;
4880 break;
4881 case KVM_CAP_EXIT_HYPERCALL:
4882 r = KVM_EXIT_HYPERCALL_VALID_MASK;
4883 break;
4884 case KVM_CAP_SET_GUEST_DEBUG2:
4885 return KVM_GUESTDBG_VALID_MASK;
4886 #ifdef CONFIG_KVM_XEN
4887 case KVM_CAP_XEN_HVM:
4888 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4889 KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4890 KVM_XEN_HVM_CONFIG_SHARED_INFO |
4891 KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4892 KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
4893 KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4894 KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
4895 if (sched_info_on())
4896 r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4897 KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
4898 break;
4899 #endif
4900 case KVM_CAP_SYNC_REGS:
4901 r = kvm_sync_valid_fields(kvm);
4902 break;
4903 case KVM_CAP_ADJUST_CLOCK:
4904 r = KVM_CLOCK_VALID_FLAGS;
4905 break;
4906 case KVM_CAP_X86_DISABLE_EXITS:
4907 r = kvm_get_allowed_disable_exits();
4908 break;
4909 case KVM_CAP_X86_SMM:
4910 if (!IS_ENABLED(CONFIG_KVM_SMM))
4911 break;
4912
4913 /* SMBASE is usually relocated above 1M on modern chipsets,
4914 * and SMM handlers might indeed rely on 4G segment limits,
4915 * so do not report SMM to be available if real mode is
4916 * emulated via vm86 mode. Still, do not go to great lengths
4917 * to avoid userspace's usage of the feature, because it is a
4918 * fringe case that is not enabled except via specific settings
4919 * of the module parameters.
4920 */
4921 r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4922 break;
4923 case KVM_CAP_NR_VCPUS:
4924 r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4925 break;
4926 case KVM_CAP_MAX_VCPUS:
4927 r = KVM_MAX_VCPUS;
4928 if (kvm)
4929 r = kvm->max_vcpus;
4930 break;
4931 case KVM_CAP_MAX_VCPU_ID:
4932 r = KVM_MAX_VCPU_IDS;
4933 break;
4934 case KVM_CAP_PV_MMU: /* obsolete */
4935 r = 0;
4936 break;
4937 case KVM_CAP_MCE:
4938 r = KVM_MAX_MCE_BANKS;
4939 break;
4940 case KVM_CAP_XCRS:
4941 r = boot_cpu_has(X86_FEATURE_XSAVE);
4942 break;
4943 case KVM_CAP_TSC_CONTROL:
4944 case KVM_CAP_VM_TSC_CONTROL:
4945 r = kvm_caps.has_tsc_control;
4946 break;
4947 case KVM_CAP_X2APIC_API:
4948 r = KVM_X2APIC_API_VALID_FLAGS;
4949 if (kvm && !irqchip_split(kvm))
4950 r &= ~KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST;
4951 break;
4952 case KVM_CAP_NESTED_STATE:
4953 r = kvm_x86_ops.nested_ops->get_state ?
4954 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4955 break;
4956 #ifdef CONFIG_KVM_HYPERV
4957 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4958 r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
4959 break;
4960 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4961 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4962 break;
4963 #endif
4964 case KVM_CAP_SMALLER_MAXPHYADDR:
4965 r = (int) allow_smaller_maxphyaddr;
4966 break;
4967 case KVM_CAP_STEAL_TIME:
4968 r = sched_info_on();
4969 break;
4970 case KVM_CAP_X86_BUS_LOCK_EXIT:
4971 if (kvm_caps.has_bus_lock_exit)
4972 r = KVM_BUS_LOCK_DETECTION_OFF |
4973 KVM_BUS_LOCK_DETECTION_EXIT;
4974 else
4975 r = 0;
4976 break;
4977 case KVM_CAP_XSAVE2: {
4978 r = xstate_required_size(kvm_get_filtered_xcr0(), false);
4979 if (r < sizeof(struct kvm_xsave))
4980 r = sizeof(struct kvm_xsave);
4981 break;
4982 }
4983 case KVM_CAP_PMU_CAPABILITY:
4984 r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4985 break;
4986 case KVM_CAP_DISABLE_QUIRKS2:
4987 r = kvm_caps.supported_quirks;
4988 break;
4989 case KVM_CAP_X86_NOTIFY_VMEXIT:
4990 r = kvm_caps.has_notify_vmexit;
4991 break;
4992 case KVM_CAP_VM_TYPES:
4993 r = kvm_caps.supported_vm_types;
4994 break;
4995 case KVM_CAP_READONLY_MEM:
4996 r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
4997 break;
4998 default:
4999 break;
5000 }
5001 return r;
5002 }
5003
__kvm_x86_dev_get_attr(struct kvm_device_attr * attr,u64 * val)5004 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
5005 {
5006 if (attr->group) {
5007 if (kvm_x86_ops.dev_get_attr)
5008 return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
5009 return -ENXIO;
5010 }
5011
5012 switch (attr->attr) {
5013 case KVM_X86_XCOMP_GUEST_SUPP:
5014 *val = kvm_caps.supported_xcr0;
5015 return 0;
5016 default:
5017 return -ENXIO;
5018 }
5019 }
5020
kvm_x86_dev_get_attr(struct kvm_device_attr * attr)5021 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
5022 {
5023 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5024 int r;
5025 u64 val;
5026
5027 r = __kvm_x86_dev_get_attr(attr, &val);
5028 if (r < 0)
5029 return r;
5030
5031 if (put_user(val, uaddr))
5032 return -EFAULT;
5033
5034 return 0;
5035 }
5036
kvm_x86_dev_has_attr(struct kvm_device_attr * attr)5037 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
5038 {
5039 u64 val;
5040
5041 return __kvm_x86_dev_get_attr(attr, &val);
5042 }
5043
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5044 long kvm_arch_dev_ioctl(struct file *filp,
5045 unsigned int ioctl, unsigned long arg)
5046 {
5047 void __user *argp = (void __user *)arg;
5048 long r;
5049
5050 switch (ioctl) {
5051 case KVM_GET_MSR_INDEX_LIST: {
5052 struct kvm_msr_list __user *user_msr_list = argp;
5053 struct kvm_msr_list msr_list;
5054 unsigned n;
5055
5056 r = -EFAULT;
5057 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
5058 goto out;
5059 n = msr_list.nmsrs;
5060 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
5061 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
5062 goto out;
5063 r = -E2BIG;
5064 if (n < msr_list.nmsrs)
5065 goto out;
5066 r = -EFAULT;
5067 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
5068 num_msrs_to_save * sizeof(u32)))
5069 goto out;
5070 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
5071 &emulated_msrs,
5072 num_emulated_msrs * sizeof(u32)))
5073 goto out;
5074 r = 0;
5075 break;
5076 }
5077 case KVM_GET_SUPPORTED_CPUID:
5078 case KVM_GET_EMULATED_CPUID: {
5079 struct kvm_cpuid2 __user *cpuid_arg = argp;
5080 struct kvm_cpuid2 cpuid;
5081
5082 r = -EFAULT;
5083 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5084 goto out;
5085
5086 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
5087 ioctl);
5088 if (r)
5089 goto out;
5090
5091 r = -EFAULT;
5092 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5093 goto out;
5094 r = 0;
5095 break;
5096 }
5097 case KVM_X86_GET_MCE_CAP_SUPPORTED:
5098 r = -EFAULT;
5099 if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
5100 sizeof(kvm_caps.supported_mce_cap)))
5101 goto out;
5102 r = 0;
5103 break;
5104 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
5105 struct kvm_msr_list __user *user_msr_list = argp;
5106 struct kvm_msr_list msr_list;
5107 unsigned int n;
5108
5109 r = -EFAULT;
5110 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
5111 goto out;
5112 n = msr_list.nmsrs;
5113 msr_list.nmsrs = num_msr_based_features;
5114 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
5115 goto out;
5116 r = -E2BIG;
5117 if (n < msr_list.nmsrs)
5118 goto out;
5119 r = -EFAULT;
5120 if (copy_to_user(user_msr_list->indices, &msr_based_features,
5121 num_msr_based_features * sizeof(u32)))
5122 goto out;
5123 r = 0;
5124 break;
5125 }
5126 case KVM_GET_MSRS:
5127 r = msr_io(NULL, argp, do_get_feature_msr, 1);
5128 break;
5129 #ifdef CONFIG_KVM_HYPERV
5130 case KVM_GET_SUPPORTED_HV_CPUID:
5131 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
5132 break;
5133 #endif
5134 case KVM_GET_DEVICE_ATTR: {
5135 struct kvm_device_attr attr;
5136 r = -EFAULT;
5137 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
5138 break;
5139 r = kvm_x86_dev_get_attr(&attr);
5140 break;
5141 }
5142 case KVM_HAS_DEVICE_ATTR: {
5143 struct kvm_device_attr attr;
5144 r = -EFAULT;
5145 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
5146 break;
5147 r = kvm_x86_dev_has_attr(&attr);
5148 break;
5149 }
5150 default:
5151 r = -EINVAL;
5152 break;
5153 }
5154 out:
5155 return r;
5156 }
5157
need_emulate_wbinvd(struct kvm_vcpu * vcpu)5158 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
5159 {
5160 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
5161 }
5162
5163 static DEFINE_PER_CPU(struct kvm_vcpu *, last_vcpu);
5164
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)5165 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
5166 {
5167 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
5168
5169 kvm_request_l1tf_flush_l1d();
5170
5171 if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
5172 pmu->need_cleanup = true;
5173 kvm_make_request(KVM_REQ_PMU, vcpu);
5174 }
5175
5176 /* Address WBINVD may be executed by guest */
5177 if (need_emulate_wbinvd(vcpu)) {
5178 if (kvm_x86_call(has_wbinvd_exit)())
5179 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5180 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
5181 wbinvd_on_cpu(vcpu->cpu);
5182 }
5183
5184 kvm_x86_call(vcpu_load)(vcpu, cpu);
5185
5186 if (vcpu != per_cpu(last_vcpu, cpu)) {
5187 /*
5188 * Flush the branch predictor when switching vCPUs on the same
5189 * physical CPU, as each vCPU needs its own branch prediction
5190 * domain. No IBPB is needed when switching between L1 and L2
5191 * on the same vCPU unless IBRS is advertised to the vCPU; that
5192 * is handled on the nested VM-Exit path.
5193 */
5194 if (static_branch_likely(&switch_vcpu_ibpb))
5195 indirect_branch_prediction_barrier();
5196 per_cpu(last_vcpu, cpu) = vcpu;
5197 }
5198
5199 /* Save host pkru register if supported */
5200 vcpu->arch.host_pkru = read_pkru();
5201
5202 /* Apply any externally detected TSC adjustments (due to suspend) */
5203 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5204 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5205 vcpu->arch.tsc_offset_adjustment = 0;
5206 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5207 }
5208
5209 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
5210 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
5211 rdtsc() - vcpu->arch.last_host_tsc;
5212 if (tsc_delta < 0)
5213 mark_tsc_unstable("KVM discovered backwards TSC");
5214
5215 if (kvm_check_tsc_unstable()) {
5216 u64 offset = kvm_compute_l1_tsc_offset(vcpu,
5217 vcpu->arch.last_guest_tsc);
5218 kvm_vcpu_write_tsc_offset(vcpu, offset);
5219 if (!vcpu->arch.guest_tsc_protected)
5220 vcpu->arch.tsc_catchup = 1;
5221 }
5222
5223 if (kvm_lapic_hv_timer_in_use(vcpu))
5224 kvm_lapic_restart_hv_timer(vcpu);
5225
5226 /*
5227 * On a host with synchronized TSC, there is no need to update
5228 * kvmclock on vcpu->cpu migration
5229 */
5230 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1) {
5231 if (__ratelimit(&vcpu->kvm->arch.kvmclock_update_rs))
5232 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
5233 else
5234 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5235 }
5236
5237 if (vcpu->cpu != cpu)
5238 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
5239 vcpu->cpu = cpu;
5240 }
5241
5242 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
5243 }
5244
kvm_steal_time_set_preempted(struct kvm_vcpu * vcpu)5245 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
5246 {
5247 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
5248 struct kvm_steal_time __user *st;
5249 struct kvm_memslots *slots;
5250 static const u8 preempted = KVM_VCPU_PREEMPTED;
5251 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
5252
5253 /*
5254 * The vCPU can be marked preempted if and only if the VM-Exit was on
5255 * an instruction boundary and will not trigger guest emulation of any
5256 * kind (see vcpu_run). Vendor specific code controls (conservatively)
5257 * when this is true, for example allowing the vCPU to be marked
5258 * preempted if and only if the VM-Exit was due to a host interrupt.
5259 */
5260 if (!vcpu->arch.at_instruction_boundary) {
5261 vcpu->stat.preemption_other++;
5262 return;
5263 }
5264
5265 vcpu->stat.preemption_reported++;
5266 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
5267 return;
5268
5269 if (vcpu->arch.st.preempted)
5270 return;
5271
5272 /* This happens on process exit */
5273 if (unlikely(current->mm != vcpu->kvm->mm))
5274 return;
5275
5276 slots = kvm_memslots(vcpu->kvm);
5277
5278 if (unlikely(slots->generation != ghc->generation ||
5279 gpa != ghc->gpa ||
5280 kvm_is_error_hva(ghc->hva) || !ghc->memslot))
5281 return;
5282
5283 st = (struct kvm_steal_time __user *)ghc->hva;
5284 BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
5285
5286 if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
5287 vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
5288
5289 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
5290 }
5291
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)5292 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
5293 {
5294 int idx;
5295
5296 if (vcpu->preempted) {
5297 /*
5298 * Assume protected guests are in-kernel. Inefficient yielding
5299 * due to false positives is preferable to never yielding due
5300 * to false negatives.
5301 */
5302 vcpu->arch.preempted_in_kernel = vcpu->arch.guest_state_protected ||
5303 !kvm_x86_call(get_cpl_no_cache)(vcpu);
5304
5305 /*
5306 * Take the srcu lock as memslots will be accessed to check the gfn
5307 * cache generation against the memslots generation.
5308 */
5309 idx = srcu_read_lock(&vcpu->kvm->srcu);
5310 if (kvm_xen_msr_enabled(vcpu->kvm))
5311 kvm_xen_runstate_set_preempted(vcpu);
5312 else
5313 kvm_steal_time_set_preempted(vcpu);
5314 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5315 }
5316
5317 kvm_x86_call(vcpu_put)(vcpu);
5318 vcpu->arch.last_host_tsc = rdtsc();
5319 }
5320
kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5321 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5322 struct kvm_lapic_state *s)
5323 {
5324 if (vcpu->arch.apic->guest_apic_protected)
5325 return -EINVAL;
5326
5327 kvm_x86_call(sync_pir_to_irr)(vcpu);
5328
5329 return kvm_apic_get_state(vcpu, s);
5330 }
5331
kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5332 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5333 struct kvm_lapic_state *s)
5334 {
5335 int r;
5336
5337 if (vcpu->arch.apic->guest_apic_protected)
5338 return -EINVAL;
5339
5340 r = kvm_apic_set_state(vcpu, s);
5341 if (r)
5342 return r;
5343 update_cr8_intercept(vcpu);
5344
5345 return 0;
5346 }
5347
kvm_cpu_accept_dm_intr(struct kvm_vcpu * vcpu)5348 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5349 {
5350 /*
5351 * We can accept userspace's request for interrupt injection
5352 * as long as we have a place to store the interrupt number.
5353 * The actual injection will happen when the CPU is able to
5354 * deliver the interrupt.
5355 */
5356 if (kvm_cpu_has_extint(vcpu))
5357 return false;
5358
5359 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
5360 return (!lapic_in_kernel(vcpu) ||
5361 kvm_apic_accept_pic_intr(vcpu));
5362 }
5363
kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu * vcpu)5364 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5365 {
5366 /*
5367 * Do not cause an interrupt window exit if an exception
5368 * is pending or an event needs reinjection; userspace
5369 * might want to inject the interrupt manually using KVM_SET_REGS
5370 * or KVM_SET_SREGS. For that to work, we must be at an
5371 * instruction boundary and with no events half-injected.
5372 */
5373 return (kvm_arch_interrupt_allowed(vcpu) &&
5374 kvm_cpu_accept_dm_intr(vcpu) &&
5375 !kvm_event_needs_reinjection(vcpu) &&
5376 !kvm_is_exception_pending(vcpu));
5377 }
5378
kvm_vcpu_ioctl_interrupt(struct kvm_vcpu * vcpu,struct kvm_interrupt * irq)5379 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5380 struct kvm_interrupt *irq)
5381 {
5382 if (irq->irq >= KVM_NR_INTERRUPTS)
5383 return -EINVAL;
5384
5385 if (!irqchip_in_kernel(vcpu->kvm)) {
5386 kvm_queue_interrupt(vcpu, irq->irq, false);
5387 kvm_make_request(KVM_REQ_EVENT, vcpu);
5388 return 0;
5389 }
5390
5391 /*
5392 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5393 * fail for in-kernel 8259.
5394 */
5395 if (pic_in_kernel(vcpu->kvm))
5396 return -ENXIO;
5397
5398 if (vcpu->arch.pending_external_vector != -1)
5399 return -EEXIST;
5400
5401 vcpu->arch.pending_external_vector = irq->irq;
5402 kvm_make_request(KVM_REQ_EVENT, vcpu);
5403 return 0;
5404 }
5405
kvm_vcpu_ioctl_nmi(struct kvm_vcpu * vcpu)5406 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5407 {
5408 kvm_inject_nmi(vcpu);
5409
5410 return 0;
5411 }
5412
vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu * vcpu,struct kvm_tpr_access_ctl * tac)5413 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5414 struct kvm_tpr_access_ctl *tac)
5415 {
5416 if (tac->flags)
5417 return -EINVAL;
5418 vcpu->arch.tpr_access_reporting = !!tac->enabled;
5419 return 0;
5420 }
5421
kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu * vcpu,u64 mcg_cap)5422 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5423 u64 mcg_cap)
5424 {
5425 int r;
5426 unsigned bank_num = mcg_cap & 0xff, bank;
5427
5428 r = -EINVAL;
5429 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
5430 goto out;
5431 if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
5432 goto out;
5433 r = 0;
5434 vcpu->arch.mcg_cap = mcg_cap;
5435 /* Init IA32_MCG_CTL to all 1s */
5436 if (mcg_cap & MCG_CTL_P)
5437 vcpu->arch.mcg_ctl = ~(u64)0;
5438 /* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5439 for (bank = 0; bank < bank_num; bank++) {
5440 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
5441 if (mcg_cap & MCG_CMCI_P)
5442 vcpu->arch.mci_ctl2_banks[bank] = 0;
5443 }
5444
5445 kvm_apic_after_set_mcg_cap(vcpu);
5446
5447 kvm_x86_call(setup_mce)(vcpu);
5448 out:
5449 return r;
5450 }
5451
5452 /*
5453 * Validate this is an UCNA (uncorrectable no action) error by checking the
5454 * MCG_STATUS and MCi_STATUS registers:
5455 * - none of the bits for Machine Check Exceptions are set
5456 * - both the VAL (valid) and UC (uncorrectable) bits are set
5457 * MCI_STATUS_PCC - Processor Context Corrupted
5458 * MCI_STATUS_S - Signaled as a Machine Check Exception
5459 * MCI_STATUS_AR - Software recoverable Action Required
5460 */
is_ucna(struct kvm_x86_mce * mce)5461 static bool is_ucna(struct kvm_x86_mce *mce)
5462 {
5463 return !mce->mcg_status &&
5464 !(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5465 (mce->status & MCI_STATUS_VAL) &&
5466 (mce->status & MCI_STATUS_UC);
5467 }
5468
kvm_vcpu_x86_set_ucna(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce,u64 * banks)5469 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5470 {
5471 u64 mcg_cap = vcpu->arch.mcg_cap;
5472
5473 banks[1] = mce->status;
5474 banks[2] = mce->addr;
5475 banks[3] = mce->misc;
5476 vcpu->arch.mcg_status = mce->mcg_status;
5477
5478 if (!(mcg_cap & MCG_CMCI_P) ||
5479 !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5480 return 0;
5481
5482 if (lapic_in_kernel(vcpu))
5483 kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5484
5485 return 0;
5486 }
5487
kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce)5488 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5489 struct kvm_x86_mce *mce)
5490 {
5491 u64 mcg_cap = vcpu->arch.mcg_cap;
5492 unsigned bank_num = mcg_cap & 0xff;
5493 u64 *banks = vcpu->arch.mce_banks;
5494
5495 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5496 return -EINVAL;
5497
5498 banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5499
5500 if (is_ucna(mce))
5501 return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5502
5503 /*
5504 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5505 * reporting is disabled
5506 */
5507 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5508 vcpu->arch.mcg_ctl != ~(u64)0)
5509 return 0;
5510 /*
5511 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5512 * reporting is disabled for the bank
5513 */
5514 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5515 return 0;
5516 if (mce->status & MCI_STATUS_UC) {
5517 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5518 !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
5519 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5520 return 0;
5521 }
5522 if (banks[1] & MCI_STATUS_VAL)
5523 mce->status |= MCI_STATUS_OVER;
5524 banks[2] = mce->addr;
5525 banks[3] = mce->misc;
5526 vcpu->arch.mcg_status = mce->mcg_status;
5527 banks[1] = mce->status;
5528 kvm_queue_exception(vcpu, MC_VECTOR);
5529 } else if (!(banks[1] & MCI_STATUS_VAL)
5530 || !(banks[1] & MCI_STATUS_UC)) {
5531 if (banks[1] & MCI_STATUS_VAL)
5532 mce->status |= MCI_STATUS_OVER;
5533 banks[2] = mce->addr;
5534 banks[3] = mce->misc;
5535 banks[1] = mce->status;
5536 } else
5537 banks[1] |= MCI_STATUS_OVER;
5538 return 0;
5539 }
5540
kvm_get_exception_to_save(struct kvm_vcpu * vcpu)5541 static struct kvm_queued_exception *kvm_get_exception_to_save(struct kvm_vcpu *vcpu)
5542 {
5543 /*
5544 * KVM's ABI only allows for one exception to be migrated. Luckily,
5545 * the only time there can be two queued exceptions is if there's a
5546 * non-exiting _injected_ exception, and a pending exiting exception.
5547 * In that case, ignore the VM-Exiting exception as it's an extension
5548 * of the injected exception.
5549 */
5550 if (vcpu->arch.exception_vmexit.pending &&
5551 !vcpu->arch.exception.pending &&
5552 !vcpu->arch.exception.injected)
5553 return &vcpu->arch.exception_vmexit;
5554
5555 return &vcpu->arch.exception;
5556 }
5557
kvm_handle_exception_payload_quirk(struct kvm_vcpu * vcpu)5558 static void kvm_handle_exception_payload_quirk(struct kvm_vcpu *vcpu)
5559 {
5560 struct kvm_queued_exception *ex = kvm_get_exception_to_save(vcpu);
5561
5562 /*
5563 * If KVM_CAP_EXCEPTION_PAYLOAD is disabled, then (prematurely) deliver
5564 * the pending exception payload when userspace saves *any* vCPU state
5565 * that interacts with exception payloads to avoid breaking userspace.
5566 *
5567 * Architecturally, KVM must not deliver an exception payload until the
5568 * exception is actually injected, e.g. to avoid losing pending #DB
5569 * information (which VMX tracks in the VMCS), and to avoid clobbering
5570 * state if the exception is never injected for whatever reason. But
5571 * if KVM_CAP_EXCEPTION_PAYLOAD isn't enabled, then userspace may or
5572 * may not propagate the payload across save+restore, and so KVM can't
5573 * safely defer delivery of the payload.
5574 */
5575 if (!vcpu->kvm->arch.exception_payload_enabled &&
5576 ex->pending && ex->has_payload)
5577 kvm_deliver_exception_payload(vcpu, ex);
5578 }
5579
kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5580 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5581 struct kvm_vcpu_events *events)
5582 {
5583 struct kvm_queued_exception *ex = kvm_get_exception_to_save(vcpu);
5584
5585 process_nmi(vcpu);
5586
5587 #ifdef CONFIG_KVM_SMM
5588 if (kvm_check_request(KVM_REQ_SMI, vcpu))
5589 process_smi(vcpu);
5590 #endif
5591
5592 kvm_handle_exception_payload_quirk(vcpu);
5593
5594 memset(events, 0, sizeof(*events));
5595
5596 /*
5597 * The API doesn't provide the instruction length for software
5598 * exceptions, so don't report them. As long as the guest RIP
5599 * isn't advanced, we should expect to encounter the exception
5600 * again.
5601 */
5602 if (!kvm_exception_is_soft(ex->vector)) {
5603 events->exception.injected = ex->injected;
5604 events->exception.pending = ex->pending;
5605 /*
5606 * For ABI compatibility, deliberately conflate
5607 * pending and injected exceptions when
5608 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5609 */
5610 if (!vcpu->kvm->arch.exception_payload_enabled)
5611 events->exception.injected |= ex->pending;
5612 }
5613 events->exception.nr = ex->vector;
5614 events->exception.has_error_code = ex->has_error_code;
5615 events->exception.error_code = ex->error_code;
5616 events->exception_has_payload = ex->has_payload;
5617 events->exception_payload = ex->payload;
5618
5619 events->interrupt.injected =
5620 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5621 events->interrupt.nr = vcpu->arch.interrupt.nr;
5622 events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
5623
5624 events->nmi.injected = vcpu->arch.nmi_injected;
5625 events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
5626 events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
5627
5628 /* events->sipi_vector is never valid when reporting to user space */
5629
5630 #ifdef CONFIG_KVM_SMM
5631 events->smi.smm = is_smm(vcpu);
5632 events->smi.pending = vcpu->arch.smi_pending;
5633 events->smi.smm_inside_nmi =
5634 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5635 #endif
5636 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5637
5638 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5639 | KVM_VCPUEVENT_VALID_SHADOW
5640 | KVM_VCPUEVENT_VALID_SMM);
5641 if (vcpu->kvm->arch.exception_payload_enabled)
5642 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5643 if (vcpu->kvm->arch.triple_fault_event) {
5644 events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5645 events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5646 }
5647 }
5648
kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5649 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5650 struct kvm_vcpu_events *events)
5651 {
5652 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5653 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5654 | KVM_VCPUEVENT_VALID_SHADOW
5655 | KVM_VCPUEVENT_VALID_SMM
5656 | KVM_VCPUEVENT_VALID_PAYLOAD
5657 | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5658 return -EINVAL;
5659
5660 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5661 if (!vcpu->kvm->arch.exception_payload_enabled)
5662 return -EINVAL;
5663 if (events->exception.pending)
5664 events->exception.injected = 0;
5665 else
5666 events->exception_has_payload = 0;
5667 } else {
5668 events->exception.pending = 0;
5669 events->exception_has_payload = 0;
5670 }
5671
5672 if ((events->exception.injected || events->exception.pending) &&
5673 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5674 return -EINVAL;
5675
5676 process_nmi(vcpu);
5677
5678 /*
5679 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5680 * morph the exception to a VM-Exit if appropriate. Do this only for
5681 * pending exceptions, already-injected exceptions are not subject to
5682 * intercpetion. Note, userspace that conflates pending and injected
5683 * is hosed, and will incorrectly convert an injected exception into a
5684 * pending exception, which in turn may cause a spurious VM-Exit.
5685 */
5686 vcpu->arch.exception_from_userspace = events->exception.pending;
5687
5688 vcpu->arch.exception_vmexit.pending = false;
5689
5690 vcpu->arch.exception.injected = events->exception.injected;
5691 vcpu->arch.exception.pending = events->exception.pending;
5692 vcpu->arch.exception.vector = events->exception.nr;
5693 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5694 vcpu->arch.exception.error_code = events->exception.error_code;
5695 vcpu->arch.exception.has_payload = events->exception_has_payload;
5696 vcpu->arch.exception.payload = events->exception_payload;
5697
5698 vcpu->arch.interrupt.injected = events->interrupt.injected;
5699 vcpu->arch.interrupt.nr = events->interrupt.nr;
5700 vcpu->arch.interrupt.soft = events->interrupt.soft;
5701 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5702 kvm_x86_call(set_interrupt_shadow)(vcpu,
5703 events->interrupt.shadow);
5704
5705 vcpu->arch.nmi_injected = events->nmi.injected;
5706 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
5707 vcpu->arch.nmi_pending = 0;
5708 atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
5709 if (events->nmi.pending)
5710 kvm_make_request(KVM_REQ_NMI, vcpu);
5711 }
5712 kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
5713
5714 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5715 lapic_in_kernel(vcpu))
5716 vcpu->arch.apic->sipi_vector = events->sipi_vector;
5717
5718 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5719 #ifdef CONFIG_KVM_SMM
5720 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5721 kvm_leave_nested(vcpu);
5722 kvm_smm_changed(vcpu, events->smi.smm);
5723 }
5724
5725 vcpu->arch.smi_pending = events->smi.pending;
5726
5727 if (events->smi.smm) {
5728 if (events->smi.smm_inside_nmi)
5729 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5730 else
5731 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5732 }
5733
5734 #else
5735 if (events->smi.smm || events->smi.pending ||
5736 events->smi.smm_inside_nmi)
5737 return -EINVAL;
5738 #endif
5739
5740 if (lapic_in_kernel(vcpu)) {
5741 if (events->smi.latched_init)
5742 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5743 else
5744 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5745 }
5746 }
5747
5748 if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5749 if (!vcpu->kvm->arch.triple_fault_event)
5750 return -EINVAL;
5751 if (events->triple_fault.pending)
5752 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5753 else
5754 kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5755 }
5756
5757 kvm_make_request(KVM_REQ_EVENT, vcpu);
5758
5759 return 0;
5760 }
5761
kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5762 static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5763 struct kvm_debugregs *dbgregs)
5764 {
5765 unsigned int i;
5766
5767 if (vcpu->kvm->arch.has_protected_state &&
5768 vcpu->arch.guest_state_protected)
5769 return -EINVAL;
5770
5771 kvm_handle_exception_payload_quirk(vcpu);
5772
5773 memset(dbgregs, 0, sizeof(*dbgregs));
5774
5775 BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5776 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5777 dbgregs->db[i] = vcpu->arch.db[i];
5778
5779 dbgregs->dr6 = vcpu->arch.dr6;
5780 dbgregs->dr7 = vcpu->arch.dr7;
5781 return 0;
5782 }
5783
kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5784 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5785 struct kvm_debugregs *dbgregs)
5786 {
5787 unsigned int i;
5788
5789 if (vcpu->kvm->arch.has_protected_state &&
5790 vcpu->arch.guest_state_protected)
5791 return -EINVAL;
5792
5793 if (dbgregs->flags)
5794 return -EINVAL;
5795
5796 if (!kvm_dr6_valid(dbgregs->dr6))
5797 return -EINVAL;
5798 if (!kvm_dr7_valid(dbgregs->dr7))
5799 return -EINVAL;
5800
5801 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5802 vcpu->arch.db[i] = dbgregs->db[i];
5803
5804 kvm_update_dr0123(vcpu);
5805 vcpu->arch.dr6 = dbgregs->dr6;
5806 vcpu->arch.dr7 = dbgregs->dr7;
5807 kvm_update_dr7(vcpu);
5808
5809 return 0;
5810 }
5811
5812
kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu * vcpu,u8 * state,unsigned int size)5813 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5814 u8 *state, unsigned int size)
5815 {
5816 /*
5817 * Only copy state for features that are enabled for the guest. The
5818 * state itself isn't problematic, but setting bits in the header for
5819 * features that are supported in *this* host but not exposed to the
5820 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5821 * compatible host without the features that are NOT exposed to the
5822 * guest.
5823 *
5824 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5825 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5826 * supported by the host.
5827 */
5828 u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5829 XFEATURE_MASK_FPSSE;
5830
5831 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5832 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5833
5834 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5835 supported_xcr0, vcpu->arch.pkru);
5836 return 0;
5837 }
5838
kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5839 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5840 struct kvm_xsave *guest_xsave)
5841 {
5842 return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5843 sizeof(guest_xsave->region));
5844 }
5845
kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5846 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5847 struct kvm_xsave *guest_xsave)
5848 {
5849 union fpregs_state *xstate = (union fpregs_state *)guest_xsave->region;
5850
5851 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5852 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5853
5854 /*
5855 * For backwards compatibility, do not expect disabled features to be in
5856 * their initial state. XSTATE_BV[i] must still be cleared whenever
5857 * XFD[i]=1, or XRSTOR would cause a #NM.
5858 */
5859 xstate->xsave.header.xfeatures &= ~vcpu->arch.guest_fpu.fpstate->xfd;
5860
5861 return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5862 guest_xsave->region,
5863 kvm_caps.supported_xcr0,
5864 &vcpu->arch.pkru);
5865 }
5866
kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5867 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5868 struct kvm_xcrs *guest_xcrs)
5869 {
5870 if (vcpu->kvm->arch.has_protected_state &&
5871 vcpu->arch.guest_state_protected)
5872 return -EINVAL;
5873
5874 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5875 guest_xcrs->nr_xcrs = 0;
5876 return 0;
5877 }
5878
5879 guest_xcrs->nr_xcrs = 1;
5880 guest_xcrs->flags = 0;
5881 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5882 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5883 return 0;
5884 }
5885
kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5886 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5887 struct kvm_xcrs *guest_xcrs)
5888 {
5889 int i, r = 0;
5890
5891 if (vcpu->kvm->arch.has_protected_state &&
5892 vcpu->arch.guest_state_protected)
5893 return -EINVAL;
5894
5895 if (!boot_cpu_has(X86_FEATURE_XSAVE))
5896 return -EINVAL;
5897
5898 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5899 return -EINVAL;
5900
5901 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5902 /* Only support XCR0 currently */
5903 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5904 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5905 guest_xcrs->xcrs[i].value);
5906 break;
5907 }
5908 if (r)
5909 r = -EINVAL;
5910 return r;
5911 }
5912
5913 /*
5914 * kvm_set_guest_paused() indicates to the guest kernel that it has been
5915 * stopped by the hypervisor. This function will be called from the host only.
5916 * EINVAL is returned when the host attempts to set the flag for a guest that
5917 * does not support pv clocks.
5918 */
kvm_set_guest_paused(struct kvm_vcpu * vcpu)5919 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5920 {
5921 if (!vcpu->arch.pv_time.active)
5922 return -EINVAL;
5923 vcpu->arch.pvclock_set_guest_stopped_request = true;
5924 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5925 return 0;
5926 }
5927
kvm_arch_tsc_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5928 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5929 struct kvm_device_attr *attr)
5930 {
5931 int r;
5932
5933 switch (attr->attr) {
5934 case KVM_VCPU_TSC_OFFSET:
5935 r = 0;
5936 break;
5937 default:
5938 r = -ENXIO;
5939 }
5940
5941 return r;
5942 }
5943
kvm_arch_tsc_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5944 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5945 struct kvm_device_attr *attr)
5946 {
5947 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5948 int r;
5949
5950 switch (attr->attr) {
5951 case KVM_VCPU_TSC_OFFSET:
5952 r = -EFAULT;
5953 if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5954 break;
5955 r = 0;
5956 break;
5957 default:
5958 r = -ENXIO;
5959 }
5960
5961 return r;
5962 }
5963
kvm_arch_tsc_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5964 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5965 struct kvm_device_attr *attr)
5966 {
5967 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5968 struct kvm *kvm = vcpu->kvm;
5969 int r;
5970
5971 switch (attr->attr) {
5972 case KVM_VCPU_TSC_OFFSET: {
5973 u64 offset, tsc, ns;
5974 unsigned long flags;
5975 bool matched;
5976
5977 r = -EFAULT;
5978 if (get_user(offset, uaddr))
5979 break;
5980
5981 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5982
5983 matched = (vcpu->arch.virtual_tsc_khz &&
5984 kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5985 kvm->arch.last_tsc_offset == offset);
5986
5987 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5988 ns = get_kvmclock_base_ns();
5989
5990 __kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched, true);
5991 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5992
5993 r = 0;
5994 break;
5995 }
5996 default:
5997 r = -ENXIO;
5998 }
5999
6000 return r;
6001 }
6002
kvm_vcpu_ioctl_device_attr(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)6003 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
6004 unsigned int ioctl,
6005 void __user *argp)
6006 {
6007 struct kvm_device_attr attr;
6008 int r;
6009
6010 if (copy_from_user(&attr, argp, sizeof(attr)))
6011 return -EFAULT;
6012
6013 if (attr.group != KVM_VCPU_TSC_CTRL)
6014 return -ENXIO;
6015
6016 switch (ioctl) {
6017 case KVM_HAS_DEVICE_ATTR:
6018 r = kvm_arch_tsc_has_attr(vcpu, &attr);
6019 break;
6020 case KVM_GET_DEVICE_ATTR:
6021 r = kvm_arch_tsc_get_attr(vcpu, &attr);
6022 break;
6023 case KVM_SET_DEVICE_ATTR:
6024 r = kvm_arch_tsc_set_attr(vcpu, &attr);
6025 break;
6026 }
6027
6028 return r;
6029 }
6030
kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu * vcpu,struct kvm_enable_cap * cap)6031 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
6032 struct kvm_enable_cap *cap)
6033 {
6034 if (cap->flags)
6035 return -EINVAL;
6036
6037 switch (cap->cap) {
6038 #ifdef CONFIG_KVM_HYPERV
6039 case KVM_CAP_HYPERV_SYNIC2:
6040 if (cap->args[0])
6041 return -EINVAL;
6042 fallthrough;
6043
6044 case KVM_CAP_HYPERV_SYNIC:
6045 if (!irqchip_in_kernel(vcpu->kvm))
6046 return -EINVAL;
6047 return kvm_hv_activate_synic(vcpu, cap->cap ==
6048 KVM_CAP_HYPERV_SYNIC2);
6049 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
6050 {
6051 int r;
6052 uint16_t vmcs_version;
6053 void __user *user_ptr;
6054
6055 if (!kvm_x86_ops.nested_ops->enable_evmcs)
6056 return -ENOTTY;
6057 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
6058 if (!r) {
6059 user_ptr = (void __user *)(uintptr_t)cap->args[0];
6060 if (copy_to_user(user_ptr, &vmcs_version,
6061 sizeof(vmcs_version)))
6062 r = -EFAULT;
6063 }
6064 return r;
6065 }
6066 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
6067 if (!kvm_x86_ops.enable_l2_tlb_flush)
6068 return -ENOTTY;
6069
6070 return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
6071
6072 case KVM_CAP_HYPERV_ENFORCE_CPUID:
6073 return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
6074 #endif
6075
6076 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
6077 vcpu->arch.pv_cpuid.enforce = cap->args[0];
6078 return 0;
6079 default:
6080 return -EINVAL;
6081 }
6082 }
6083
6084 struct kvm_x86_reg_id {
6085 __u32 index;
6086 __u8 type;
6087 __u8 rsvd1;
6088 __u8 rsvd2:4;
6089 __u8 size:4;
6090 __u8 x86;
6091 };
6092
kvm_translate_kvm_reg(struct kvm_vcpu * vcpu,struct kvm_x86_reg_id * reg)6093 static int kvm_translate_kvm_reg(struct kvm_vcpu *vcpu,
6094 struct kvm_x86_reg_id *reg)
6095 {
6096 switch (reg->index) {
6097 case KVM_REG_GUEST_SSP:
6098 /*
6099 * FIXME: If host-initiated accesses are ever exempted from
6100 * ignore_msrs (in kvm_do_msr_access()), drop this manual check
6101 * and rely on KVM's standard checks to reject accesses to regs
6102 * that don't exist.
6103 */
6104 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
6105 return -EINVAL;
6106
6107 reg->type = KVM_X86_REG_TYPE_MSR;
6108 reg->index = MSR_KVM_INTERNAL_GUEST_SSP;
6109 break;
6110 default:
6111 return -EINVAL;
6112 }
6113 return 0;
6114 }
6115
kvm_get_one_msr(struct kvm_vcpu * vcpu,u32 msr,u64 __user * user_val)6116 static int kvm_get_one_msr(struct kvm_vcpu *vcpu, u32 msr, u64 __user *user_val)
6117 {
6118 u64 val;
6119
6120 if (do_get_msr(vcpu, msr, &val))
6121 return -EINVAL;
6122
6123 if (put_user(val, user_val))
6124 return -EFAULT;
6125
6126 return 0;
6127 }
6128
kvm_set_one_msr(struct kvm_vcpu * vcpu,u32 msr,u64 __user * user_val)6129 static int kvm_set_one_msr(struct kvm_vcpu *vcpu, u32 msr, u64 __user *user_val)
6130 {
6131 u64 val;
6132
6133 if (get_user(val, user_val))
6134 return -EFAULT;
6135
6136 if (do_set_msr(vcpu, msr, &val))
6137 return -EINVAL;
6138
6139 return 0;
6140 }
6141
kvm_get_set_one_reg(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)6142 static int kvm_get_set_one_reg(struct kvm_vcpu *vcpu, unsigned int ioctl,
6143 void __user *argp)
6144 {
6145 struct kvm_one_reg one_reg;
6146 struct kvm_x86_reg_id *reg;
6147 u64 __user *user_val;
6148 bool load_fpu;
6149 int r;
6150
6151 if (copy_from_user(&one_reg, argp, sizeof(one_reg)))
6152 return -EFAULT;
6153
6154 if ((one_reg.id & KVM_REG_ARCH_MASK) != KVM_REG_X86)
6155 return -EINVAL;
6156
6157 reg = (struct kvm_x86_reg_id *)&one_reg.id;
6158 if (reg->rsvd1 || reg->rsvd2)
6159 return -EINVAL;
6160
6161 if (reg->type == KVM_X86_REG_TYPE_KVM) {
6162 r = kvm_translate_kvm_reg(vcpu, reg);
6163 if (r)
6164 return r;
6165 }
6166
6167 if (reg->type != KVM_X86_REG_TYPE_MSR)
6168 return -EINVAL;
6169
6170 if ((one_reg.id & KVM_REG_SIZE_MASK) != KVM_REG_SIZE_U64)
6171 return -EINVAL;
6172
6173 guard(srcu)(&vcpu->kvm->srcu);
6174
6175 load_fpu = is_xstate_managed_msr(vcpu, reg->index);
6176 if (load_fpu)
6177 kvm_load_guest_fpu(vcpu);
6178
6179 user_val = u64_to_user_ptr(one_reg.addr);
6180 if (ioctl == KVM_GET_ONE_REG)
6181 r = kvm_get_one_msr(vcpu, reg->index, user_val);
6182 else
6183 r = kvm_set_one_msr(vcpu, reg->index, user_val);
6184
6185 if (load_fpu)
6186 kvm_put_guest_fpu(vcpu);
6187 return r;
6188 }
6189
kvm_get_reg_list(struct kvm_vcpu * vcpu,struct kvm_reg_list __user * user_list)6190 static int kvm_get_reg_list(struct kvm_vcpu *vcpu,
6191 struct kvm_reg_list __user *user_list)
6192 {
6193 u64 nr_regs = guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) ? 1 : 0;
6194 u64 user_nr_regs;
6195
6196 if (get_user(user_nr_regs, &user_list->n))
6197 return -EFAULT;
6198
6199 if (put_user(nr_regs, &user_list->n))
6200 return -EFAULT;
6201
6202 if (user_nr_regs < nr_regs)
6203 return -E2BIG;
6204
6205 if (nr_regs &&
6206 put_user(KVM_X86_REG_KVM(KVM_REG_GUEST_SSP), &user_list->reg[0]))
6207 return -EFAULT;
6208
6209 return 0;
6210 }
6211
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)6212 long kvm_arch_vcpu_ioctl(struct file *filp,
6213 unsigned int ioctl, unsigned long arg)
6214 {
6215 struct kvm_vcpu *vcpu = filp->private_data;
6216 void __user *argp = (void __user *)arg;
6217 int r;
6218 union {
6219 struct kvm_sregs2 *sregs2;
6220 struct kvm_lapic_state *lapic;
6221 struct kvm_xsave *xsave;
6222 struct kvm_xcrs *xcrs;
6223 void *buffer;
6224 } u;
6225
6226 vcpu_load(vcpu);
6227
6228 u.buffer = NULL;
6229 switch (ioctl) {
6230 case KVM_GET_LAPIC: {
6231 r = -EINVAL;
6232 if (!lapic_in_kernel(vcpu))
6233 goto out;
6234 u.lapic = kzalloc_obj(struct kvm_lapic_state);
6235
6236 r = -ENOMEM;
6237 if (!u.lapic)
6238 goto out;
6239 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
6240 if (r)
6241 goto out;
6242 r = -EFAULT;
6243 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
6244 goto out;
6245 r = 0;
6246 break;
6247 }
6248 case KVM_SET_LAPIC: {
6249 r = -EINVAL;
6250 if (!lapic_in_kernel(vcpu))
6251 goto out;
6252 u.lapic = memdup_user(argp, sizeof(*u.lapic));
6253 if (IS_ERR(u.lapic)) {
6254 r = PTR_ERR(u.lapic);
6255 goto out_nofree;
6256 }
6257
6258 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
6259 break;
6260 }
6261 case KVM_INTERRUPT: {
6262 struct kvm_interrupt irq;
6263
6264 r = -EFAULT;
6265 if (copy_from_user(&irq, argp, sizeof(irq)))
6266 goto out;
6267 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
6268 break;
6269 }
6270 case KVM_NMI: {
6271 r = kvm_vcpu_ioctl_nmi(vcpu);
6272 break;
6273 }
6274 case KVM_SMI: {
6275 r = kvm_inject_smi(vcpu);
6276 break;
6277 }
6278 case KVM_SET_CPUID: {
6279 struct kvm_cpuid __user *cpuid_arg = argp;
6280 struct kvm_cpuid cpuid;
6281
6282 r = -EFAULT;
6283 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6284 goto out;
6285 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
6286 break;
6287 }
6288 case KVM_SET_CPUID2: {
6289 struct kvm_cpuid2 __user *cpuid_arg = argp;
6290 struct kvm_cpuid2 cpuid;
6291
6292 r = -EFAULT;
6293 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6294 goto out;
6295 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
6296 cpuid_arg->entries);
6297 break;
6298 }
6299 case KVM_GET_CPUID2: {
6300 struct kvm_cpuid2 __user *cpuid_arg = argp;
6301 struct kvm_cpuid2 cpuid;
6302
6303 r = -EFAULT;
6304 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6305 goto out;
6306 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
6307 cpuid_arg->entries);
6308 if (r)
6309 goto out;
6310 r = -EFAULT;
6311 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
6312 goto out;
6313 r = 0;
6314 break;
6315 }
6316 case KVM_GET_MSRS: {
6317 int idx = srcu_read_lock(&vcpu->kvm->srcu);
6318 r = msr_io(vcpu, argp, do_get_msr, 1);
6319 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6320 break;
6321 }
6322 case KVM_SET_MSRS: {
6323 int idx = srcu_read_lock(&vcpu->kvm->srcu);
6324 r = msr_io(vcpu, argp, do_set_msr, 0);
6325 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6326 break;
6327 }
6328 case KVM_GET_ONE_REG:
6329 case KVM_SET_ONE_REG:
6330 r = kvm_get_set_one_reg(vcpu, ioctl, argp);
6331 break;
6332 case KVM_GET_REG_LIST:
6333 r = kvm_get_reg_list(vcpu, argp);
6334 break;
6335 case KVM_TPR_ACCESS_REPORTING: {
6336 struct kvm_tpr_access_ctl tac;
6337
6338 r = -EFAULT;
6339 if (copy_from_user(&tac, argp, sizeof(tac)))
6340 goto out;
6341 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
6342 if (r)
6343 goto out;
6344 r = -EFAULT;
6345 if (copy_to_user(argp, &tac, sizeof(tac)))
6346 goto out;
6347 r = 0;
6348 break;
6349 };
6350 case KVM_SET_VAPIC_ADDR: {
6351 struct kvm_vapic_addr va;
6352 int idx;
6353
6354 r = -EINVAL;
6355 if (!lapic_in_kernel(vcpu))
6356 goto out;
6357 r = -EFAULT;
6358 if (copy_from_user(&va, argp, sizeof(va)))
6359 goto out;
6360 idx = srcu_read_lock(&vcpu->kvm->srcu);
6361 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
6362 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6363 break;
6364 }
6365 case KVM_X86_SETUP_MCE: {
6366 u64 mcg_cap;
6367
6368 r = -EFAULT;
6369 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
6370 goto out;
6371 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6372 break;
6373 }
6374 case KVM_X86_SET_MCE: {
6375 struct kvm_x86_mce mce;
6376
6377 r = -EFAULT;
6378 if (copy_from_user(&mce, argp, sizeof(mce)))
6379 goto out;
6380 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6381 break;
6382 }
6383 case KVM_GET_VCPU_EVENTS: {
6384 struct kvm_vcpu_events events;
6385
6386 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6387
6388 r = -EFAULT;
6389 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6390 break;
6391 r = 0;
6392 break;
6393 }
6394 case KVM_SET_VCPU_EVENTS: {
6395 struct kvm_vcpu_events events;
6396
6397 r = -EFAULT;
6398 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6399 break;
6400
6401 kvm_vcpu_srcu_read_lock(vcpu);
6402 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
6403 kvm_vcpu_srcu_read_unlock(vcpu);
6404 break;
6405 }
6406 case KVM_GET_DEBUGREGS: {
6407 struct kvm_debugregs dbgregs;
6408
6409 r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6410 if (r < 0)
6411 break;
6412
6413 r = -EFAULT;
6414 if (copy_to_user(argp, &dbgregs,
6415 sizeof(struct kvm_debugregs)))
6416 break;
6417 r = 0;
6418 break;
6419 }
6420 case KVM_SET_DEBUGREGS: {
6421 struct kvm_debugregs dbgregs;
6422
6423 r = -EFAULT;
6424 if (copy_from_user(&dbgregs, argp,
6425 sizeof(struct kvm_debugregs)))
6426 break;
6427
6428 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6429 break;
6430 }
6431 case KVM_GET_XSAVE: {
6432 r = -EINVAL;
6433 if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6434 break;
6435
6436 u.xsave = kzalloc_obj(struct kvm_xsave);
6437 r = -ENOMEM;
6438 if (!u.xsave)
6439 break;
6440
6441 r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6442 if (r < 0)
6443 break;
6444
6445 r = -EFAULT;
6446 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
6447 break;
6448 r = 0;
6449 break;
6450 }
6451 case KVM_SET_XSAVE: {
6452 int size = vcpu->arch.guest_fpu.uabi_size;
6453
6454 u.xsave = memdup_user(argp, size);
6455 if (IS_ERR(u.xsave)) {
6456 r = PTR_ERR(u.xsave);
6457 goto out_nofree;
6458 }
6459
6460 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
6461 break;
6462 }
6463
6464 case KVM_GET_XSAVE2: {
6465 int size = vcpu->arch.guest_fpu.uabi_size;
6466
6467 u.xsave = kzalloc(size, GFP_KERNEL);
6468 r = -ENOMEM;
6469 if (!u.xsave)
6470 break;
6471
6472 r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6473 if (r < 0)
6474 break;
6475
6476 r = -EFAULT;
6477 if (copy_to_user(argp, u.xsave, size))
6478 break;
6479
6480 r = 0;
6481 break;
6482 }
6483
6484 case KVM_GET_XCRS: {
6485 u.xcrs = kzalloc_obj(struct kvm_xcrs);
6486 r = -ENOMEM;
6487 if (!u.xcrs)
6488 break;
6489
6490 r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6491 if (r < 0)
6492 break;
6493
6494 r = -EFAULT;
6495 if (copy_to_user(argp, u.xcrs,
6496 sizeof(struct kvm_xcrs)))
6497 break;
6498 r = 0;
6499 break;
6500 }
6501 case KVM_SET_XCRS: {
6502 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
6503 if (IS_ERR(u.xcrs)) {
6504 r = PTR_ERR(u.xcrs);
6505 goto out_nofree;
6506 }
6507
6508 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
6509 break;
6510 }
6511 case KVM_SET_TSC_KHZ: {
6512 u32 user_tsc_khz;
6513
6514 r = -EINVAL;
6515
6516 if (vcpu->arch.guest_tsc_protected)
6517 goto out;
6518
6519 user_tsc_khz = (u32)arg;
6520
6521 if (kvm_caps.has_tsc_control &&
6522 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6523 goto out;
6524
6525 if (user_tsc_khz == 0)
6526 user_tsc_khz = tsc_khz;
6527
6528 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6529 r = 0;
6530
6531 goto out;
6532 }
6533 case KVM_GET_TSC_KHZ: {
6534 r = vcpu->arch.virtual_tsc_khz;
6535 goto out;
6536 }
6537 case KVM_KVMCLOCK_CTRL: {
6538 r = kvm_set_guest_paused(vcpu);
6539 goto out;
6540 }
6541 case KVM_ENABLE_CAP: {
6542 struct kvm_enable_cap cap;
6543
6544 r = -EFAULT;
6545 if (copy_from_user(&cap, argp, sizeof(cap)))
6546 goto out;
6547 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6548 break;
6549 }
6550 case KVM_GET_NESTED_STATE: {
6551 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6552 u32 user_data_size;
6553
6554 r = -EINVAL;
6555 if (!kvm_x86_ops.nested_ops->get_state)
6556 break;
6557
6558 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
6559 r = -EFAULT;
6560 if (get_user(user_data_size, &user_kvm_nested_state->size))
6561 break;
6562
6563 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6564 user_data_size);
6565 if (r < 0)
6566 break;
6567
6568 if (r > user_data_size) {
6569 if (put_user(r, &user_kvm_nested_state->size))
6570 r = -EFAULT;
6571 else
6572 r = -E2BIG;
6573 break;
6574 }
6575
6576 r = 0;
6577 break;
6578 }
6579 case KVM_SET_NESTED_STATE: {
6580 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6581 struct kvm_nested_state kvm_state;
6582 int idx;
6583
6584 r = -EINVAL;
6585 if (!kvm_x86_ops.nested_ops->set_state)
6586 break;
6587
6588 r = -EFAULT;
6589 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
6590 break;
6591
6592 r = -EINVAL;
6593 if (kvm_state.size < sizeof(kvm_state))
6594 break;
6595
6596 if (kvm_state.flags &
6597 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
6598 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6599 | KVM_STATE_NESTED_GIF_SET))
6600 break;
6601
6602 /* nested_run_pending implies guest_mode. */
6603 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6604 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
6605 break;
6606
6607 idx = srcu_read_lock(&vcpu->kvm->srcu);
6608 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
6609 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6610 break;
6611 }
6612 #ifdef CONFIG_KVM_HYPERV
6613 case KVM_GET_SUPPORTED_HV_CPUID:
6614 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
6615 break;
6616 #endif
6617 #ifdef CONFIG_KVM_XEN
6618 case KVM_XEN_VCPU_GET_ATTR: {
6619 struct kvm_xen_vcpu_attr xva;
6620
6621 r = -EFAULT;
6622 if (copy_from_user(&xva, argp, sizeof(xva)))
6623 goto out;
6624 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6625 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6626 r = -EFAULT;
6627 break;
6628 }
6629 case KVM_XEN_VCPU_SET_ATTR: {
6630 struct kvm_xen_vcpu_attr xva;
6631
6632 r = -EFAULT;
6633 if (copy_from_user(&xva, argp, sizeof(xva)))
6634 goto out;
6635 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6636 break;
6637 }
6638 #endif
6639 case KVM_GET_SREGS2: {
6640 r = -EINVAL;
6641 if (vcpu->kvm->arch.has_protected_state &&
6642 vcpu->arch.guest_state_protected)
6643 goto out;
6644
6645 u.sregs2 = kzalloc_obj(struct kvm_sregs2);
6646 r = -ENOMEM;
6647 if (!u.sregs2)
6648 goto out;
6649 __get_sregs2(vcpu, u.sregs2);
6650 r = -EFAULT;
6651 if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6652 goto out;
6653 r = 0;
6654 break;
6655 }
6656 case KVM_SET_SREGS2: {
6657 r = -EINVAL;
6658 if (vcpu->kvm->arch.has_protected_state &&
6659 vcpu->arch.guest_state_protected)
6660 goto out;
6661
6662 u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6663 if (IS_ERR(u.sregs2)) {
6664 r = PTR_ERR(u.sregs2);
6665 u.sregs2 = NULL;
6666 goto out;
6667 }
6668 r = __set_sregs2(vcpu, u.sregs2);
6669 break;
6670 }
6671 case KVM_HAS_DEVICE_ATTR:
6672 case KVM_GET_DEVICE_ATTR:
6673 case KVM_SET_DEVICE_ATTR:
6674 r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6675 break;
6676 case KVM_MEMORY_ENCRYPT_OP:
6677 r = -ENOTTY;
6678 if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
6679 goto out;
6680 r = kvm_x86_ops.vcpu_mem_enc_ioctl(vcpu, argp);
6681 break;
6682 default:
6683 r = -EINVAL;
6684 }
6685 out:
6686 kfree(u.buffer);
6687 out_nofree:
6688 vcpu_put(vcpu);
6689 return r;
6690 }
6691
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)6692 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6693 {
6694 return VM_FAULT_SIGBUS;
6695 }
6696
kvm_vm_ioctl_set_tss_addr(struct kvm * kvm,unsigned long addr)6697 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6698 {
6699 int ret;
6700
6701 if (addr > (unsigned int)(-3 * PAGE_SIZE))
6702 return -EINVAL;
6703 ret = kvm_x86_call(set_tss_addr)(kvm, addr);
6704 return ret;
6705 }
6706
kvm_vm_ioctl_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)6707 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6708 u64 ident_addr)
6709 {
6710 return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
6711 }
6712
kvm_vm_ioctl_set_nr_mmu_pages(struct kvm * kvm,unsigned long kvm_nr_mmu_pages)6713 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6714 unsigned long kvm_nr_mmu_pages)
6715 {
6716 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6717 return -EINVAL;
6718
6719 mutex_lock(&kvm->slots_lock);
6720
6721 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6722 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6723
6724 mutex_unlock(&kvm->slots_lock);
6725 return 0;
6726 }
6727
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)6728 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6729 {
6730
6731 /*
6732 * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
6733 * before reporting dirty_bitmap to userspace. KVM flushes the buffers
6734 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6735 * VM-Exit.
6736 */
6737 struct kvm_vcpu *vcpu;
6738 unsigned long i;
6739
6740 if (!kvm->arch.cpu_dirty_log_size)
6741 return;
6742
6743 kvm_for_each_vcpu(i, vcpu, kvm)
6744 kvm_vcpu_kick(vcpu);
6745 }
6746
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)6747 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6748 struct kvm_enable_cap *cap)
6749 {
6750 int r;
6751
6752 if (cap->flags)
6753 return -EINVAL;
6754
6755 switch (cap->cap) {
6756 case KVM_CAP_DISABLE_QUIRKS2:
6757 r = -EINVAL;
6758 if (cap->args[0] & ~kvm_caps.supported_quirks)
6759 break;
6760 fallthrough;
6761 case KVM_CAP_DISABLE_QUIRKS:
6762 kvm->arch.disabled_quirks |= cap->args[0] & kvm_caps.supported_quirks;
6763 r = 0;
6764 break;
6765 case KVM_CAP_SPLIT_IRQCHIP: {
6766 mutex_lock(&kvm->lock);
6767 r = -EINVAL;
6768 if (cap->args[0] > KVM_MAX_IRQ_ROUTES)
6769 goto split_irqchip_unlock;
6770 r = -EEXIST;
6771 if (irqchip_in_kernel(kvm))
6772 goto split_irqchip_unlock;
6773 if (kvm->created_vcpus)
6774 goto split_irqchip_unlock;
6775 /* Pairs with irqchip_in_kernel. */
6776 smp_wmb();
6777 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6778 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6779 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6780 r = 0;
6781 split_irqchip_unlock:
6782 mutex_unlock(&kvm->lock);
6783 break;
6784 }
6785 case KVM_CAP_X2APIC_API:
6786 r = -EINVAL;
6787 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6788 break;
6789
6790 if ((cap->args[0] & KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST) &&
6791 (cap->args[0] & KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST))
6792 break;
6793
6794 if ((cap->args[0] & KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST) &&
6795 !irqchip_split(kvm))
6796 break;
6797
6798 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6799 kvm->arch.x2apic_format = true;
6800 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6801 kvm->arch.x2apic_broadcast_quirk_disabled = true;
6802
6803 if (cap->args[0] & KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST)
6804 kvm->arch.suppress_eoi_broadcast_mode = KVM_SUPPRESS_EOI_BROADCAST_ENABLED;
6805 if (cap->args[0] & KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST)
6806 kvm->arch.suppress_eoi_broadcast_mode = KVM_SUPPRESS_EOI_BROADCAST_DISABLED;
6807
6808 r = 0;
6809 break;
6810 case KVM_CAP_X86_DISABLE_EXITS:
6811 r = -EINVAL;
6812 if (cap->args[0] & ~kvm_get_allowed_disable_exits())
6813 break;
6814
6815 mutex_lock(&kvm->lock);
6816 if (kvm->created_vcpus)
6817 goto disable_exits_unlock;
6818
6819 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6820 "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6821
6822 if (!mitigate_smt_rsb && boot_cpu_has_bug(X86_BUG_SMT_RSB) &&
6823 cpu_smt_possible() &&
6824 (cap->args[0] & ~(KVM_X86_DISABLE_EXITS_PAUSE |
6825 KVM_X86_DISABLE_EXITS_APERFMPERF)))
6826 pr_warn_once(SMT_RSB_MSG);
6827
6828 kvm_disable_exits(kvm, cap->args[0]);
6829 r = 0;
6830 disable_exits_unlock:
6831 mutex_unlock(&kvm->lock);
6832 break;
6833 case KVM_CAP_MSR_PLATFORM_INFO:
6834 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6835 r = 0;
6836 break;
6837 case KVM_CAP_EXCEPTION_PAYLOAD:
6838 kvm->arch.exception_payload_enabled = cap->args[0];
6839 r = 0;
6840 break;
6841 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6842 kvm->arch.triple_fault_event = cap->args[0];
6843 r = 0;
6844 break;
6845 case KVM_CAP_X86_USER_SPACE_MSR:
6846 r = -EINVAL;
6847 if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
6848 break;
6849 kvm->arch.user_space_msr_mask = cap->args[0];
6850 r = 0;
6851 break;
6852 case KVM_CAP_X86_BUS_LOCK_EXIT:
6853 r = -EINVAL;
6854 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6855 break;
6856
6857 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6858 (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6859 break;
6860
6861 if (kvm_caps.has_bus_lock_exit &&
6862 cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6863 kvm->arch.bus_lock_detection_enabled = true;
6864 r = 0;
6865 break;
6866 #ifdef CONFIG_X86_SGX_KVM
6867 case KVM_CAP_SGX_ATTRIBUTE: {
6868 unsigned long allowed_attributes = 0;
6869
6870 r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6871 if (r)
6872 break;
6873
6874 /* KVM only supports the PROVISIONKEY privileged attribute. */
6875 if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6876 !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6877 kvm->arch.sgx_provisioning_allowed = true;
6878 else
6879 r = -EINVAL;
6880 break;
6881 }
6882 #endif
6883 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6884 r = -EINVAL;
6885 if (!kvm_x86_ops.vm_copy_enc_context_from)
6886 break;
6887
6888 r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
6889 break;
6890 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6891 r = -EINVAL;
6892 if (!kvm_x86_ops.vm_move_enc_context_from)
6893 break;
6894
6895 r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
6896 break;
6897 case KVM_CAP_EXIT_HYPERCALL:
6898 if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6899 r = -EINVAL;
6900 break;
6901 }
6902 kvm->arch.hypercall_exit_enabled = cap->args[0];
6903 r = 0;
6904 break;
6905 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6906 r = -EINVAL;
6907 if (cap->args[0] & ~1)
6908 break;
6909 kvm->arch.exit_on_emulation_error = cap->args[0];
6910 r = 0;
6911 break;
6912 case KVM_CAP_PMU_CAPABILITY:
6913 r = -EINVAL;
6914 if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6915 break;
6916
6917 mutex_lock(&kvm->lock);
6918 if (!kvm->created_vcpus && !kvm->arch.created_mediated_pmu) {
6919 kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6920 r = 0;
6921 }
6922 mutex_unlock(&kvm->lock);
6923 break;
6924 case KVM_CAP_MAX_VCPU_ID:
6925 r = -EINVAL;
6926 if (cap->args[0] > KVM_MAX_VCPU_IDS)
6927 break;
6928
6929 mutex_lock(&kvm->lock);
6930 if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
6931 ;
6932 } else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6933 r = 0;
6934 } else if (!kvm->arch.max_vcpu_ids) {
6935 kvm->arch.max_vcpu_ids = cap->args[0];
6936 r = 0;
6937 }
6938 mutex_unlock(&kvm->lock);
6939 break;
6940 case KVM_CAP_X86_NOTIFY_VMEXIT:
6941 r = -EINVAL;
6942 if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6943 break;
6944 if (!kvm_caps.has_notify_vmexit)
6945 break;
6946 if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6947 break;
6948 mutex_lock(&kvm->lock);
6949 if (!kvm->created_vcpus) {
6950 kvm->arch.notify_window = cap->args[0] >> 32;
6951 kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6952 r = 0;
6953 }
6954 mutex_unlock(&kvm->lock);
6955 break;
6956 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6957 r = -EINVAL;
6958
6959 /*
6960 * Since the risk of disabling NX hugepages is a guest crashing
6961 * the system, ensure the userspace process has permission to
6962 * reboot the system.
6963 *
6964 * Note that unlike the reboot() syscall, the process must have
6965 * this capability in the root namespace because exposing
6966 * /dev/kvm into a container does not limit the scope of the
6967 * iTLB multihit bug to that container. In other words,
6968 * this must use capable(), not ns_capable().
6969 */
6970 if (!capable(CAP_SYS_BOOT)) {
6971 r = -EPERM;
6972 break;
6973 }
6974
6975 if (cap->args[0])
6976 break;
6977
6978 mutex_lock(&kvm->lock);
6979 if (!kvm->created_vcpus) {
6980 kvm->arch.disable_nx_huge_pages = true;
6981 r = 0;
6982 }
6983 mutex_unlock(&kvm->lock);
6984 break;
6985 case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
6986 u64 bus_cycle_ns = cap->args[0];
6987 u64 unused;
6988
6989 /*
6990 * Guard against overflow in tmict_to_ns(). 128 is the highest
6991 * divide value that can be programmed in APIC_TDCR.
6992 */
6993 r = -EINVAL;
6994 if (!bus_cycle_ns ||
6995 check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
6996 break;
6997
6998 r = 0;
6999 mutex_lock(&kvm->lock);
7000 if (!irqchip_in_kernel(kvm))
7001 r = -ENXIO;
7002 else if (kvm->created_vcpus)
7003 r = -EINVAL;
7004 else
7005 kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
7006 mutex_unlock(&kvm->lock);
7007 break;
7008 }
7009 default:
7010 r = -EINVAL;
7011 break;
7012 }
7013 return r;
7014 }
7015
kvm_alloc_msr_filter(bool default_allow)7016 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
7017 {
7018 struct kvm_x86_msr_filter *msr_filter;
7019
7020 msr_filter = kzalloc_obj(*msr_filter, GFP_KERNEL_ACCOUNT);
7021 if (!msr_filter)
7022 return NULL;
7023
7024 msr_filter->default_allow = default_allow;
7025 return msr_filter;
7026 }
7027
kvm_free_msr_filter(struct kvm_x86_msr_filter * msr_filter)7028 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
7029 {
7030 u32 i;
7031
7032 if (!msr_filter)
7033 return;
7034
7035 for (i = 0; i < msr_filter->count; i++)
7036 kfree(msr_filter->ranges[i].bitmap);
7037
7038 kfree(msr_filter);
7039 }
7040
kvm_add_msr_filter(struct kvm_x86_msr_filter * msr_filter,struct kvm_msr_filter_range * user_range)7041 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
7042 struct kvm_msr_filter_range *user_range)
7043 {
7044 unsigned long *bitmap;
7045 size_t bitmap_size;
7046
7047 if (!user_range->nmsrs)
7048 return 0;
7049
7050 if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
7051 return -EINVAL;
7052
7053 if (!user_range->flags)
7054 return -EINVAL;
7055
7056 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
7057 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
7058 return -EINVAL;
7059
7060 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
7061 if (IS_ERR(bitmap))
7062 return PTR_ERR(bitmap);
7063
7064 msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
7065 .flags = user_range->flags,
7066 .base = user_range->base,
7067 .nmsrs = user_range->nmsrs,
7068 .bitmap = bitmap,
7069 };
7070
7071 msr_filter->count++;
7072 return 0;
7073 }
7074
kvm_vm_ioctl_set_msr_filter(struct kvm * kvm,struct kvm_msr_filter * filter)7075 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
7076 struct kvm_msr_filter *filter)
7077 {
7078 struct kvm_x86_msr_filter *new_filter, *old_filter;
7079 bool default_allow;
7080 bool empty = true;
7081 int r;
7082 u32 i;
7083
7084 if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
7085 return -EINVAL;
7086
7087 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
7088 empty &= !filter->ranges[i].nmsrs;
7089
7090 default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
7091 if (empty && !default_allow)
7092 return -EINVAL;
7093
7094 new_filter = kvm_alloc_msr_filter(default_allow);
7095 if (!new_filter)
7096 return -ENOMEM;
7097
7098 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
7099 r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
7100 if (r) {
7101 kvm_free_msr_filter(new_filter);
7102 return r;
7103 }
7104 }
7105
7106 mutex_lock(&kvm->lock);
7107 old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
7108 mutex_is_locked(&kvm->lock));
7109 mutex_unlock(&kvm->lock);
7110 synchronize_srcu(&kvm->srcu);
7111
7112 kvm_free_msr_filter(old_filter);
7113
7114 /*
7115 * Recalc MSR intercepts as userspace may want to intercept accesses to
7116 * MSRs that KVM would otherwise pass through to the guest.
7117 */
7118 kvm_make_all_cpus_request(kvm, KVM_REQ_RECALC_INTERCEPTS);
7119
7120 return 0;
7121 }
7122
7123 #ifdef CONFIG_KVM_COMPAT
7124 /* for KVM_X86_SET_MSR_FILTER */
7125 struct kvm_msr_filter_range_compat {
7126 __u32 flags;
7127 __u32 nmsrs;
7128 __u32 base;
7129 __u32 bitmap;
7130 };
7131
7132 struct kvm_msr_filter_compat {
7133 __u32 flags;
7134 struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
7135 };
7136
7137 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
7138
kvm_arch_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7139 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
7140 unsigned long arg)
7141 {
7142 void __user *argp = (void __user *)arg;
7143 struct kvm *kvm = filp->private_data;
7144 long r = -ENOTTY;
7145
7146 switch (ioctl) {
7147 case KVM_X86_SET_MSR_FILTER_COMPAT: {
7148 struct kvm_msr_filter __user *user_msr_filter = argp;
7149 struct kvm_msr_filter_compat filter_compat;
7150 struct kvm_msr_filter filter;
7151 int i;
7152
7153 if (copy_from_user(&filter_compat, user_msr_filter,
7154 sizeof(filter_compat)))
7155 return -EFAULT;
7156
7157 filter.flags = filter_compat.flags;
7158 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
7159 struct kvm_msr_filter_range_compat *cr;
7160
7161 cr = &filter_compat.ranges[i];
7162 filter.ranges[i] = (struct kvm_msr_filter_range) {
7163 .flags = cr->flags,
7164 .nmsrs = cr->nmsrs,
7165 .base = cr->base,
7166 .bitmap = (__u8 *)(ulong)cr->bitmap,
7167 };
7168 }
7169
7170 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7171 break;
7172 }
7173 }
7174
7175 return r;
7176 }
7177 #endif
7178
7179 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_arch_suspend_notifier(struct kvm * kvm)7180 static int kvm_arch_suspend_notifier(struct kvm *kvm)
7181 {
7182 struct kvm_vcpu *vcpu;
7183 unsigned long i;
7184
7185 /*
7186 * Ignore the return, marking the guest paused only "fails" if the vCPU
7187 * isn't using kvmclock; continuing on is correct and desirable.
7188 */
7189 kvm_for_each_vcpu(i, vcpu, kvm)
7190 (void)kvm_set_guest_paused(vcpu);
7191
7192 return NOTIFY_DONE;
7193 }
7194
kvm_arch_pm_notifier(struct kvm * kvm,unsigned long state)7195 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
7196 {
7197 switch (state) {
7198 case PM_HIBERNATION_PREPARE:
7199 case PM_SUSPEND_PREPARE:
7200 return kvm_arch_suspend_notifier(kvm);
7201 }
7202
7203 return NOTIFY_DONE;
7204 }
7205 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
7206
kvm_vm_ioctl_get_clock(struct kvm * kvm,void __user * argp)7207 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
7208 {
7209 struct kvm_clock_data data = { 0 };
7210
7211 get_kvmclock(kvm, &data);
7212 if (copy_to_user(argp, &data, sizeof(data)))
7213 return -EFAULT;
7214
7215 return 0;
7216 }
7217
kvm_vm_ioctl_set_clock(struct kvm * kvm,void __user * argp)7218 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
7219 {
7220 struct kvm_arch *ka = &kvm->arch;
7221 struct kvm_clock_data data;
7222 u64 now_raw_ns;
7223
7224 if (copy_from_user(&data, argp, sizeof(data)))
7225 return -EFAULT;
7226
7227 /*
7228 * Only KVM_CLOCK_REALTIME is used, but allow passing the
7229 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
7230 */
7231 if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
7232 return -EINVAL;
7233
7234 kvm_hv_request_tsc_page_update(kvm);
7235 kvm_start_pvclock_update(kvm);
7236 pvclock_update_vm_gtod_copy(kvm);
7237
7238 /*
7239 * This pairs with kvm_guest_time_update(): when masterclock is
7240 * in use, we use master_kernel_ns + kvmclock_offset to set
7241 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
7242 * is slightly ahead) here we risk going negative on unsigned
7243 * 'system_time' when 'data.clock' is very small.
7244 */
7245 if (data.flags & KVM_CLOCK_REALTIME) {
7246 u64 now_real_ns = ktime_get_real_ns();
7247
7248 /*
7249 * Avoid stepping the kvmclock backwards.
7250 */
7251 if (now_real_ns > data.realtime)
7252 data.clock += now_real_ns - data.realtime;
7253 }
7254
7255 if (ka->use_master_clock)
7256 now_raw_ns = ka->master_kernel_ns;
7257 else
7258 now_raw_ns = get_kvmclock_base_ns();
7259 ka->kvmclock_offset = data.clock - now_raw_ns;
7260 kvm_end_pvclock_update(kvm);
7261 return 0;
7262 }
7263
kvm_arch_vcpu_unlocked_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7264 long kvm_arch_vcpu_unlocked_ioctl(struct file *filp, unsigned int ioctl,
7265 unsigned long arg)
7266 {
7267 struct kvm_vcpu *vcpu = filp->private_data;
7268 void __user *argp = (void __user *)arg;
7269
7270 if (ioctl == KVM_MEMORY_ENCRYPT_OP &&
7271 kvm_x86_ops.vcpu_mem_enc_unlocked_ioctl)
7272 return kvm_x86_call(vcpu_mem_enc_unlocked_ioctl)(vcpu, argp);
7273
7274 return -ENOIOCTLCMD;
7275 }
7276
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7277 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
7278 {
7279 struct kvm *kvm = filp->private_data;
7280 void __user *argp = (void __user *)arg;
7281 int r = -ENOTTY;
7282
7283 #ifdef CONFIG_KVM_IOAPIC
7284 /*
7285 * This union makes it completely explicit to gcc-3.x
7286 * that these three variables' stack usage should be
7287 * combined, not added together.
7288 */
7289 union {
7290 struct kvm_pit_state ps;
7291 struct kvm_pit_state2 ps2;
7292 struct kvm_pit_config pit_config;
7293 } u;
7294 #endif
7295
7296 switch (ioctl) {
7297 case KVM_SET_TSS_ADDR:
7298 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
7299 break;
7300 case KVM_SET_IDENTITY_MAP_ADDR: {
7301 u64 ident_addr;
7302
7303 mutex_lock(&kvm->lock);
7304 r = -EINVAL;
7305 if (kvm->created_vcpus)
7306 goto set_identity_unlock;
7307 r = -EFAULT;
7308 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
7309 goto set_identity_unlock;
7310 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
7311 set_identity_unlock:
7312 mutex_unlock(&kvm->lock);
7313 break;
7314 }
7315 case KVM_SET_NR_MMU_PAGES:
7316 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
7317 break;
7318 #ifdef CONFIG_KVM_IOAPIC
7319 case KVM_CREATE_IRQCHIP: {
7320 mutex_lock(&kvm->lock);
7321
7322 r = -EEXIST;
7323 if (irqchip_in_kernel(kvm))
7324 goto create_irqchip_unlock;
7325
7326 /*
7327 * Disallow an in-kernel I/O APIC if the VM has protected EOIs,
7328 * i.e. if KVM can't intercept EOIs and thus can't properly
7329 * emulate level-triggered interrupts.
7330 */
7331 r = -ENOTTY;
7332 if (kvm->arch.has_protected_eoi)
7333 goto create_irqchip_unlock;
7334
7335 r = -EINVAL;
7336 if (kvm->created_vcpus)
7337 goto create_irqchip_unlock;
7338
7339 r = kvm_pic_init(kvm);
7340 if (r)
7341 goto create_irqchip_unlock;
7342
7343 r = kvm_ioapic_init(kvm);
7344 if (r) {
7345 kvm_pic_destroy(kvm);
7346 goto create_irqchip_unlock;
7347 }
7348
7349 r = kvm_setup_default_ioapic_and_pic_routing(kvm);
7350 if (r) {
7351 kvm_ioapic_destroy(kvm);
7352 kvm_pic_destroy(kvm);
7353 goto create_irqchip_unlock;
7354 }
7355 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
7356 smp_wmb();
7357 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
7358 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
7359 create_irqchip_unlock:
7360 mutex_unlock(&kvm->lock);
7361 break;
7362 }
7363 case KVM_CREATE_PIT:
7364 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7365 goto create_pit;
7366 case KVM_CREATE_PIT2:
7367 r = -EFAULT;
7368 if (copy_from_user(&u.pit_config, argp,
7369 sizeof(struct kvm_pit_config)))
7370 goto out;
7371 create_pit:
7372 mutex_lock(&kvm->lock);
7373 r = -EEXIST;
7374 if (kvm->arch.vpit)
7375 goto create_pit_unlock;
7376 r = -ENOENT;
7377 if (!pic_in_kernel(kvm))
7378 goto create_pit_unlock;
7379 r = -ENOMEM;
7380 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7381 if (kvm->arch.vpit)
7382 r = 0;
7383 create_pit_unlock:
7384 mutex_unlock(&kvm->lock);
7385 break;
7386 case KVM_GET_IRQCHIP: {
7387 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7388 struct kvm_irqchip *chip;
7389
7390 chip = memdup_user(argp, sizeof(*chip));
7391 if (IS_ERR(chip)) {
7392 r = PTR_ERR(chip);
7393 goto out;
7394 }
7395
7396 r = -ENXIO;
7397 if (!irqchip_full(kvm))
7398 goto get_irqchip_out;
7399 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
7400 if (r)
7401 goto get_irqchip_out;
7402 r = -EFAULT;
7403 if (copy_to_user(argp, chip, sizeof(*chip)))
7404 goto get_irqchip_out;
7405 r = 0;
7406 get_irqchip_out:
7407 kfree(chip);
7408 break;
7409 }
7410 case KVM_SET_IRQCHIP: {
7411 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7412 struct kvm_irqchip *chip;
7413
7414 chip = memdup_user(argp, sizeof(*chip));
7415 if (IS_ERR(chip)) {
7416 r = PTR_ERR(chip);
7417 goto out;
7418 }
7419
7420 r = -ENXIO;
7421 if (!irqchip_full(kvm))
7422 goto set_irqchip_out;
7423 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
7424 set_irqchip_out:
7425 kfree(chip);
7426 break;
7427 }
7428 case KVM_GET_PIT: {
7429 r = -EFAULT;
7430 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
7431 goto out;
7432 r = -ENXIO;
7433 if (!kvm->arch.vpit)
7434 goto out;
7435 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
7436 if (r)
7437 goto out;
7438 r = -EFAULT;
7439 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
7440 goto out;
7441 r = 0;
7442 break;
7443 }
7444 case KVM_SET_PIT: {
7445 r = -EFAULT;
7446 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
7447 goto out;
7448 mutex_lock(&kvm->lock);
7449 r = -ENXIO;
7450 if (!kvm->arch.vpit)
7451 goto set_pit_out;
7452 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7453 set_pit_out:
7454 mutex_unlock(&kvm->lock);
7455 break;
7456 }
7457 case KVM_GET_PIT2: {
7458 r = -ENXIO;
7459 if (!kvm->arch.vpit)
7460 goto out;
7461 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7462 if (r)
7463 goto out;
7464 r = -EFAULT;
7465 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7466 goto out;
7467 r = 0;
7468 break;
7469 }
7470 case KVM_SET_PIT2: {
7471 r = -EFAULT;
7472 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7473 goto out;
7474 mutex_lock(&kvm->lock);
7475 r = -ENXIO;
7476 if (!kvm->arch.vpit)
7477 goto set_pit2_out;
7478 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7479 set_pit2_out:
7480 mutex_unlock(&kvm->lock);
7481 break;
7482 }
7483 case KVM_REINJECT_CONTROL: {
7484 struct kvm_reinject_control control;
7485 r = -EFAULT;
7486 if (copy_from_user(&control, argp, sizeof(control)))
7487 goto out;
7488 r = -ENXIO;
7489 if (!kvm->arch.vpit)
7490 goto out;
7491 r = kvm_vm_ioctl_reinject(kvm, &control);
7492 break;
7493 }
7494 #endif
7495 case KVM_SET_BOOT_CPU_ID:
7496 r = 0;
7497 mutex_lock(&kvm->lock);
7498 if (kvm->created_vcpus)
7499 r = -EBUSY;
7500 else if (arg > KVM_MAX_VCPU_IDS ||
7501 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
7502 r = -EINVAL;
7503 else
7504 kvm->arch.bsp_vcpu_id = arg;
7505 mutex_unlock(&kvm->lock);
7506 break;
7507 #ifdef CONFIG_KVM_XEN
7508 case KVM_XEN_HVM_CONFIG: {
7509 struct kvm_xen_hvm_config xhc;
7510 r = -EFAULT;
7511 if (copy_from_user(&xhc, argp, sizeof(xhc)))
7512 goto out;
7513 r = kvm_xen_hvm_config(kvm, &xhc);
7514 break;
7515 }
7516 case KVM_XEN_HVM_GET_ATTR: {
7517 struct kvm_xen_hvm_attr xha;
7518
7519 r = -EFAULT;
7520 if (copy_from_user(&xha, argp, sizeof(xha)))
7521 goto out;
7522 r = kvm_xen_hvm_get_attr(kvm, &xha);
7523 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7524 r = -EFAULT;
7525 break;
7526 }
7527 case KVM_XEN_HVM_SET_ATTR: {
7528 struct kvm_xen_hvm_attr xha;
7529
7530 r = -EFAULT;
7531 if (copy_from_user(&xha, argp, sizeof(xha)))
7532 goto out;
7533 r = kvm_xen_hvm_set_attr(kvm, &xha);
7534 break;
7535 }
7536 case KVM_XEN_HVM_EVTCHN_SEND: {
7537 struct kvm_irq_routing_xen_evtchn uxe;
7538
7539 r = -EFAULT;
7540 if (copy_from_user(&uxe, argp, sizeof(uxe)))
7541 goto out;
7542 r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7543 break;
7544 }
7545 #endif
7546 case KVM_SET_CLOCK:
7547 r = kvm_vm_ioctl_set_clock(kvm, argp);
7548 break;
7549 case KVM_GET_CLOCK:
7550 r = kvm_vm_ioctl_get_clock(kvm, argp);
7551 break;
7552 case KVM_SET_TSC_KHZ: {
7553 u32 user_tsc_khz;
7554
7555 r = -EINVAL;
7556 user_tsc_khz = (u32)arg;
7557
7558 if (kvm_caps.has_tsc_control &&
7559 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
7560 goto out;
7561
7562 if (user_tsc_khz == 0)
7563 user_tsc_khz = tsc_khz;
7564
7565 mutex_lock(&kvm->lock);
7566 if (!kvm->created_vcpus) {
7567 WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7568 r = 0;
7569 }
7570 mutex_unlock(&kvm->lock);
7571 goto out;
7572 }
7573 case KVM_GET_TSC_KHZ: {
7574 r = READ_ONCE(kvm->arch.default_tsc_khz);
7575 goto out;
7576 }
7577 case KVM_MEMORY_ENCRYPT_OP:
7578 r = -ENOTTY;
7579 if (!kvm_x86_ops.mem_enc_ioctl)
7580 goto out;
7581
7582 r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
7583 break;
7584 case KVM_MEMORY_ENCRYPT_REG_REGION: {
7585 struct kvm_enc_region region;
7586
7587 r = -EFAULT;
7588 if (copy_from_user(®ion, argp, sizeof(region)))
7589 goto out;
7590
7591 r = -ENOTTY;
7592 if (!kvm_x86_ops.mem_enc_register_region)
7593 goto out;
7594
7595 r = kvm_x86_call(mem_enc_register_region)(kvm, ®ion);
7596 break;
7597 }
7598 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7599 struct kvm_enc_region region;
7600
7601 r = -EFAULT;
7602 if (copy_from_user(®ion, argp, sizeof(region)))
7603 goto out;
7604
7605 r = -ENOTTY;
7606 if (!kvm_x86_ops.mem_enc_unregister_region)
7607 goto out;
7608
7609 r = kvm_x86_call(mem_enc_unregister_region)(kvm, ®ion);
7610 break;
7611 }
7612 #ifdef CONFIG_KVM_HYPERV
7613 case KVM_HYPERV_EVENTFD: {
7614 struct kvm_hyperv_eventfd hvevfd;
7615
7616 r = -EFAULT;
7617 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7618 goto out;
7619 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7620 break;
7621 }
7622 #endif
7623 case KVM_SET_PMU_EVENT_FILTER:
7624 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7625 break;
7626 case KVM_X86_SET_MSR_FILTER: {
7627 struct kvm_msr_filter __user *user_msr_filter = argp;
7628 struct kvm_msr_filter filter;
7629
7630 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7631 return -EFAULT;
7632
7633 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7634 break;
7635 }
7636 default:
7637 r = -ENOTTY;
7638 }
7639 out:
7640 return r;
7641 }
7642
kvm_probe_feature_msr(u32 msr_index)7643 static void kvm_probe_feature_msr(u32 msr_index)
7644 {
7645 u64 data;
7646
7647 if (kvm_get_feature_msr(NULL, msr_index, &data, true))
7648 return;
7649
7650 msr_based_features[num_msr_based_features++] = msr_index;
7651 }
7652
kvm_probe_msr_to_save(u32 msr_index)7653 static void kvm_probe_msr_to_save(u32 msr_index)
7654 {
7655 u32 dummy[2];
7656
7657 if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7658 return;
7659
7660 /*
7661 * Even MSRs that are valid in the host may not be exposed to guests in
7662 * some cases.
7663 */
7664 switch (msr_index) {
7665 case MSR_IA32_BNDCFGS:
7666 if (!kvm_mpx_supported())
7667 return;
7668 break;
7669 case MSR_TSC_AUX:
7670 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7671 !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7672 return;
7673 break;
7674 case MSR_IA32_UMWAIT_CONTROL:
7675 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7676 return;
7677 break;
7678 case MSR_IA32_RTIT_CTL:
7679 case MSR_IA32_RTIT_STATUS:
7680 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7681 return;
7682 break;
7683 case MSR_IA32_RTIT_CR3_MATCH:
7684 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7685 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7686 return;
7687 break;
7688 case MSR_IA32_RTIT_OUTPUT_BASE:
7689 case MSR_IA32_RTIT_OUTPUT_MASK:
7690 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7691 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7692 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7693 return;
7694 break;
7695 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7696 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7697 (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7698 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7699 return;
7700 break;
7701 case MSR_ARCH_PERFMON_PERFCTR0 ...
7702 MSR_ARCH_PERFMON_PERFCTR0 + KVM_MAX_NR_GP_COUNTERS - 1:
7703 if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7704 kvm_pmu_cap.num_counters_gp)
7705 return;
7706 break;
7707 case MSR_ARCH_PERFMON_EVENTSEL0 ...
7708 MSR_ARCH_PERFMON_EVENTSEL0 + KVM_MAX_NR_GP_COUNTERS - 1:
7709 if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7710 kvm_pmu_cap.num_counters_gp)
7711 return;
7712 break;
7713 case MSR_ARCH_PERFMON_FIXED_CTR0 ...
7714 MSR_ARCH_PERFMON_FIXED_CTR0 + KVM_MAX_NR_FIXED_COUNTERS - 1:
7715 if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7716 kvm_pmu_cap.num_counters_fixed)
7717 return;
7718 break;
7719 case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7720 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7721 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7722 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET:
7723 if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7724 return;
7725 break;
7726 case MSR_IA32_XFD:
7727 case MSR_IA32_XFD_ERR:
7728 if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7729 return;
7730 break;
7731 case MSR_IA32_TSX_CTRL:
7732 if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7733 return;
7734 break;
7735 case MSR_IA32_XSS:
7736 if (!kvm_caps.supported_xss)
7737 return;
7738 break;
7739 case MSR_IA32_U_CET:
7740 case MSR_IA32_S_CET:
7741 if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
7742 !kvm_cpu_cap_has(X86_FEATURE_IBT))
7743 return;
7744 break;
7745 case MSR_IA32_INT_SSP_TAB:
7746 if (!kvm_cpu_cap_has(X86_FEATURE_LM))
7747 return;
7748 fallthrough;
7749 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
7750 if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK))
7751 return;
7752 break;
7753 default:
7754 break;
7755 }
7756
7757 msrs_to_save[num_msrs_to_save++] = msr_index;
7758 }
7759
kvm_init_msr_lists(void)7760 static void kvm_init_msr_lists(void)
7761 {
7762 unsigned i;
7763
7764 BUILD_BUG_ON_MSG(KVM_MAX_NR_FIXED_COUNTERS != 3,
7765 "Please update the fixed PMCs in msrs_to_save_pmu[]");
7766
7767 num_msrs_to_save = 0;
7768 num_emulated_msrs = 0;
7769 num_msr_based_features = 0;
7770
7771 for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7772 kvm_probe_msr_to_save(msrs_to_save_base[i]);
7773
7774 if (enable_pmu) {
7775 for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7776 kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
7777 }
7778
7779 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7780 if (!kvm_x86_call(has_emulated_msr)(NULL,
7781 emulated_msrs_all[i]))
7782 continue;
7783
7784 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7785 }
7786
7787 for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7788 kvm_probe_feature_msr(i);
7789
7790 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7791 kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
7792 }
7793
vcpu_mmio_write(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * __v)7794 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7795 void *__v)
7796 {
7797 const void *v = __v;
7798 int handled = 0;
7799 int n;
7800
7801 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, len, addr, __v);
7802
7803 do {
7804 n = min(len, 8);
7805 if (!(lapic_in_kernel(vcpu) &&
7806 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7807 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7808 break;
7809 handled += n;
7810 addr += n;
7811 len -= n;
7812 v += n;
7813 } while (len);
7814
7815 return handled;
7816 }
7817
vcpu_mmio_read(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * v)7818 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7819 {
7820 int handled = 0;
7821 int n;
7822
7823 do {
7824 n = min(len, 8);
7825 if (!(lapic_in_kernel(vcpu) &&
7826 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7827 addr, n, v))
7828 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7829 break;
7830 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7831 handled += n;
7832 addr += n;
7833 len -= n;
7834 v += n;
7835 } while (len);
7836
7837 if (len)
7838 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, len, addr, NULL);
7839
7840 return handled;
7841 }
7842
kvm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7843 void kvm_set_segment(struct kvm_vcpu *vcpu,
7844 struct kvm_segment *var, int seg)
7845 {
7846 kvm_x86_call(set_segment)(vcpu, var, seg);
7847 }
7848
kvm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7849 void kvm_get_segment(struct kvm_vcpu *vcpu,
7850 struct kvm_segment *var, int seg)
7851 {
7852 kvm_x86_call(get_segment)(vcpu, var, seg);
7853 }
7854
translate_nested_gpa(struct kvm_vcpu * vcpu,gpa_t gpa,u64 access,struct x86_exception * exception)7855 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7856 struct x86_exception *exception)
7857 {
7858 struct kvm_mmu *mmu = vcpu->arch.mmu;
7859 gpa_t t_gpa;
7860
7861 BUG_ON(!mmu_is_nested(vcpu));
7862
7863 /* NPT walks are always user-walks */
7864 access |= PFERR_USER_MASK;
7865 t_gpa = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7866
7867 return t_gpa;
7868 }
7869
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7870 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7871 struct x86_exception *exception)
7872 {
7873 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7874
7875 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7876 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7877 }
7878 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_read);
7879
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7880 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7881 struct x86_exception *exception)
7882 {
7883 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7884
7885 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7886 access |= PFERR_WRITE_MASK;
7887 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7888 }
7889 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_write);
7890
7891 /* 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)7892 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7893 struct x86_exception *exception)
7894 {
7895 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7896
7897 return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7898 }
7899
kvm_read_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7900 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7901 struct kvm_vcpu *vcpu, u64 access,
7902 struct x86_exception *exception)
7903 {
7904 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7905 void *data = val;
7906 int r = X86EMUL_CONTINUE;
7907
7908 while (bytes) {
7909 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7910 unsigned offset = addr & (PAGE_SIZE-1);
7911 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7912 int ret;
7913
7914 if (gpa == INVALID_GPA)
7915 return X86EMUL_PROPAGATE_FAULT;
7916 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7917 offset, toread);
7918 if (ret < 0) {
7919 r = X86EMUL_IO_NEEDED;
7920 goto out;
7921 }
7922
7923 bytes -= toread;
7924 data += toread;
7925 addr += toread;
7926 }
7927 out:
7928 return r;
7929 }
7930
7931 /* 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)7932 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7933 gva_t addr, void *val, unsigned int bytes,
7934 struct x86_exception *exception)
7935 {
7936 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7937 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7938 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7939 unsigned offset;
7940 int ret;
7941
7942 /* Inline kvm_read_guest_virt_helper for speed. */
7943 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7944 exception);
7945 if (unlikely(gpa == INVALID_GPA))
7946 return X86EMUL_PROPAGATE_FAULT;
7947
7948 offset = addr & (PAGE_SIZE-1);
7949 if (WARN_ON(offset + bytes > PAGE_SIZE))
7950 bytes = (unsigned)PAGE_SIZE - offset;
7951 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7952 offset, bytes);
7953 if (unlikely(ret < 0))
7954 return X86EMUL_IO_NEEDED;
7955
7956 return X86EMUL_CONTINUE;
7957 }
7958
kvm_read_guest_virt(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7959 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7960 gva_t addr, void *val, unsigned int bytes,
7961 struct x86_exception *exception)
7962 {
7963 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7964
7965 /*
7966 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7967 * is returned, but our callers are not ready for that and they blindly
7968 * call kvm_inject_page_fault. Ensure that they at least do not leak
7969 * uninitialized kernel stack memory into cr2 and error code.
7970 */
7971 memset(exception, 0, sizeof(*exception));
7972 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7973 exception);
7974 }
7975 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_virt);
7976
emulator_read_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7977 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7978 gva_t addr, void *val, unsigned int bytes,
7979 struct x86_exception *exception, bool system)
7980 {
7981 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7982 u64 access = 0;
7983
7984 if (system)
7985 access |= PFERR_IMPLICIT_ACCESS;
7986 else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7987 access |= PFERR_USER_MASK;
7988
7989 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7990 }
7991
kvm_write_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7992 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7993 struct kvm_vcpu *vcpu, u64 access,
7994 struct x86_exception *exception)
7995 {
7996 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7997 void *data = val;
7998 int r = X86EMUL_CONTINUE;
7999
8000 while (bytes) {
8001 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
8002 unsigned offset = addr & (PAGE_SIZE-1);
8003 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
8004 int ret;
8005
8006 if (gpa == INVALID_GPA)
8007 return X86EMUL_PROPAGATE_FAULT;
8008 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
8009 if (ret < 0) {
8010 r = X86EMUL_IO_NEEDED;
8011 goto out;
8012 }
8013
8014 bytes -= towrite;
8015 data += towrite;
8016 addr += towrite;
8017 }
8018 out:
8019 return r;
8020 }
8021
emulator_write_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)8022 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
8023 unsigned int bytes, struct x86_exception *exception,
8024 bool system)
8025 {
8026 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8027 u64 access = PFERR_WRITE_MASK;
8028
8029 if (system)
8030 access |= PFERR_IMPLICIT_ACCESS;
8031 else if (kvm_x86_call(get_cpl)(vcpu) == 3)
8032 access |= PFERR_USER_MASK;
8033
8034 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
8035 access, exception);
8036 }
8037
kvm_write_guest_virt_system(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)8038 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
8039 unsigned int bytes, struct x86_exception *exception)
8040 {
8041 /* kvm_write_guest_virt_system can pull in tons of pages. */
8042 kvm_request_l1tf_flush_l1d();
8043
8044 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
8045 PFERR_WRITE_MASK, exception);
8046 }
8047 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_write_guest_virt_system);
8048
kvm_check_emulate_insn(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)8049 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
8050 void *insn, int insn_len)
8051 {
8052 return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
8053 insn, insn_len);
8054 }
8055
handle_ud(struct kvm_vcpu * vcpu)8056 int handle_ud(struct kvm_vcpu *vcpu)
8057 {
8058 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
8059 int fep_flags = READ_ONCE(force_emulation_prefix);
8060 int emul_type = EMULTYPE_TRAP_UD;
8061 char sig[5]; /* ud2; .ascii "kvm" */
8062 struct x86_exception e;
8063 int r;
8064
8065 r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
8066 if (r != X86EMUL_CONTINUE)
8067 return 1;
8068
8069 if (fep_flags &&
8070 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
8071 sig, sizeof(sig), &e) == 0 &&
8072 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
8073 if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
8074 kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
8075 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
8076 emul_type = EMULTYPE_TRAP_UD_FORCED;
8077 }
8078
8079 return kvm_emulate_instruction(vcpu, emul_type);
8080 }
8081 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_ud);
8082
vcpu_is_mmio_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t gpa,bool write)8083 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
8084 gpa_t gpa, bool write)
8085 {
8086 /* For APIC access vmexit */
8087 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8088 return 1;
8089
8090 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
8091 trace_vcpu_match_mmio(gva, gpa, write, true);
8092 return 1;
8093 }
8094
8095 return 0;
8096 }
8097
vcpu_mmio_gva_to_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t * gpa,struct x86_exception * exception,bool write)8098 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
8099 gpa_t *gpa, struct x86_exception *exception,
8100 bool write)
8101 {
8102 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8103 u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
8104 | (write ? PFERR_WRITE_MASK : 0);
8105
8106 /*
8107 * currently PKRU is only applied to ept enabled guest so
8108 * there is no pkey in EPT page table for L1 guest or EPT
8109 * shadow page table for L2 guest.
8110 */
8111 if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
8112 !permission_fault(vcpu, vcpu->arch.walk_mmu,
8113 vcpu->arch.mmio_access, 0, access))) {
8114 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
8115 (gva & (PAGE_SIZE - 1));
8116 trace_vcpu_match_mmio(gva, *gpa, write, false);
8117 return 1;
8118 }
8119
8120 *gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
8121
8122 if (*gpa == INVALID_GPA)
8123 return -1;
8124
8125 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
8126 }
8127
8128 struct read_write_emulator_ops {
8129 int (*read_write_guest)(struct kvm_vcpu *vcpu, gpa_t gpa,
8130 void *val, int bytes);
8131 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
8132 int bytes, void *val);
8133 bool write;
8134 };
8135
emulator_read_guest(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8136 static int emulator_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa,
8137 void *val, int bytes)
8138 {
8139 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
8140 }
8141
emulator_write_guest(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8142 static int emulator_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa,
8143 void *val, int bytes)
8144 {
8145 int ret;
8146
8147 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
8148 if (ret < 0)
8149 return 0;
8150 kvm_page_track_write(vcpu, gpa, val, bytes);
8151 return 1;
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 /*
8184 * If the memory is not _known_ to be emulated MMIO, attempt to access
8185 * guest memory. If accessing guest memory fails, e.g. because there's
8186 * no memslot, then handle the access as MMIO. Note, treating the
8187 * access as emulated MMIO is technically wrong if there is a memslot,
8188 * i.e. if accessing host user memory failed, but this has been KVM's
8189 * historical ABI for decades.
8190 */
8191 if (!ret && ops->read_write_guest(vcpu, gpa, val, bytes))
8192 return X86EMUL_CONTINUE;
8193
8194 /*
8195 * Attempt to handle emulated MMIO within the kernel, e.g. for accesses
8196 * to an in-kernel local or I/O APIC, or to an ioeventfd range attached
8197 * to MMIO bus. If the access isn't fully resolved, insert an MMIO
8198 * fragment with the relevant details.
8199 */
8200 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
8201 if (handled == bytes)
8202 return X86EMUL_CONTINUE;
8203
8204 gpa += handled;
8205 bytes -= handled;
8206 val += handled;
8207
8208 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
8209 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
8210 frag->gpa = gpa;
8211 if (write && bytes <= 8u) {
8212 frag->val = 0;
8213 frag->data = &frag->val;
8214 memcpy(&frag->val, val, bytes);
8215 } else {
8216 frag->data = val;
8217 }
8218 frag->len = bytes;
8219
8220 /*
8221 * Continue emulating, even though KVM needs to (eventually) do an MMIO
8222 * exit to userspace. If the access splits multiple pages, then KVM
8223 * needs to exit to userspace only after emulating both parts of the
8224 * access.
8225 */
8226 return X86EMUL_CONTINUE;
8227 }
8228
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)8229 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
8230 unsigned long addr,
8231 void *val, unsigned int bytes,
8232 struct x86_exception *exception,
8233 const struct read_write_emulator_ops *ops)
8234 {
8235 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8236 int rc;
8237
8238 if (WARN_ON_ONCE((bytes > 8u || !ops->write) && object_is_on_stack(val)))
8239 return X86EMUL_UNHANDLEABLE;
8240
8241 /*
8242 * If the read was already completed via a userspace MMIO exit, there's
8243 * nothing left to do except trace the MMIO read. When completing MMIO
8244 * reads, KVM re-emulates the instruction to propagate the value into
8245 * the correct destination, e.g. into the correct register, but the
8246 * value itself has already been copied to the read cache.
8247 *
8248 * Note! This is *tightly* coupled to read_emulated() satisfying reads
8249 * from the emulator's mem_read cache, so that the MMIO fragment data
8250 * is copied to the correct chunk of the correct operand.
8251 */
8252 if (!ops->write && vcpu->mmio_read_completed) {
8253 /*
8254 * For simplicity, trace the entire MMIO read in one shot, even
8255 * though the GPA might be incorrect if there are two fragments
8256 * that aren't contiguous in the GPA space.
8257 */
8258 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
8259 vcpu->mmio_fragments[0].gpa, val);
8260 vcpu->mmio_read_completed = 0;
8261 return X86EMUL_CONTINUE;
8262 }
8263
8264 vcpu->mmio_nr_fragments = 0;
8265
8266 /* Crossing a page boundary? */
8267 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
8268 int now;
8269
8270 now = -addr & ~PAGE_MASK;
8271 rc = emulator_read_write_onepage(addr, val, now, exception,
8272 vcpu, ops);
8273
8274 if (rc != X86EMUL_CONTINUE)
8275 return rc;
8276 addr += now;
8277 if (ctxt->mode != X86EMUL_MODE_PROT64)
8278 addr = (u32)addr;
8279 val += now;
8280 bytes -= now;
8281 }
8282
8283 rc = emulator_read_write_onepage(addr, val, bytes, exception,
8284 vcpu, ops);
8285 if (rc != X86EMUL_CONTINUE)
8286 return rc;
8287
8288 if (!vcpu->mmio_nr_fragments)
8289 return X86EMUL_CONTINUE;
8290
8291 vcpu->mmio_needed = 1;
8292 vcpu->mmio_cur_fragment = 0;
8293 vcpu->mmio_is_write = ops->write;
8294
8295 kvm_prepare_emulated_mmio_exit(vcpu, &vcpu->mmio_fragments[0]);
8296
8297 /*
8298 * For MMIO reads, stop emulating and immediately exit to userspace, as
8299 * KVM needs the value to correctly emulate the instruction. For MMIO
8300 * writes, continue emulating as the write to MMIO is a side effect for
8301 * all intents and purposes. KVM will still exit to userspace, but
8302 * after completing emulation (see the check on vcpu->mmio_needed in
8303 * x86_emulate_instruction()).
8304 */
8305 return ops->write ? X86EMUL_CONTINUE : X86EMUL_IO_NEEDED;
8306 }
8307
emulator_read_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception)8308 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8309 unsigned long addr,
8310 void *val,
8311 unsigned int bytes,
8312 struct x86_exception *exception)
8313 {
8314 static const struct read_write_emulator_ops ops = {
8315 .read_write_guest = emulator_read_guest,
8316 .read_write_mmio = vcpu_mmio_read,
8317 .write = false,
8318 };
8319
8320 return emulator_read_write(ctxt, addr, val, bytes, exception, &ops);
8321 }
8322
emulator_write_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * val,unsigned int bytes,struct x86_exception * exception)8323 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
8324 unsigned long addr,
8325 const void *val,
8326 unsigned int bytes,
8327 struct x86_exception *exception)
8328 {
8329 static const struct read_write_emulator_ops ops = {
8330 .read_write_guest = emulator_write_guest,
8331 .read_write_mmio = vcpu_mmio_write,
8332 .write = true,
8333 };
8334
8335 return emulator_read_write(ctxt, addr, (void *)val, bytes, exception, &ops);
8336 }
8337
8338 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
8339 (__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
8340
emulator_cmpxchg_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * old,const void * new,unsigned int bytes,struct x86_exception * exception)8341 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8342 unsigned long addr,
8343 const void *old,
8344 const void *new,
8345 unsigned int bytes,
8346 struct x86_exception *exception)
8347 {
8348 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8349 u64 page_line_mask;
8350 unsigned long hva;
8351 gpa_t gpa;
8352 int r;
8353
8354 /* guests cmpxchg8b have to be emulated atomically */
8355 if (bytes > 8 || (bytes & (bytes - 1)))
8356 goto emul_write;
8357
8358 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
8359
8360 if (gpa == INVALID_GPA ||
8361 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8362 goto emul_write;
8363
8364 /*
8365 * Emulate the atomic as a straight write to avoid #AC if SLD is
8366 * enabled in the host and the access splits a cache line.
8367 */
8368 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8369 page_line_mask = ~(cache_line_size() - 1);
8370 else
8371 page_line_mask = PAGE_MASK;
8372
8373 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
8374 goto emul_write;
8375
8376 hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
8377 if (kvm_is_error_hva(hva))
8378 goto emul_write;
8379
8380 hva += offset_in_page(gpa);
8381
8382 switch (bytes) {
8383 case 1:
8384 r = emulator_try_cmpxchg_user(u8, hva, old, new);
8385 break;
8386 case 2:
8387 r = emulator_try_cmpxchg_user(u16, hva, old, new);
8388 break;
8389 case 4:
8390 r = emulator_try_cmpxchg_user(u32, hva, old, new);
8391 break;
8392 case 8:
8393 r = emulator_try_cmpxchg_user(u64, hva, old, new);
8394 break;
8395 default:
8396 BUG();
8397 }
8398
8399 if (r < 0)
8400 return X86EMUL_UNHANDLEABLE;
8401
8402 /*
8403 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8404 * successful, as the old value is written back on failure. Note, for
8405 * live migration, this is unnecessarily conservative as CMPXCHG writes
8406 * back the original value and the access is atomic, but KVM's ABI is
8407 * that all writes are dirty logged, regardless of the value written.
8408 */
8409 kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8410
8411 if (r)
8412 return X86EMUL_CMPXCHG_FAILED;
8413
8414 kvm_page_track_write(vcpu, gpa, new, bytes);
8415
8416 return X86EMUL_CONTINUE;
8417
8418 emul_write:
8419 pr_warn_once("emulating exchange as write\n");
8420
8421 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
8422 }
8423
emulator_pio_in_out(struct kvm_vcpu * vcpu,int size,unsigned short port,void * data,unsigned int count,bool in)8424 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
8425 unsigned short port, void *data,
8426 unsigned int count, bool in)
8427 {
8428 unsigned i;
8429 int r;
8430
8431 WARN_ON_ONCE(vcpu->arch.pio.count);
8432 for (i = 0; i < count; i++) {
8433 if (in)
8434 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
8435 else
8436 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
8437
8438 if (r) {
8439 if (i == 0)
8440 goto userspace_io;
8441
8442 /*
8443 * Userspace must have unregistered the device while PIO
8444 * was running. Drop writes / read as 0.
8445 */
8446 if (in)
8447 memset(data, 0, size * (count - i));
8448 break;
8449 }
8450
8451 data += size;
8452 }
8453 return 1;
8454
8455 userspace_io:
8456 vcpu->arch.pio.port = port;
8457 vcpu->arch.pio.in = in;
8458 vcpu->arch.pio.count = count;
8459 vcpu->arch.pio.size = size;
8460
8461 if (in)
8462 memset(vcpu->arch.pio_data, 0, size * count);
8463 else
8464 memcpy(vcpu->arch.pio_data, data, size * count);
8465
8466 vcpu->run->exit_reason = KVM_EXIT_IO;
8467 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
8468 vcpu->run->io.size = size;
8469 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8470 vcpu->run->io.count = count;
8471 vcpu->run->io.port = port;
8472 return 0;
8473 }
8474
emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,void * val,unsigned int count)8475 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8476 unsigned short port, void *val, unsigned int count)
8477 {
8478 int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8479 if (r)
8480 trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8481
8482 return r;
8483 }
8484
complete_emulator_pio_in(struct kvm_vcpu * vcpu,void * val)8485 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
8486 {
8487 int size = vcpu->arch.pio.size;
8488 unsigned int count = vcpu->arch.pio.count;
8489 memcpy(val, vcpu->arch.pio_data, size * count);
8490 trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
8491 vcpu->arch.pio.count = 0;
8492 }
8493
emulator_pio_in_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,void * val,unsigned int count)8494 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8495 int size, unsigned short port, void *val,
8496 unsigned int count)
8497 {
8498 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8499 if (vcpu->arch.pio.count) {
8500 /*
8501 * Complete a previous iteration that required userspace I/O.
8502 * Note, @count isn't guaranteed to match pio.count as userspace
8503 * can modify ECX before rerunning the vCPU. Ignore any such
8504 * shenanigans as KVM doesn't support modifying the rep count,
8505 * and the emulator ensures @count doesn't overflow the buffer.
8506 */
8507 complete_emulator_pio_in(vcpu, val);
8508 return 1;
8509 }
8510
8511 return emulator_pio_in(vcpu, size, port, val, count);
8512 }
8513
emulator_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port,const void * val,unsigned int count)8514 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8515 unsigned short port, const void *val,
8516 unsigned int count)
8517 {
8518 trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
8519 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
8520 }
8521
emulator_pio_out_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,const void * val,unsigned int count)8522 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8523 int size, unsigned short port,
8524 const void *val, unsigned int count)
8525 {
8526 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8527 }
8528
get_segment_base(struct kvm_vcpu * vcpu,int seg)8529 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8530 {
8531 return kvm_x86_call(get_segment_base)(vcpu, seg);
8532 }
8533
emulator_invlpg(struct x86_emulate_ctxt * ctxt,ulong address)8534 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
8535 {
8536 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
8537 }
8538
kvm_emulate_wbinvd_noskip(struct kvm_vcpu * vcpu)8539 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
8540 {
8541 if (!need_emulate_wbinvd(vcpu))
8542 return X86EMUL_CONTINUE;
8543
8544 if (kvm_x86_call(has_wbinvd_exit)()) {
8545 int cpu = get_cpu();
8546
8547 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
8548 wbinvd_on_cpus_mask(vcpu->arch.wbinvd_dirty_mask);
8549 put_cpu();
8550 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
8551 } else
8552 wbinvd();
8553 return X86EMUL_CONTINUE;
8554 }
8555
kvm_emulate_wbinvd(struct kvm_vcpu * vcpu)8556 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8557 {
8558 kvm_emulate_wbinvd_noskip(vcpu);
8559 return kvm_skip_emulated_instruction(vcpu);
8560 }
8561 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wbinvd);
8562
8563
8564
emulator_wbinvd(struct x86_emulate_ctxt * ctxt)8565 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8566 {
8567 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
8568 }
8569
emulator_get_dr(struct x86_emulate_ctxt * ctxt,int dr)8570 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
8571 {
8572 return kvm_get_dr(emul_to_vcpu(ctxt), dr);
8573 }
8574
emulator_set_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long value)8575 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8576 unsigned long value)
8577 {
8578
8579 return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
8580 }
8581
mk_cr_64(u64 curr_cr,u32 new_val)8582 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
8583 {
8584 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
8585 }
8586
emulator_get_cr(struct x86_emulate_ctxt * ctxt,int cr)8587 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
8588 {
8589 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8590 unsigned long value;
8591
8592 switch (cr) {
8593 case 0:
8594 value = kvm_read_cr0(vcpu);
8595 break;
8596 case 2:
8597 value = vcpu->arch.cr2;
8598 break;
8599 case 3:
8600 value = kvm_read_cr3(vcpu);
8601 break;
8602 case 4:
8603 value = kvm_read_cr4(vcpu);
8604 break;
8605 case 8:
8606 value = kvm_get_cr8(vcpu);
8607 break;
8608 default:
8609 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8610 return 0;
8611 }
8612
8613 return value;
8614 }
8615
emulator_set_cr(struct x86_emulate_ctxt * ctxt,int cr,ulong val)8616 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
8617 {
8618 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8619 int res = 0;
8620
8621 switch (cr) {
8622 case 0:
8623 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
8624 break;
8625 case 2:
8626 vcpu->arch.cr2 = val;
8627 break;
8628 case 3:
8629 res = kvm_set_cr3(vcpu, val);
8630 break;
8631 case 4:
8632 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
8633 break;
8634 case 8:
8635 res = kvm_set_cr8(vcpu, val);
8636 break;
8637 default:
8638 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8639 res = -1;
8640 }
8641
8642 return res;
8643 }
8644
emulator_get_cpl(struct x86_emulate_ctxt * ctxt)8645 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8646 {
8647 return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
8648 }
8649
emulator_get_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8650 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8651 {
8652 kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
8653 }
8654
emulator_get_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8655 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8656 {
8657 kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
8658 }
8659
emulator_set_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8660 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8661 {
8662 kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
8663 }
8664
emulator_set_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8665 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8666 {
8667 kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
8668 }
8669
emulator_get_cached_segment_base(struct x86_emulate_ctxt * ctxt,int seg)8670 static unsigned long emulator_get_cached_segment_base(
8671 struct x86_emulate_ctxt *ctxt, int seg)
8672 {
8673 return get_segment_base(emul_to_vcpu(ctxt), seg);
8674 }
8675
emulator_get_segment(struct x86_emulate_ctxt * ctxt,u16 * selector,struct desc_struct * desc,u32 * base3,int seg)8676 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8677 struct desc_struct *desc, u32 *base3,
8678 int seg)
8679 {
8680 struct kvm_segment var;
8681
8682 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8683 *selector = var.selector;
8684
8685 if (var.unusable) {
8686 memset(desc, 0, sizeof(*desc));
8687 if (base3)
8688 *base3 = 0;
8689 return false;
8690 }
8691
8692 if (var.g)
8693 var.limit >>= 12;
8694 set_desc_limit(desc, var.limit);
8695 set_desc_base(desc, (unsigned long)var.base);
8696 #ifdef CONFIG_X86_64
8697 if (base3)
8698 *base3 = var.base >> 32;
8699 #endif
8700 desc->type = var.type;
8701 desc->s = var.s;
8702 desc->dpl = var.dpl;
8703 desc->p = var.present;
8704 desc->avl = var.avl;
8705 desc->l = var.l;
8706 desc->d = var.db;
8707 desc->g = var.g;
8708
8709 return true;
8710 }
8711
emulator_set_segment(struct x86_emulate_ctxt * ctxt,u16 selector,struct desc_struct * desc,u32 base3,int seg)8712 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8713 struct desc_struct *desc, u32 base3,
8714 int seg)
8715 {
8716 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8717 struct kvm_segment var;
8718
8719 var.selector = selector;
8720 var.base = get_desc_base(desc);
8721 #ifdef CONFIG_X86_64
8722 var.base |= ((u64)base3) << 32;
8723 #endif
8724 var.limit = get_desc_limit(desc);
8725 if (desc->g)
8726 var.limit = (var.limit << 12) | 0xfff;
8727 var.type = desc->type;
8728 var.dpl = desc->dpl;
8729 var.db = desc->d;
8730 var.s = desc->s;
8731 var.l = desc->l;
8732 var.g = desc->g;
8733 var.avl = desc->avl;
8734 var.present = desc->p;
8735 var.unusable = !var.present;
8736 var.padding = 0;
8737
8738 kvm_set_segment(vcpu, &var, seg);
8739 return;
8740 }
8741
emulator_get_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8742 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8743 u32 msr_index, u64 *pdata)
8744 {
8745 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8746 int r;
8747
8748 r = kvm_emulate_msr_read(vcpu, msr_index, pdata);
8749 if (r < 0)
8750 return X86EMUL_UNHANDLEABLE;
8751
8752 if (r) {
8753 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8754 complete_emulated_rdmsr, r))
8755 return X86EMUL_IO_NEEDED;
8756
8757 trace_kvm_msr_read_ex(msr_index);
8758 return X86EMUL_PROPAGATE_FAULT;
8759 }
8760
8761 trace_kvm_msr_read(msr_index, *pdata);
8762 return X86EMUL_CONTINUE;
8763 }
8764
emulator_set_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)8765 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8766 u32 msr_index, u64 data)
8767 {
8768 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8769 int r;
8770
8771 r = kvm_emulate_msr_write(vcpu, msr_index, data);
8772 if (r < 0)
8773 return X86EMUL_UNHANDLEABLE;
8774
8775 if (r) {
8776 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8777 complete_emulated_msr_access, r))
8778 return X86EMUL_IO_NEEDED;
8779
8780 trace_kvm_msr_write_ex(msr_index, data);
8781 return X86EMUL_PROPAGATE_FAULT;
8782 }
8783
8784 trace_kvm_msr_write(msr_index, data);
8785 return X86EMUL_CONTINUE;
8786 }
8787
emulator_get_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8788 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8789 u32 msr_index, u64 *pdata)
8790 {
8791 /*
8792 * Treat emulator accesses to the current shadow stack pointer as host-
8793 * initiated, as they aren't true MSR accesses (SSP is a "just a reg"),
8794 * and this API is used only for implicit accesses, i.e. not RDMSR, and
8795 * so the index is fully KVM-controlled.
8796 */
8797 if (unlikely(msr_index == MSR_KVM_INTERNAL_GUEST_SSP))
8798 return kvm_msr_read(emul_to_vcpu(ctxt), msr_index, pdata);
8799
8800 return __kvm_emulate_msr_read(emul_to_vcpu(ctxt), msr_index, pdata);
8801 }
8802
emulator_check_rdpmc_early(struct x86_emulate_ctxt * ctxt,u32 pmc)8803 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
8804 {
8805 return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
8806 }
8807
emulator_read_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc,u64 * pdata)8808 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8809 u32 pmc, u64 *pdata)
8810 {
8811 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8812 }
8813
emulator_halt(struct x86_emulate_ctxt * ctxt)8814 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8815 {
8816 emul_to_vcpu(ctxt)->arch.halt_request = 1;
8817 }
8818
emulator_intercept(struct x86_emulate_ctxt * ctxt,struct x86_instruction_info * info,enum x86_intercept_stage stage)8819 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8820 struct x86_instruction_info *info,
8821 enum x86_intercept_stage stage)
8822 {
8823 return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
8824 &ctxt->exception);
8825 }
8826
emulator_get_cpuid(struct x86_emulate_ctxt * ctxt,u32 * eax,u32 * ebx,u32 * ecx,u32 * edx,bool exact_only)8827 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8828 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8829 bool exact_only)
8830 {
8831 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8832 }
8833
emulator_guest_has_movbe(struct x86_emulate_ctxt * ctxt)8834 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8835 {
8836 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8837 }
8838
emulator_guest_has_fxsr(struct x86_emulate_ctxt * ctxt)8839 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8840 {
8841 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8842 }
8843
emulator_guest_has_rdpid(struct x86_emulate_ctxt * ctxt)8844 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8845 {
8846 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8847 }
8848
emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt * ctxt)8849 static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
8850 {
8851 return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
8852 }
8853
emulator_read_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg)8854 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8855 {
8856 return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8857 }
8858
emulator_write_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg,ulong val)8859 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8860 {
8861 kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8862 }
8863
emulator_set_nmi_mask(struct x86_emulate_ctxt * ctxt,bool masked)8864 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8865 {
8866 kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8867 }
8868
emulator_is_smm(struct x86_emulate_ctxt * ctxt)8869 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
8870 {
8871 return is_smm(emul_to_vcpu(ctxt));
8872 }
8873
8874 #ifndef CONFIG_KVM_SMM
emulator_leave_smm(struct x86_emulate_ctxt * ctxt)8875 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8876 {
8877 WARN_ON_ONCE(1);
8878 return X86EMUL_UNHANDLEABLE;
8879 }
8880 #endif
8881
emulator_triple_fault(struct x86_emulate_ctxt * ctxt)8882 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8883 {
8884 kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8885 }
8886
emulator_get_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 * xcr)8887 static int emulator_get_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 *xcr)
8888 {
8889 if (index != XCR_XFEATURE_ENABLED_MASK)
8890 return 1;
8891 *xcr = emul_to_vcpu(ctxt)->arch.xcr0;
8892 return 0;
8893 }
8894
emulator_set_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 xcr)8895 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8896 {
8897 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8898 }
8899
emulator_vm_bugged(struct x86_emulate_ctxt * ctxt)8900 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8901 {
8902 struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8903
8904 if (!kvm->vm_bugged)
8905 kvm_vm_bugged(kvm);
8906 }
8907
emulator_get_untagged_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8908 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8909 gva_t addr, unsigned int flags)
8910 {
8911 if (!kvm_x86_ops.get_untagged_addr)
8912 return addr;
8913
8914 return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
8915 addr, flags);
8916 }
8917
emulator_is_canonical_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8918 static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
8919 gva_t addr, unsigned int flags)
8920 {
8921 return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
8922 }
8923
emulator_page_address_valid(struct x86_emulate_ctxt * ctxt,gpa_t gpa)8924 static bool emulator_page_address_valid(struct x86_emulate_ctxt *ctxt, gpa_t gpa)
8925 {
8926 return page_address_valid(emul_to_vcpu(ctxt), gpa);
8927 }
8928
8929 static const struct x86_emulate_ops emulate_ops = {
8930 .vm_bugged = emulator_vm_bugged,
8931 .read_gpr = emulator_read_gpr,
8932 .write_gpr = emulator_write_gpr,
8933 .read_std = emulator_read_std,
8934 .write_std = emulator_write_std,
8935 .fetch = kvm_fetch_guest_virt,
8936 .read_emulated = emulator_read_emulated,
8937 .write_emulated = emulator_write_emulated,
8938 .cmpxchg_emulated = emulator_cmpxchg_emulated,
8939 .invlpg = emulator_invlpg,
8940 .pio_in_emulated = emulator_pio_in_emulated,
8941 .pio_out_emulated = emulator_pio_out_emulated,
8942 .get_segment = emulator_get_segment,
8943 .set_segment = emulator_set_segment,
8944 .get_cached_segment_base = emulator_get_cached_segment_base,
8945 .get_gdt = emulator_get_gdt,
8946 .get_idt = emulator_get_idt,
8947 .set_gdt = emulator_set_gdt,
8948 .set_idt = emulator_set_idt,
8949 .get_cr = emulator_get_cr,
8950 .set_cr = emulator_set_cr,
8951 .cpl = emulator_get_cpl,
8952 .get_dr = emulator_get_dr,
8953 .set_dr = emulator_set_dr,
8954 .set_msr_with_filter = emulator_set_msr_with_filter,
8955 .get_msr_with_filter = emulator_get_msr_with_filter,
8956 .get_msr = emulator_get_msr,
8957 .check_rdpmc_early = emulator_check_rdpmc_early,
8958 .read_pmc = emulator_read_pmc,
8959 .halt = emulator_halt,
8960 .wbinvd = emulator_wbinvd,
8961 .fix_hypercall = emulator_fix_hypercall,
8962 .intercept = emulator_intercept,
8963 .get_cpuid = emulator_get_cpuid,
8964 .guest_has_movbe = emulator_guest_has_movbe,
8965 .guest_has_fxsr = emulator_guest_has_fxsr,
8966 .guest_has_rdpid = emulator_guest_has_rdpid,
8967 .guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
8968 .set_nmi_mask = emulator_set_nmi_mask,
8969 .is_smm = emulator_is_smm,
8970 .leave_smm = emulator_leave_smm,
8971 .triple_fault = emulator_triple_fault,
8972 .get_xcr = emulator_get_xcr,
8973 .set_xcr = emulator_set_xcr,
8974 .get_untagged_addr = emulator_get_untagged_addr,
8975 .is_canonical_addr = emulator_is_canonical_addr,
8976 .page_address_valid = emulator_page_address_valid,
8977 };
8978
toggle_interruptibility(struct kvm_vcpu * vcpu,u32 mask)8979 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8980 {
8981 u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
8982 /*
8983 * an sti; sti; sequence only disable interrupts for the first
8984 * instruction. So, if the last instruction, be it emulated or
8985 * not, left the system with the INT_STI flag enabled, it
8986 * means that the last instruction is an sti. We should not
8987 * leave the flag on in this case. The same goes for mov ss
8988 */
8989 if (int_shadow & mask)
8990 mask = 0;
8991 if (unlikely(int_shadow || mask)) {
8992 kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
8993 if (!mask)
8994 kvm_make_request(KVM_REQ_EVENT, vcpu);
8995 }
8996 }
8997
inject_emulated_exception(struct kvm_vcpu * vcpu)8998 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8999 {
9000 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9001
9002 if (ctxt->exception.vector == PF_VECTOR)
9003 kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
9004 else if (ctxt->exception.error_code_valid)
9005 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
9006 ctxt->exception.error_code);
9007 else
9008 kvm_queue_exception(vcpu, ctxt->exception.vector);
9009 }
9010
alloc_emulate_ctxt(struct kvm_vcpu * vcpu)9011 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
9012 {
9013 struct x86_emulate_ctxt *ctxt;
9014
9015 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
9016 if (!ctxt) {
9017 pr_err("failed to allocate vcpu's emulator\n");
9018 return NULL;
9019 }
9020
9021 ctxt->vcpu = vcpu;
9022 ctxt->ops = &emulate_ops;
9023 vcpu->arch.emulate_ctxt = ctxt;
9024
9025 return ctxt;
9026 }
9027
init_emulate_ctxt(struct kvm_vcpu * vcpu)9028 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
9029 {
9030 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9031 int cs_db, cs_l;
9032
9033 kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
9034
9035 ctxt->gpa_available = false;
9036 ctxt->eflags = kvm_get_rflags(vcpu);
9037 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
9038
9039 ctxt->eip = kvm_rip_read(vcpu);
9040 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
9041 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
9042 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
9043 cs_db ? X86EMUL_MODE_PROT32 :
9044 X86EMUL_MODE_PROT16;
9045 ctxt->interruptibility = 0;
9046 ctxt->have_exception = false;
9047 ctxt->exception.vector = -1;
9048 ctxt->perm_ok = false;
9049
9050 init_decode_cache(ctxt);
9051 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9052 }
9053
kvm_inject_realmode_interrupt(struct kvm_vcpu * vcpu,int irq,int inc_eip)9054 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
9055 {
9056 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9057 int ret;
9058
9059 init_emulate_ctxt(vcpu);
9060
9061 ctxt->op_bytes = 2;
9062 ctxt->ad_bytes = 2;
9063 ctxt->_eip = ctxt->eip + inc_eip;
9064 ret = emulate_int_real(ctxt, irq);
9065
9066 if (ret != X86EMUL_CONTINUE) {
9067 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
9068 } else {
9069 ctxt->eip = ctxt->_eip;
9070 kvm_rip_write(vcpu, ctxt->eip);
9071 kvm_set_rflags(vcpu, ctxt->eflags);
9072 }
9073 }
9074 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_realmode_interrupt);
9075
prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata,u8 * insn_bytes,u8 insn_size)9076 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
9077 u8 ndata, u8 *insn_bytes, u8 insn_size)
9078 {
9079 struct kvm_run *run = vcpu->run;
9080 u64 info[5];
9081 u8 info_start;
9082
9083 /*
9084 * Zero the whole array used to retrieve the exit info, as casting to
9085 * u32 for select entries will leave some chunks uninitialized.
9086 */
9087 memset(&info, 0, sizeof(info));
9088
9089 kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
9090 (u32 *)&info[3], (u32 *)&info[4]);
9091
9092 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9093 run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
9094
9095 /*
9096 * There's currently space for 13 entries, but 5 are used for the exit
9097 * reason and info. Restrict to 4 to reduce the maintenance burden
9098 * when expanding kvm_run.emulation_failure in the future.
9099 */
9100 if (WARN_ON_ONCE(ndata > 4))
9101 ndata = 4;
9102
9103 /* Always include the flags as a 'data' entry. */
9104 info_start = 1;
9105 run->emulation_failure.flags = 0;
9106
9107 if (insn_size) {
9108 BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
9109 sizeof(run->emulation_failure.insn_bytes) != 16));
9110 info_start += 2;
9111 run->emulation_failure.flags |=
9112 KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
9113 run->emulation_failure.insn_size = insn_size;
9114 memset(run->emulation_failure.insn_bytes, 0x90,
9115 sizeof(run->emulation_failure.insn_bytes));
9116 memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
9117 }
9118
9119 memcpy(&run->internal.data[info_start], info, sizeof(info));
9120 memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
9121 ndata * sizeof(data[0]));
9122
9123 run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
9124 }
9125
prepare_emulation_ctxt_failure_exit(struct kvm_vcpu * vcpu)9126 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
9127 {
9128 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9129
9130 prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
9131 ctxt->fetch.end - ctxt->fetch.data);
9132 }
9133
__kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata)9134 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
9135 u8 ndata)
9136 {
9137 prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
9138 }
9139 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_prepare_emulation_failure_exit);
9140
kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu)9141 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
9142 {
9143 __kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
9144 }
9145 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_emulation_failure_exit);
9146
kvm_prepare_event_vectoring_exit(struct kvm_vcpu * vcpu,gpa_t gpa)9147 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa)
9148 {
9149 u32 reason, intr_info, error_code;
9150 struct kvm_run *run = vcpu->run;
9151 u64 info1, info2;
9152 int ndata = 0;
9153
9154 kvm_x86_call(get_exit_info)(vcpu, &reason, &info1, &info2,
9155 &intr_info, &error_code);
9156
9157 run->internal.data[ndata++] = info2;
9158 run->internal.data[ndata++] = reason;
9159 run->internal.data[ndata++] = info1;
9160 run->internal.data[ndata++] = gpa;
9161 run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
9162
9163 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9164 run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
9165 run->internal.ndata = ndata;
9166 }
9167 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_event_vectoring_exit);
9168
kvm_prepare_unexpected_reason_exit(struct kvm_vcpu * vcpu,u64 exit_reason)9169 void kvm_prepare_unexpected_reason_exit(struct kvm_vcpu *vcpu, u64 exit_reason)
9170 {
9171 vcpu_unimpl(vcpu, "unexpected exit reason 0x%llx\n", exit_reason);
9172
9173 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9174 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
9175 vcpu->run->internal.ndata = 2;
9176 vcpu->run->internal.data[0] = exit_reason;
9177 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
9178 }
9179 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_unexpected_reason_exit);
9180
handle_emulation_failure(struct kvm_vcpu * vcpu,int emulation_type)9181 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
9182 {
9183 struct kvm *kvm = vcpu->kvm;
9184
9185 ++vcpu->stat.insn_emulation_fail;
9186 trace_kvm_emulate_insn_failed(vcpu);
9187
9188 if (emulation_type & EMULTYPE_VMWARE_GP) {
9189 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9190 return 1;
9191 }
9192
9193 if (kvm->arch.exit_on_emulation_error ||
9194 (emulation_type & EMULTYPE_SKIP)) {
9195 prepare_emulation_ctxt_failure_exit(vcpu);
9196 return 0;
9197 }
9198
9199 kvm_queue_exception(vcpu, UD_VECTOR);
9200
9201 if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
9202 prepare_emulation_ctxt_failure_exit(vcpu);
9203 return 0;
9204 }
9205
9206 return 1;
9207 }
9208
kvm_unprotect_and_retry_on_failure(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type)9209 static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
9210 gpa_t cr2_or_gpa,
9211 int emulation_type)
9212 {
9213 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
9214 return false;
9215
9216 /*
9217 * If the failed instruction faulted on an access to page tables that
9218 * are used to translate any part of the instruction, KVM can't resolve
9219 * the issue by unprotecting the gfn, as zapping the shadow page will
9220 * result in the instruction taking a !PRESENT page fault and thus put
9221 * the vCPU into an infinite loop of page faults. E.g. KVM will create
9222 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
9223 * then zap the SPTE to unprotect the gfn, and then do it all over
9224 * again. Report the error to userspace.
9225 */
9226 if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
9227 return false;
9228
9229 /*
9230 * If emulation may have been triggered by a write to a shadowed page
9231 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
9232 * guest to let the CPU re-execute the instruction in the hope that the
9233 * CPU can cleanly execute the instruction that KVM failed to emulate.
9234 */
9235 __kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
9236
9237 /*
9238 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
9239 * all SPTEs were already zapped by a different task. The alternative
9240 * is to report the error to userspace and likely terminate the guest,
9241 * and the last_retry_{eip,addr} checks will prevent retrying the page
9242 * fault indefinitely, i.e. there's nothing to lose by retrying.
9243 */
9244 return true;
9245 }
9246
9247 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
9248 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
9249
kvm_vcpu_check_hw_bp(unsigned long addr,u32 type,u32 dr7,unsigned long * db)9250 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
9251 unsigned long *db)
9252 {
9253 u32 dr6 = 0;
9254 int i;
9255 u32 enable, rwlen;
9256
9257 enable = dr7;
9258 rwlen = dr7 >> 16;
9259 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
9260 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
9261 dr6 |= (1 << i);
9262 return dr6;
9263 }
9264
kvm_vcpu_do_singlestep(struct kvm_vcpu * vcpu)9265 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
9266 {
9267 struct kvm_run *kvm_run = vcpu->run;
9268
9269 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
9270 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
9271 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
9272 kvm_run->debug.arch.exception = DB_VECTOR;
9273 kvm_run->exit_reason = KVM_EXIT_DEBUG;
9274 return 0;
9275 }
9276 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
9277 return 1;
9278 }
9279
kvm_skip_emulated_instruction(struct kvm_vcpu * vcpu)9280 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
9281 {
9282 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9283 int r;
9284
9285 r = kvm_x86_call(skip_emulated_instruction)(vcpu);
9286 if (unlikely(!r))
9287 return 0;
9288
9289 kvm_pmu_instruction_retired(vcpu);
9290
9291 /*
9292 * rflags is the old, "raw" value of the flags. The new value has
9293 * not been saved yet.
9294 *
9295 * This is correct even for TF set by the guest, because "the
9296 * processor will not generate this exception after the instruction
9297 * that sets the TF flag".
9298 */
9299 if (unlikely(rflags & X86_EFLAGS_TF))
9300 r = kvm_vcpu_do_singlestep(vcpu);
9301 return r;
9302 }
9303 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_skip_emulated_instruction);
9304
kvm_is_code_breakpoint_inhibited(struct kvm_vcpu * vcpu)9305 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
9306 {
9307 if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
9308 return true;
9309
9310 /*
9311 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
9312 * active, but AMD compatible CPUs do not.
9313 */
9314 if (!guest_cpuid_is_intel_compatible(vcpu))
9315 return false;
9316
9317 return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
9318 }
9319
kvm_vcpu_check_code_breakpoint(struct kvm_vcpu * vcpu,int emulation_type,int * r)9320 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
9321 int emulation_type, int *r)
9322 {
9323 WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
9324
9325 /*
9326 * Do not check for code breakpoints if hardware has already done the
9327 * checks, as inferred from the emulation type. On NO_DECODE and SKIP,
9328 * the instruction has passed all exception checks, and all intercepted
9329 * exceptions that trigger emulation have lower priority than code
9330 * breakpoints, i.e. the fact that the intercepted exception occurred
9331 * means any code breakpoints have already been serviced.
9332 *
9333 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
9334 * hardware has checked the RIP of the magic prefix, but not the RIP of
9335 * the instruction being emulated. The intent of forced emulation is
9336 * to behave as if KVM intercepted the instruction without an exception
9337 * and without a prefix.
9338 */
9339 if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
9340 EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
9341 return false;
9342
9343 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
9344 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
9345 struct kvm_run *kvm_run = vcpu->run;
9346 unsigned long eip = kvm_get_linear_rip(vcpu);
9347 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9348 vcpu->arch.guest_debug_dr7,
9349 vcpu->arch.eff_db);
9350
9351 if (dr6 != 0) {
9352 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
9353 kvm_run->debug.arch.pc = eip;
9354 kvm_run->debug.arch.exception = DB_VECTOR;
9355 kvm_run->exit_reason = KVM_EXIT_DEBUG;
9356 *r = 0;
9357 return true;
9358 }
9359 }
9360
9361 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
9362 !kvm_is_code_breakpoint_inhibited(vcpu)) {
9363 unsigned long eip = kvm_get_linear_rip(vcpu);
9364 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9365 vcpu->arch.dr7,
9366 vcpu->arch.db);
9367
9368 if (dr6 != 0) {
9369 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
9370 *r = 1;
9371 return true;
9372 }
9373 }
9374
9375 return false;
9376 }
9377
is_vmware_backdoor_opcode(struct x86_emulate_ctxt * ctxt)9378 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9379 {
9380 switch (ctxt->opcode_len) {
9381 case 1:
9382 switch (ctxt->b) {
9383 case 0xe4: /* IN */
9384 case 0xe5:
9385 case 0xec:
9386 case 0xed:
9387 case 0xe6: /* OUT */
9388 case 0xe7:
9389 case 0xee:
9390 case 0xef:
9391 case 0x6c: /* INS */
9392 case 0x6d:
9393 case 0x6e: /* OUTS */
9394 case 0x6f:
9395 return true;
9396 }
9397 break;
9398 case 2:
9399 switch (ctxt->b) {
9400 case 0x33: /* RDPMC */
9401 return true;
9402 }
9403 break;
9404 }
9405
9406 return false;
9407 }
9408
is_soft_int_instruction(struct x86_emulate_ctxt * ctxt,int emulation_type)9409 static bool is_soft_int_instruction(struct x86_emulate_ctxt *ctxt,
9410 int emulation_type)
9411 {
9412 u8 vector = EMULTYPE_GET_SOFT_INT_VECTOR(emulation_type);
9413
9414 switch (ctxt->b) {
9415 case 0xcc:
9416 return vector == BP_VECTOR;
9417 case 0xcd:
9418 return vector == ctxt->src.val;
9419 case 0xce:
9420 return vector == OF_VECTOR;
9421 default:
9422 return false;
9423 }
9424 }
9425
9426 /*
9427 * Decode an instruction for emulation. The caller is responsible for handling
9428 * code breakpoints. Note, manually detecting code breakpoints is unnecessary
9429 * (and wrong) when emulating on an intercepted fault-like exception[*], as
9430 * code breakpoints have higher priority and thus have already been done by
9431 * hardware.
9432 *
9433 * [*] Except #MC, which is higher priority, but KVM should never emulate in
9434 * response to a machine check.
9435 */
x86_decode_emulated_instruction(struct kvm_vcpu * vcpu,int emulation_type,void * insn,int insn_len)9436 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9437 void *insn, int insn_len)
9438 {
9439 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9440 int r;
9441
9442 init_emulate_ctxt(vcpu);
9443
9444 r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
9445
9446 trace_kvm_emulate_insn_start(vcpu);
9447 ++vcpu->stat.insn_emulation;
9448
9449 return r;
9450 }
9451 EXPORT_SYMBOL_FOR_KVM_INTERNAL(x86_decode_emulated_instruction);
9452
x86_emulate_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type,void * insn,int insn_len)9453 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9454 int emulation_type, void *insn, int insn_len)
9455 {
9456 int r;
9457 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9458 bool writeback = true;
9459
9460 if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9461 (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
9462 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
9463 emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
9464
9465 r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
9466 if (r != X86EMUL_CONTINUE) {
9467 if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9468 return 1;
9469
9470 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9471 emulation_type))
9472 return 1;
9473
9474 if (r == X86EMUL_UNHANDLEABLE_VECTORING) {
9475 kvm_prepare_event_vectoring_exit(vcpu, cr2_or_gpa);
9476 return 0;
9477 }
9478
9479 WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9480 return handle_emulation_failure(vcpu, emulation_type);
9481 }
9482
9483 kvm_request_l1tf_flush_l1d();
9484
9485 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
9486 kvm_clear_exception_queue(vcpu);
9487
9488 /*
9489 * Return immediately if RIP hits a code breakpoint, such #DBs
9490 * are fault-like and are higher priority than any faults on
9491 * the code fetch itself.
9492 */
9493 if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
9494 return r;
9495
9496 r = x86_decode_emulated_instruction(vcpu, emulation_type,
9497 insn, insn_len);
9498 if (r != EMULATION_OK) {
9499 if ((emulation_type & EMULTYPE_TRAP_UD) ||
9500 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9501 kvm_queue_exception(vcpu, UD_VECTOR);
9502 return 1;
9503 }
9504 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9505 emulation_type))
9506 return 1;
9507
9508 if (ctxt->have_exception &&
9509 !(emulation_type & EMULTYPE_SKIP)) {
9510 /*
9511 * #UD should result in just EMULATION_FAILED, and trap-like
9512 * exception should not be encountered during decode.
9513 */
9514 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9515 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
9516 inject_emulated_exception(vcpu);
9517 return 1;
9518 }
9519 return handle_emulation_failure(vcpu, emulation_type);
9520 }
9521 }
9522
9523 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9524 !is_vmware_backdoor_opcode(ctxt)) {
9525 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9526 return 1;
9527 }
9528
9529 /*
9530 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9531 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9532 * The caller is responsible for updating interruptibility state and
9533 * injecting single-step #DBs.
9534 */
9535 if (emulation_type & EMULTYPE_SKIP) {
9536 if (emulation_type & EMULTYPE_SKIP_SOFT_INT &&
9537 !is_soft_int_instruction(ctxt, emulation_type))
9538 return 0;
9539
9540 if (ctxt->mode != X86EMUL_MODE_PROT64)
9541 ctxt->eip = (u32)ctxt->_eip;
9542 else
9543 ctxt->eip = ctxt->_eip;
9544
9545 if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9546 r = 1;
9547 goto writeback;
9548 }
9549
9550 kvm_rip_write(vcpu, ctxt->eip);
9551 if (ctxt->eflags & X86_EFLAGS_RF)
9552 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
9553 return 1;
9554 }
9555
9556 /*
9557 * If emulation was caused by a write-protection #PF on a non-page_table
9558 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
9559 * and retry the instruction, as the vCPU is likely no longer using the
9560 * gfn as a page table.
9561 */
9562 if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9563 !x86_page_table_writing_insn(ctxt) &&
9564 kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
9565 return 1;
9566
9567 /* this is needed for vmware backdoor interface to work since it
9568 changes registers values during IO operation */
9569 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9570 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9571 emulator_invalidate_register_cache(ctxt);
9572 }
9573
9574 restart:
9575 if (emulation_type & EMULTYPE_PF) {
9576 /* Save the faulting GPA (cr2) in the address field */
9577 ctxt->exception.address = cr2_or_gpa;
9578
9579 /* With shadow page tables, cr2 contains a GVA or nGPA. */
9580 if (vcpu->arch.mmu->root_role.direct) {
9581 ctxt->gpa_available = true;
9582 ctxt->gpa_val = cr2_or_gpa;
9583 }
9584 } else {
9585 /* Sanitize the address out of an abundance of paranoia. */
9586 ctxt->exception.address = 0;
9587 }
9588
9589 /*
9590 * Check L1's instruction intercepts when emulating instructions for
9591 * L2, unless KVM is re-emulating a previously decoded instruction,
9592 * e.g. to complete userspace I/O, in which case KVM has already
9593 * checked the intercepts.
9594 */
9595 r = x86_emulate_insn(ctxt, is_guest_mode(vcpu) &&
9596 !(emulation_type & EMULTYPE_NO_DECODE));
9597
9598 if (r == EMULATION_INTERCEPTED)
9599 return 1;
9600
9601 if (r == EMULATION_FAILED) {
9602 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9603 emulation_type))
9604 return 1;
9605
9606 return handle_emulation_failure(vcpu, emulation_type);
9607 }
9608
9609 if (ctxt->have_exception) {
9610 WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9611 vcpu->mmio_needed = false;
9612 r = 1;
9613 inject_emulated_exception(vcpu);
9614 } else if (vcpu->arch.pio.count) {
9615 if (!vcpu->arch.pio.in) {
9616 /* FIXME: return into emulator if single-stepping. */
9617 vcpu->arch.pio.count = 0;
9618 } else {
9619 writeback = false;
9620 vcpu->arch.complete_userspace_io = complete_emulated_pio;
9621 }
9622 r = 0;
9623 } else if (vcpu->mmio_needed) {
9624 ++vcpu->stat.mmio_exits;
9625
9626 if (!vcpu->mmio_is_write)
9627 writeback = false;
9628 r = 0;
9629 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9630 } else if (vcpu->arch.complete_userspace_io) {
9631 writeback = false;
9632 r = 0;
9633 } else if (r == EMULATION_RESTART)
9634 goto restart;
9635 else
9636 r = 1;
9637
9638 writeback:
9639 if (writeback) {
9640 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9641 toggle_interruptibility(vcpu, ctxt->interruptibility);
9642 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9643
9644 /*
9645 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9646 * only supports code breakpoints and general detect #DB, both
9647 * of which are fault-like.
9648 */
9649 if (!ctxt->have_exception ||
9650 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9651 kvm_pmu_instruction_retired(vcpu);
9652 if (ctxt->is_branch)
9653 kvm_pmu_branch_retired(vcpu);
9654 kvm_rip_write(vcpu, ctxt->eip);
9655 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9656 r = kvm_vcpu_do_singlestep(vcpu);
9657 kvm_x86_call(update_emulated_instruction)(vcpu);
9658 __kvm_set_rflags(vcpu, ctxt->eflags);
9659 }
9660
9661 /*
9662 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9663 * do nothing, and it will be requested again as soon as
9664 * the shadow expires. But we still need to check here,
9665 * because POPF has no interrupt shadow.
9666 */
9667 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9668 kvm_make_request(KVM_REQ_EVENT, vcpu);
9669 } else
9670 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9671
9672 return r;
9673 }
9674
kvm_emulate_instruction(struct kvm_vcpu * vcpu,int emulation_type)9675 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9676 {
9677 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9678 }
9679 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction);
9680
kvm_emulate_instruction_from_buffer(struct kvm_vcpu * vcpu,void * insn,int insn_len)9681 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9682 void *insn, int insn_len)
9683 {
9684 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9685 }
9686 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction_from_buffer);
9687
complete_fast_pio_out_port_0x7e(struct kvm_vcpu * vcpu)9688 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9689 {
9690 vcpu->arch.pio.count = 0;
9691 return 1;
9692 }
9693
complete_fast_pio_out(struct kvm_vcpu * vcpu)9694 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9695 {
9696 vcpu->arch.pio.count = 0;
9697
9698 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip)))
9699 return 1;
9700
9701 return kvm_skip_emulated_instruction(vcpu);
9702 }
9703
kvm_fast_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port)9704 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9705 unsigned short port)
9706 {
9707 unsigned long val = kvm_rax_read(vcpu);
9708 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9709
9710 if (ret)
9711 return ret;
9712
9713 /*
9714 * Workaround userspace that relies on old KVM behavior of %rip being
9715 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9716 */
9717 if (port == 0x7e &&
9718 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9719 vcpu->arch.complete_userspace_io =
9720 complete_fast_pio_out_port_0x7e;
9721 kvm_skip_emulated_instruction(vcpu);
9722 } else {
9723 vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9724 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9725 }
9726 return 0;
9727 }
9728
complete_fast_pio_in(struct kvm_vcpu * vcpu)9729 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9730 {
9731 unsigned long val;
9732
9733 /* We should only ever be called with arch.pio.count equal to 1 */
9734 if (KVM_BUG_ON(vcpu->arch.pio.count != 1, vcpu->kvm))
9735 return -EIO;
9736
9737 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip))) {
9738 vcpu->arch.pio.count = 0;
9739 return 1;
9740 }
9741
9742 /* For size less than 4 we merge, else we zero extend */
9743 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9744
9745 complete_emulator_pio_in(vcpu, &val);
9746 kvm_rax_write(vcpu, val);
9747
9748 return kvm_skip_emulated_instruction(vcpu);
9749 }
9750
kvm_fast_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port)9751 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9752 unsigned short port)
9753 {
9754 unsigned long val;
9755 int ret;
9756
9757 /* For size less than 4 we merge, else we zero extend */
9758 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9759
9760 ret = emulator_pio_in(vcpu, size, port, &val, 1);
9761 if (ret) {
9762 kvm_rax_write(vcpu, val);
9763 return ret;
9764 }
9765
9766 vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9767 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9768
9769 return 0;
9770 }
9771
kvm_fast_pio(struct kvm_vcpu * vcpu,int size,unsigned short port,int in)9772 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9773 {
9774 int ret;
9775
9776 if (in)
9777 ret = kvm_fast_pio_in(vcpu, size, port);
9778 else
9779 ret = kvm_fast_pio_out(vcpu, size, port);
9780 return ret && kvm_skip_emulated_instruction(vcpu);
9781 }
9782 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fast_pio);
9783
kvmclock_cpu_down_prep(unsigned int cpu)9784 static int kvmclock_cpu_down_prep(unsigned int cpu)
9785 {
9786 __this_cpu_write(cpu_tsc_khz, 0);
9787 return 0;
9788 }
9789
tsc_khz_changed(void * data)9790 static void tsc_khz_changed(void *data)
9791 {
9792 struct cpufreq_freqs *freq = data;
9793 unsigned long khz;
9794
9795 WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9796
9797 if (data)
9798 khz = freq->new;
9799 else
9800 khz = cpufreq_quick_get(raw_smp_processor_id());
9801 if (!khz)
9802 khz = tsc_khz;
9803 __this_cpu_write(cpu_tsc_khz, khz);
9804 }
9805
9806 #ifdef CONFIG_X86_64
kvm_hyperv_tsc_notifier(void)9807 static void kvm_hyperv_tsc_notifier(void)
9808 {
9809 struct kvm *kvm;
9810 int cpu;
9811
9812 mutex_lock(&kvm_lock);
9813 list_for_each_entry(kvm, &vm_list, vm_list)
9814 kvm_make_mclock_inprogress_request(kvm);
9815
9816 /* no guest entries from this point */
9817 hyperv_stop_tsc_emulation();
9818
9819 /* TSC frequency always matches when on Hyper-V */
9820 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9821 for_each_present_cpu(cpu)
9822 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9823 }
9824 kvm_caps.max_guest_tsc_khz = tsc_khz;
9825
9826 list_for_each_entry(kvm, &vm_list, vm_list) {
9827 __kvm_start_pvclock_update(kvm);
9828 pvclock_update_vm_gtod_copy(kvm);
9829 kvm_end_pvclock_update(kvm);
9830 }
9831
9832 mutex_unlock(&kvm_lock);
9833 }
9834 #endif
9835
__kvmclock_cpufreq_notifier(struct cpufreq_freqs * freq,int cpu)9836 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9837 {
9838 struct kvm *kvm;
9839 struct kvm_vcpu *vcpu;
9840 int send_ipi = 0;
9841 unsigned long i;
9842
9843 /*
9844 * We allow guests to temporarily run on slowing clocks,
9845 * provided we notify them after, or to run on accelerating
9846 * clocks, provided we notify them before. Thus time never
9847 * goes backwards.
9848 *
9849 * However, we have a problem. We can't atomically update
9850 * the frequency of a given CPU from this function; it is
9851 * merely a notifier, which can be called from any CPU.
9852 * Changing the TSC frequency at arbitrary points in time
9853 * requires a recomputation of local variables related to
9854 * the TSC for each VCPU. We must flag these local variables
9855 * to be updated and be sure the update takes place with the
9856 * new frequency before any guests proceed.
9857 *
9858 * Unfortunately, the combination of hotplug CPU and frequency
9859 * change creates an intractable locking scenario; the order
9860 * of when these callouts happen is undefined with respect to
9861 * CPU hotplug, and they can race with each other. As such,
9862 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9863 * undefined; you can actually have a CPU frequency change take
9864 * place in between the computation of X and the setting of the
9865 * variable. To protect against this problem, all updates of
9866 * the per_cpu tsc_khz variable are done in an interrupt
9867 * protected IPI, and all callers wishing to update the value
9868 * must wait for a synchronous IPI to complete (which is trivial
9869 * if the caller is on the CPU already). This establishes the
9870 * necessary total order on variable updates.
9871 *
9872 * Note that because a guest time update may take place
9873 * anytime after the setting of the VCPU's request bit, the
9874 * correct TSC value must be set before the request. However,
9875 * to ensure the update actually makes it to any guest which
9876 * starts running in hardware virtualization between the set
9877 * and the acquisition of the spinlock, we must also ping the
9878 * CPU after setting the request bit.
9879 *
9880 */
9881
9882 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9883
9884 mutex_lock(&kvm_lock);
9885 list_for_each_entry(kvm, &vm_list, vm_list) {
9886 kvm_for_each_vcpu(i, vcpu, kvm) {
9887 if (vcpu->cpu != cpu)
9888 continue;
9889 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9890 if (vcpu->cpu != raw_smp_processor_id())
9891 send_ipi = 1;
9892 }
9893 }
9894 mutex_unlock(&kvm_lock);
9895
9896 if (freq->old < freq->new && send_ipi) {
9897 /*
9898 * We upscale the frequency. Must make the guest
9899 * doesn't see old kvmclock values while running with
9900 * the new frequency, otherwise we risk the guest sees
9901 * time go backwards.
9902 *
9903 * In case we update the frequency for another cpu
9904 * (which might be in guest context) send an interrupt
9905 * to kick the cpu out of guest context. Next time
9906 * guest context is entered kvmclock will be updated,
9907 * so the guest will not see stale values.
9908 */
9909 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9910 }
9911 }
9912
kvmclock_cpufreq_notifier(struct notifier_block * nb,unsigned long val,void * data)9913 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9914 void *data)
9915 {
9916 struct cpufreq_freqs *freq = data;
9917 int cpu;
9918
9919 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9920 return 0;
9921 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9922 return 0;
9923
9924 for_each_cpu(cpu, freq->policy->cpus)
9925 __kvmclock_cpufreq_notifier(freq, cpu);
9926
9927 return 0;
9928 }
9929
9930 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9931 .notifier_call = kvmclock_cpufreq_notifier
9932 };
9933
kvmclock_cpu_online(unsigned int cpu)9934 static int kvmclock_cpu_online(unsigned int cpu)
9935 {
9936 tsc_khz_changed(NULL);
9937 return 0;
9938 }
9939
kvm_timer_init(void)9940 static void kvm_timer_init(void)
9941 {
9942 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9943 max_tsc_khz = tsc_khz;
9944
9945 if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9946 struct cpufreq_policy *policy;
9947 int cpu;
9948
9949 cpu = get_cpu();
9950 policy = cpufreq_cpu_get(cpu);
9951 if (policy) {
9952 if (policy->cpuinfo.max_freq)
9953 max_tsc_khz = policy->cpuinfo.max_freq;
9954 cpufreq_cpu_put(policy);
9955 }
9956 put_cpu();
9957 }
9958 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9959 CPUFREQ_TRANSITION_NOTIFIER);
9960
9961 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9962 kvmclock_cpu_online, kvmclock_cpu_down_prep);
9963 }
9964 }
9965
9966 #ifdef CONFIG_X86_64
pvclock_gtod_update_fn(struct work_struct * work)9967 static void pvclock_gtod_update_fn(struct work_struct *work)
9968 {
9969 struct kvm *kvm;
9970 struct kvm_vcpu *vcpu;
9971 unsigned long i;
9972
9973 mutex_lock(&kvm_lock);
9974 list_for_each_entry(kvm, &vm_list, vm_list)
9975 kvm_for_each_vcpu(i, vcpu, kvm)
9976 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9977 atomic_set(&kvm_guest_has_master_clock, 0);
9978 mutex_unlock(&kvm_lock);
9979 }
9980
9981 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9982
9983 /*
9984 * Indirection to move queue_work() out of the tk_core.seq write held
9985 * region to prevent possible deadlocks against time accessors which
9986 * are invoked with work related locks held.
9987 */
pvclock_irq_work_fn(struct irq_work * w)9988 static void pvclock_irq_work_fn(struct irq_work *w)
9989 {
9990 queue_work(system_long_wq, &pvclock_gtod_work);
9991 }
9992
9993 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9994
9995 /*
9996 * Notification about pvclock gtod data update.
9997 */
pvclock_gtod_notify(struct notifier_block * nb,unsigned long unused,void * priv)9998 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9999 void *priv)
10000 {
10001 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
10002 struct timekeeper *tk = priv;
10003
10004 update_pvclock_gtod(tk);
10005
10006 /*
10007 * Disable master clock if host does not trust, or does not use,
10008 * TSC based clocksource. Delegate queue_work() to irq_work as
10009 * this is invoked with tk_core.seq write held.
10010 */
10011 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
10012 atomic_read(&kvm_guest_has_master_clock) != 0)
10013 irq_work_queue(&pvclock_irq_work);
10014 return 0;
10015 }
10016
10017 static struct notifier_block pvclock_gtod_notifier = {
10018 .notifier_call = pvclock_gtod_notify,
10019 };
10020 #endif
10021
kvm_setup_xss_caps(void)10022 void kvm_setup_xss_caps(void)
10023 {
10024 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
10025 kvm_caps.supported_xss = 0;
10026
10027 if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
10028 !kvm_cpu_cap_has(X86_FEATURE_IBT))
10029 kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
10030
10031 if ((kvm_caps.supported_xss & XFEATURE_MASK_CET_ALL) != XFEATURE_MASK_CET_ALL) {
10032 kvm_cpu_cap_clear(X86_FEATURE_SHSTK);
10033 kvm_cpu_cap_clear(X86_FEATURE_IBT);
10034 kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
10035 }
10036 }
10037 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_setup_xss_caps);
10038
kvm_setup_efer_caps(void)10039 static void kvm_setup_efer_caps(void)
10040 {
10041 if (kvm_cpu_cap_has(X86_FEATURE_NX))
10042 kvm_enable_efer_bits(EFER_NX);
10043
10044 if (kvm_cpu_cap_has(X86_FEATURE_FXSR_OPT))
10045 kvm_enable_efer_bits(EFER_FFXSR);
10046
10047 if (kvm_cpu_cap_has(X86_FEATURE_AUTOIBRS))
10048 kvm_enable_efer_bits(EFER_AUTOIBRS);
10049 }
10050
kvm_ops_update(struct kvm_x86_init_ops * ops)10051 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
10052 {
10053 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
10054
10055 #define __KVM_X86_OP(func) \
10056 static_call_update(kvm_x86_##func, kvm_x86_ops.func);
10057 #define KVM_X86_OP(func) \
10058 WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
10059 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
10060 #define KVM_X86_OP_OPTIONAL_RET0(func) \
10061 static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
10062 (void *)__static_call_return0);
10063 #include <asm/kvm-x86-ops.h>
10064 #undef __KVM_X86_OP
10065
10066 kvm_pmu_ops_update(ops->pmu_ops);
10067 }
10068
kvm_x86_check_processor_compatibility(void)10069 static int kvm_x86_check_processor_compatibility(void)
10070 {
10071 int cpu = smp_processor_id();
10072 struct cpuinfo_x86 *c = &cpu_data(cpu);
10073
10074 /*
10075 * Compatibility checks are done when loading KVM and when enabling
10076 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
10077 * compatible, i.e. KVM should never perform a compatibility check on
10078 * an offline CPU.
10079 */
10080 WARN_ON(!cpu_online(cpu));
10081
10082 if (__cr4_reserved_bits(cpu_has, c) !=
10083 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
10084 return -EIO;
10085
10086 return kvm_x86_call(check_processor_compatibility)();
10087 }
10088
kvm_x86_check_cpu_compat(void * ret)10089 static void kvm_x86_check_cpu_compat(void *ret)
10090 {
10091 *(int *)ret = kvm_x86_check_processor_compatibility();
10092 }
10093
kvm_x86_vendor_init(struct kvm_x86_init_ops * ops)10094 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
10095 {
10096 u64 host_pat;
10097 int r, cpu;
10098
10099 guard(mutex)(&vendor_module_lock);
10100
10101 if (kvm_x86_ops.enable_virtualization_cpu) {
10102 pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
10103 return -EEXIST;
10104 }
10105
10106 /*
10107 * KVM explicitly assumes that the guest has an FPU and
10108 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
10109 * vCPU's FPU state as a fxregs_state struct.
10110 */
10111 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
10112 pr_err("inadequate fpu\n");
10113 return -EOPNOTSUPP;
10114 }
10115
10116 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
10117 pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
10118 return -EOPNOTSUPP;
10119 }
10120
10121 /*
10122 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
10123 * the PAT bits in SPTEs. Bail if PAT[0] is programmed to something
10124 * other than WB. Note, EPT doesn't utilize the PAT, but don't bother
10125 * with an exception. PAT[0] is set to WB on RESET and also by the
10126 * kernel, i.e. failure indicates a kernel bug or broken firmware.
10127 */
10128 if (rdmsrq_safe(MSR_IA32_CR_PAT, &host_pat) ||
10129 (host_pat & GENMASK(2, 0)) != 6) {
10130 pr_err("host PAT[0] is not WB\n");
10131 return -EIO;
10132 }
10133
10134 if (boot_cpu_has(X86_FEATURE_SHSTK) || boot_cpu_has(X86_FEATURE_IBT)) {
10135 rdmsrq(MSR_IA32_S_CET, kvm_host.s_cet);
10136 /*
10137 * Linux doesn't yet support supervisor shadow stacks (SSS), so
10138 * KVM doesn't save/restore the associated MSRs, i.e. KVM may
10139 * clobber the host values. Yell and refuse to load if SSS is
10140 * unexpectedly enabled, e.g. to avoid crashing the host.
10141 */
10142 if (WARN_ON_ONCE(kvm_host.s_cet & CET_SHSTK_EN))
10143 return -EIO;
10144 }
10145
10146 memset(&kvm_caps, 0, sizeof(kvm_caps));
10147
10148 x86_emulator_cache = kvm_alloc_emulator_cache();
10149 if (!x86_emulator_cache) {
10150 pr_err("failed to allocate cache for x86 emulator\n");
10151 return -ENOMEM;
10152 }
10153
10154 r = kvm_mmu_vendor_module_init();
10155 if (r)
10156 goto out_free_x86_emulator_cache;
10157
10158 kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
10159 kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
10160
10161 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
10162 kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
10163 kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
10164 }
10165
10166 if (boot_cpu_has(X86_FEATURE_XSAVES)) {
10167 rdmsrq(MSR_IA32_XSS, kvm_host.xss);
10168 kvm_caps.supported_xss = kvm_host.xss & KVM_SUPPORTED_XSS;
10169 }
10170
10171 kvm_caps.supported_quirks = KVM_X86_VALID_QUIRKS;
10172 kvm_caps.inapplicable_quirks = KVM_X86_CONDITIONAL_QUIRKS;
10173
10174 rdmsrq_safe(MSR_EFER, &kvm_host.efer);
10175
10176 kvm_init_pmu_capability(ops->pmu_ops);
10177
10178 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
10179 rdmsrq(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
10180
10181 WARN_ON_ONCE(kvm_nr_uret_msrs);
10182
10183 r = ops->hardware_setup();
10184 if (r != 0)
10185 goto out_mmu_exit;
10186
10187 kvm_setup_efer_caps();
10188
10189 enable_device_posted_irqs &= enable_apicv &&
10190 irq_remapping_cap(IRQ_POSTING_CAP);
10191
10192 kvm_ops_update(ops);
10193
10194 for_each_online_cpu(cpu) {
10195 smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
10196 if (r < 0)
10197 goto out_unwind_ops;
10198 }
10199
10200 /*
10201 * Point of no return! DO NOT add error paths below this point unless
10202 * absolutely necessary, as most operations from this point forward
10203 * require unwinding.
10204 */
10205 kvm_timer_init();
10206
10207 if (pi_inject_timer == -1)
10208 pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
10209 #ifdef CONFIG_X86_64
10210 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
10211
10212 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
10213 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
10214 #endif
10215
10216 __kvm_register_perf_callbacks(ops->handle_intel_pt_intr,
10217 enable_mediated_pmu ? kvm_handle_guest_mediated_pmi : NULL);
10218
10219 if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
10220 kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
10221
10222 /* KVM always ignores guest PAT for shadow paging. */
10223 if (!tdp_enabled)
10224 kvm_caps.supported_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT;
10225
10226 if (kvm_caps.has_tsc_control) {
10227 /*
10228 * Make sure the user can only configure tsc_khz values that
10229 * fit into a signed integer.
10230 * A min value is not calculated because it will always
10231 * be 1 on all machines.
10232 */
10233 u64 max = min(0x7fffffffULL,
10234 __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
10235 kvm_caps.max_guest_tsc_khz = max;
10236 }
10237 kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
10238 kvm_init_msr_lists();
10239 return 0;
10240
10241 out_unwind_ops:
10242 kvm_x86_ops.enable_virtualization_cpu = NULL;
10243 kvm_x86_call(hardware_unsetup)();
10244 out_mmu_exit:
10245 kvm_destroy_user_return_msrs();
10246 kvm_mmu_vendor_module_exit();
10247 out_free_x86_emulator_cache:
10248 kmem_cache_destroy(x86_emulator_cache);
10249 return r;
10250 }
10251 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_init);
10252
kvm_x86_vendor_exit(void)10253 void kvm_x86_vendor_exit(void)
10254 {
10255 kvm_unregister_perf_callbacks();
10256
10257 #ifdef CONFIG_X86_64
10258 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
10259 clear_hv_tscchange_cb();
10260 #endif
10261 kvm_lapic_exit();
10262
10263 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
10264 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
10265 CPUFREQ_TRANSITION_NOTIFIER);
10266 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
10267 }
10268 #ifdef CONFIG_X86_64
10269 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
10270 irq_work_sync(&pvclock_irq_work);
10271 cancel_work_sync(&pvclock_gtod_work);
10272 #endif
10273 kvm_x86_call(hardware_unsetup)();
10274 kvm_destroy_user_return_msrs();
10275 kvm_mmu_vendor_module_exit();
10276 kmem_cache_destroy(x86_emulator_cache);
10277 #ifdef CONFIG_KVM_XEN
10278 static_key_deferred_flush(&kvm_xen_enabled);
10279 WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
10280 #endif
10281 mutex_lock(&vendor_module_lock);
10282 kvm_x86_ops.enable_virtualization_cpu = NULL;
10283 mutex_unlock(&vendor_module_lock);
10284 }
10285 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_exit);
10286
10287 #ifdef CONFIG_X86_64
kvm_pv_clock_pairing(struct kvm_vcpu * vcpu,gpa_t paddr,unsigned long clock_type)10288 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
10289 unsigned long clock_type)
10290 {
10291 struct kvm_clock_pairing clock_pairing;
10292 struct timespec64 ts;
10293 u64 cycle;
10294 int ret;
10295
10296 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
10297 return -KVM_EOPNOTSUPP;
10298
10299 /*
10300 * When tsc is in permanent catchup mode guests won't be able to use
10301 * pvclock_read_retry loop to get consistent view of pvclock
10302 */
10303 if (vcpu->arch.tsc_always_catchup)
10304 return -KVM_EOPNOTSUPP;
10305
10306 if (!kvm_get_walltime_and_clockread(&ts, &cycle))
10307 return -KVM_EOPNOTSUPP;
10308
10309 clock_pairing.sec = ts.tv_sec;
10310 clock_pairing.nsec = ts.tv_nsec;
10311 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
10312 clock_pairing.flags = 0;
10313 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
10314
10315 ret = 0;
10316 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
10317 sizeof(struct kvm_clock_pairing)))
10318 ret = -KVM_EFAULT;
10319
10320 return ret;
10321 }
10322 #endif
10323
10324 /*
10325 * kvm_pv_kick_cpu_op: Kick a vcpu.
10326 *
10327 * @apicid - apicid of vcpu to be kicked.
10328 */
kvm_pv_kick_cpu_op(struct kvm * kvm,int apicid)10329 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
10330 {
10331 /*
10332 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
10333 * common code, e.g. for tracing. Defer initialization to the compiler.
10334 */
10335 struct kvm_lapic_irq lapic_irq = {
10336 .delivery_mode = APIC_DM_REMRD,
10337 .dest_mode = APIC_DEST_PHYSICAL,
10338 .shorthand = APIC_DEST_NOSHORT,
10339 .dest_id = apicid,
10340 };
10341
10342 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq);
10343 }
10344
kvm_apicv_activated(struct kvm * kvm)10345 bool kvm_apicv_activated(struct kvm *kvm)
10346 {
10347 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
10348 }
10349 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_apicv_activated);
10350
kvm_vcpu_apicv_activated(struct kvm_vcpu * vcpu)10351 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
10352 {
10353 ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
10354 ulong vcpu_reasons =
10355 kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
10356
10357 return (vm_reasons | vcpu_reasons) == 0;
10358 }
10359 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_apicv_activated);
10360
set_or_clear_apicv_inhibit(unsigned long * inhibits,enum kvm_apicv_inhibit reason,bool set)10361 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
10362 enum kvm_apicv_inhibit reason, bool set)
10363 {
10364 const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
10365
10366 BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
10367
10368 if (set)
10369 __set_bit(reason, inhibits);
10370 else
10371 __clear_bit(reason, inhibits);
10372
10373 trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
10374 }
10375
kvm_apicv_init(struct kvm * kvm)10376 static void kvm_apicv_init(struct kvm *kvm)
10377 {
10378 enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
10379 APICV_INHIBIT_REASON_DISABLED;
10380
10381 set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
10382
10383 init_rwsem(&kvm->arch.apicv_update_lock);
10384 }
10385
kvm_sched_yield(struct kvm_vcpu * vcpu,unsigned long dest_id)10386 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
10387 {
10388 struct kvm_vcpu *target = NULL;
10389 struct kvm_apic_map *map;
10390
10391 vcpu->stat.directed_yield_attempted++;
10392
10393 if (single_task_running())
10394 goto no_yield;
10395
10396 rcu_read_lock();
10397 map = rcu_dereference(vcpu->kvm->arch.apic_map);
10398
10399 if (likely(map) && dest_id <= map->max_apic_id) {
10400 dest_id = array_index_nospec(dest_id, map->max_apic_id + 1);
10401 if (map->phys_map[dest_id])
10402 target = map->phys_map[dest_id]->vcpu;
10403 }
10404
10405 rcu_read_unlock();
10406
10407 if (!target || !READ_ONCE(target->ready))
10408 goto no_yield;
10409
10410 /* Ignore requests to yield to self */
10411 if (vcpu == target)
10412 goto no_yield;
10413
10414 if (kvm_vcpu_yield_to(target) <= 0)
10415 goto no_yield;
10416
10417 vcpu->stat.directed_yield_successful++;
10418
10419 no_yield:
10420 return;
10421 }
10422
complete_hypercall_exit(struct kvm_vcpu * vcpu)10423 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
10424 {
10425 u64 ret = vcpu->run->hypercall.ret;
10426
10427 if (!is_64_bit_hypercall(vcpu))
10428 ret = (u32)ret;
10429 kvm_rax_write(vcpu, ret);
10430 return kvm_skip_emulated_instruction(vcpu);
10431 }
10432
____kvm_emulate_hypercall(struct kvm_vcpu * vcpu,int cpl,int (* complete_hypercall)(struct kvm_vcpu *))10433 int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
10434 int (*complete_hypercall)(struct kvm_vcpu *))
10435 {
10436 unsigned long ret;
10437 unsigned long nr = kvm_rax_read(vcpu);
10438 unsigned long a0 = kvm_rbx_read(vcpu);
10439 unsigned long a1 = kvm_rcx_read(vcpu);
10440 unsigned long a2 = kvm_rdx_read(vcpu);
10441 unsigned long a3 = kvm_rsi_read(vcpu);
10442 int op_64_bit = is_64_bit_hypercall(vcpu);
10443
10444 ++vcpu->stat.hypercalls;
10445
10446 trace_kvm_hypercall(nr, a0, a1, a2, a3);
10447
10448 if (!op_64_bit) {
10449 nr &= 0xFFFFFFFF;
10450 a0 &= 0xFFFFFFFF;
10451 a1 &= 0xFFFFFFFF;
10452 a2 &= 0xFFFFFFFF;
10453 a3 &= 0xFFFFFFFF;
10454 }
10455
10456 if (cpl) {
10457 ret = -KVM_EPERM;
10458 goto out;
10459 }
10460
10461 ret = -KVM_ENOSYS;
10462
10463 switch (nr) {
10464 case KVM_HC_VAPIC_POLL_IRQ:
10465 ret = 0;
10466 break;
10467 case KVM_HC_KICK_CPU:
10468 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10469 break;
10470
10471 kvm_pv_kick_cpu_op(vcpu->kvm, a1);
10472 kvm_sched_yield(vcpu, a1);
10473 ret = 0;
10474 break;
10475 #ifdef CONFIG_X86_64
10476 case KVM_HC_CLOCK_PAIRING:
10477 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10478 break;
10479 #endif
10480 case KVM_HC_SEND_IPI:
10481 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10482 break;
10483
10484 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10485 break;
10486 case KVM_HC_SCHED_YIELD:
10487 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10488 break;
10489
10490 kvm_sched_yield(vcpu, a0);
10491 ret = 0;
10492 break;
10493 case KVM_HC_MAP_GPA_RANGE: {
10494 u64 gpa = a0, npages = a1, attrs = a2;
10495
10496 ret = -KVM_ENOSYS;
10497 if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE))
10498 break;
10499
10500 if (!PAGE_ALIGNED(gpa) || !npages ||
10501 gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10502 ret = -KVM_EINVAL;
10503 break;
10504 }
10505
10506 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
10507 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
10508 /*
10509 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
10510 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
10511 * it was always zero on KVM_EXIT_HYPERCALL. Since KVM is now overwriting
10512 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
10513 */
10514 vcpu->run->hypercall.ret = 0;
10515 vcpu->run->hypercall.args[0] = gpa;
10516 vcpu->run->hypercall.args[1] = npages;
10517 vcpu->run->hypercall.args[2] = attrs;
10518 vcpu->run->hypercall.flags = 0;
10519 if (op_64_bit)
10520 vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10521
10522 WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
10523 vcpu->arch.complete_userspace_io = complete_hypercall;
10524 return 0;
10525 }
10526 default:
10527 ret = -KVM_ENOSYS;
10528 break;
10529 }
10530
10531 out:
10532 vcpu->run->hypercall.ret = ret;
10533 return 1;
10534 }
10535 EXPORT_SYMBOL_FOR_KVM_INTERNAL(____kvm_emulate_hypercall);
10536
kvm_emulate_hypercall(struct kvm_vcpu * vcpu)10537 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10538 {
10539 if (kvm_xen_hypercall_enabled(vcpu->kvm))
10540 return kvm_xen_hypercall(vcpu);
10541
10542 if (kvm_hv_hypercall_enabled(vcpu))
10543 return kvm_hv_hypercall(vcpu);
10544
10545 return __kvm_emulate_hypercall(vcpu, kvm_x86_call(get_cpl)(vcpu),
10546 complete_hypercall_exit);
10547 }
10548 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_hypercall);
10549
emulator_fix_hypercall(struct x86_emulate_ctxt * ctxt)10550 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
10551 {
10552 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
10553 char instruction[3];
10554 unsigned long rip = kvm_rip_read(vcpu);
10555
10556 /*
10557 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10558 * the pieces.
10559 */
10560 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10561 ctxt->exception.error_code_valid = false;
10562 ctxt->exception.vector = UD_VECTOR;
10563 ctxt->have_exception = true;
10564 return X86EMUL_PROPAGATE_FAULT;
10565 }
10566
10567 kvm_x86_call(patch_hypercall)(vcpu, instruction);
10568
10569 return emulator_write_emulated(ctxt, rip, instruction, 3,
10570 &ctxt->exception);
10571 }
10572
dm_request_for_irq_injection(struct kvm_vcpu * vcpu)10573 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
10574 {
10575 return vcpu->run->request_interrupt_window &&
10576 likely(!pic_in_kernel(vcpu->kvm));
10577 }
10578
10579 /* Called within kvm->srcu read side. */
post_kvm_run_save(struct kvm_vcpu * vcpu)10580 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
10581 {
10582 struct kvm_run *kvm_run = vcpu->run;
10583
10584 kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
10585 kvm_run->cr8 = kvm_get_cr8(vcpu);
10586 kvm_run->apic_base = vcpu->arch.apic_base;
10587
10588 kvm_run->ready_for_interrupt_injection =
10589 pic_in_kernel(vcpu->kvm) ||
10590 kvm_vcpu_ready_for_interrupt_injection(vcpu);
10591
10592 if (is_smm(vcpu))
10593 kvm_run->flags |= KVM_RUN_X86_SMM;
10594 if (is_guest_mode(vcpu))
10595 kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
10596 }
10597
update_cr8_intercept(struct kvm_vcpu * vcpu)10598 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10599 {
10600 int max_irr, tpr;
10601
10602 if (!kvm_x86_ops.update_cr8_intercept)
10603 return;
10604
10605 if (!lapic_in_kernel(vcpu))
10606 return;
10607
10608 if (vcpu->arch.apic->apicv_active)
10609 return;
10610
10611 if (!vcpu->arch.apic->vapic_addr)
10612 max_irr = kvm_lapic_find_highest_irr(vcpu);
10613 else
10614 max_irr = -1;
10615
10616 if (max_irr != -1)
10617 max_irr >>= 4;
10618
10619 tpr = kvm_lapic_get_cr8(vcpu);
10620
10621 kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
10622 }
10623
10624
kvm_check_nested_events(struct kvm_vcpu * vcpu)10625 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10626 {
10627 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10628 kvm_x86_ops.nested_ops->triple_fault(vcpu);
10629 return 1;
10630 }
10631
10632 return kvm_x86_ops.nested_ops->check_events(vcpu);
10633 }
10634
kvm_inject_exception(struct kvm_vcpu * vcpu)10635 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10636 {
10637 /*
10638 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10639 * exceptions don't report error codes. The presence of an error code
10640 * is carried with the exception and only stripped when the exception
10641 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10642 * report an error code despite the CPU being in Real Mode.
10643 */
10644 vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10645
10646 trace_kvm_inj_exception(vcpu->arch.exception.vector,
10647 vcpu->arch.exception.has_error_code,
10648 vcpu->arch.exception.error_code,
10649 vcpu->arch.exception.injected);
10650
10651 kvm_x86_call(inject_exception)(vcpu);
10652 }
10653
10654 /*
10655 * Check for any event (interrupt or exception) that is ready to be injected,
10656 * and if there is at least one event, inject the event with the highest
10657 * priority. This handles both "pending" events, i.e. events that have never
10658 * been injected into the guest, and "injected" events, i.e. events that were
10659 * injected as part of a previous VM-Enter, but weren't successfully delivered
10660 * and need to be re-injected.
10661 *
10662 * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10663 * i.e. doesn't guarantee that there's an event window in the guest. KVM must
10664 * be able to inject exceptions in the "middle" of an instruction, and so must
10665 * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10666 * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10667 * boundaries is necessary and correct.
10668 *
10669 * For simplicity, KVM uses a single path to inject all events (except events
10670 * that are injected directly from L1 to L2) and doesn't explicitly track
10671 * instruction boundaries for asynchronous events. However, because VM-Exits
10672 * that can occur during instruction execution typically result in KVM skipping
10673 * the instruction or injecting an exception, e.g. instruction and exception
10674 * intercepts, and because pending exceptions have higher priority than pending
10675 * interrupts, KVM still honors instruction boundaries in most scenarios.
10676 *
10677 * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10678 * the instruction or inject an exception, then KVM can incorrecty inject a new
10679 * asynchronous event if the event became pending after the CPU fetched the
10680 * instruction (in the guest). E.g. if a page fault (#PF, #NPF, EPT violation)
10681 * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10682 * injected on the restarted instruction instead of being deferred until the
10683 * instruction completes.
10684 *
10685 * In practice, this virtualization hole is unlikely to be observed by the
10686 * guest, and even less likely to cause functional problems. To detect the
10687 * hole, the guest would have to trigger an event on a side effect of an early
10688 * phase of instruction execution, e.g. on the instruction fetch from memory.
10689 * And for it to be a functional problem, the guest would need to depend on the
10690 * ordering between that side effect, the instruction completing, _and_ the
10691 * delivery of the asynchronous event.
10692 */
kvm_check_and_inject_events(struct kvm_vcpu * vcpu,bool * req_immediate_exit)10693 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10694 bool *req_immediate_exit)
10695 {
10696 bool can_inject;
10697 int r;
10698
10699 /*
10700 * Process nested events first, as nested VM-Exit supersedes event
10701 * re-injection. If there's an event queued for re-injection, it will
10702 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10703 */
10704 if (is_guest_mode(vcpu))
10705 r = kvm_check_nested_events(vcpu);
10706 else
10707 r = 0;
10708
10709 /*
10710 * Re-inject exceptions and events *especially* if immediate entry+exit
10711 * to/from L2 is needed, as any event that has already been injected
10712 * into L2 needs to complete its lifecycle before injecting a new event.
10713 *
10714 * Don't re-inject an NMI or interrupt if there is a pending exception.
10715 * This collision arises if an exception occurred while vectoring the
10716 * injected event, KVM intercepted said exception, and KVM ultimately
10717 * determined the fault belongs to the guest and queues the exception
10718 * for injection back into the guest.
10719 *
10720 * "Injected" interrupts can also collide with pending exceptions if
10721 * userspace ignores the "ready for injection" flag and blindly queues
10722 * an interrupt. In that case, prioritizing the exception is correct,
10723 * as the exception "occurred" before the exit to userspace. Trap-like
10724 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10725 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10726 * priority, they're only generated (pended) during instruction
10727 * execution, and interrupts are recognized at instruction boundaries.
10728 * Thus a pending fault-like exception means the fault occurred on the
10729 * *previous* instruction and must be serviced prior to recognizing any
10730 * new events in order to fully complete the previous instruction.
10731 */
10732 if (vcpu->arch.exception.injected)
10733 kvm_inject_exception(vcpu);
10734 else if (kvm_is_exception_pending(vcpu))
10735 ; /* see above */
10736 else if (vcpu->arch.nmi_injected)
10737 kvm_x86_call(inject_nmi)(vcpu);
10738 else if (vcpu->arch.interrupt.injected)
10739 kvm_x86_call(inject_irq)(vcpu, true);
10740
10741 /*
10742 * Exceptions that morph to VM-Exits are handled above, and pending
10743 * exceptions on top of injected exceptions that do not VM-Exit should
10744 * either morph to #DF or, sadly, override the injected exception.
10745 */
10746 WARN_ON_ONCE(vcpu->arch.exception.injected &&
10747 vcpu->arch.exception.pending);
10748
10749 /*
10750 * Bail if immediate entry+exit to/from the guest is needed to complete
10751 * nested VM-Enter or event re-injection so that a different pending
10752 * event can be serviced (or if KVM needs to exit to userspace).
10753 *
10754 * Otherwise, continue processing events even if VM-Exit occurred. The
10755 * VM-Exit will have cleared exceptions that were meant for L2, but
10756 * there may now be events that can be injected into L1.
10757 */
10758 if (r < 0)
10759 goto out;
10760
10761 /*
10762 * A pending exception VM-Exit should either result in nested VM-Exit
10763 * or force an immediate re-entry and exit to/from L2, and exception
10764 * VM-Exits cannot be injected (flag should _never_ be set).
10765 */
10766 WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10767 vcpu->arch.exception_vmexit.pending);
10768
10769 /*
10770 * New events, other than exceptions, cannot be injected if KVM needs
10771 * to re-inject a previous event. See above comments on re-injecting
10772 * for why pending exceptions get priority.
10773 */
10774 can_inject = !kvm_event_needs_reinjection(vcpu);
10775
10776 if (vcpu->arch.exception.pending) {
10777 /*
10778 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10779 * value pushed on the stack. Trap-like exception and all #DBs
10780 * leave RF as-is (KVM follows Intel's behavior in this regard;
10781 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10782 *
10783 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10784 * describe the behavior of General Detect #DBs, which are
10785 * fault-like. They do _not_ set RF, a la code breakpoints.
10786 */
10787 if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10788 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10789 X86_EFLAGS_RF);
10790
10791 if (vcpu->arch.exception.vector == DB_VECTOR &&
10792 vcpu->arch.dr7 & DR7_GD) {
10793 vcpu->arch.dr7 &= ~DR7_GD;
10794 kvm_update_dr7(vcpu);
10795 }
10796
10797 kvm_inject_exception(vcpu);
10798
10799 vcpu->arch.exception.pending = false;
10800 vcpu->arch.exception.injected = true;
10801
10802 can_inject = false;
10803 }
10804
10805 /* Don't inject interrupts if the user asked to avoid doing so */
10806 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10807 return 0;
10808
10809 /*
10810 * Finally, inject interrupt events. If an event cannot be injected
10811 * due to architectural conditions (e.g. IF=0) a window-open exit
10812 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
10813 * and can architecturally be injected, but we cannot do it right now:
10814 * an interrupt could have arrived just now and we have to inject it
10815 * as a vmexit, or there could already an event in the queue, which is
10816 * indicated by can_inject. In that case we request an immediate exit
10817 * in order to make progress and get back here for another iteration.
10818 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10819 */
10820 #ifdef CONFIG_KVM_SMM
10821 if (vcpu->arch.smi_pending) {
10822 r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
10823 -EBUSY;
10824 if (r < 0)
10825 goto out;
10826 if (r) {
10827 vcpu->arch.smi_pending = false;
10828 ++vcpu->arch.smi_count;
10829 enter_smm(vcpu);
10830 can_inject = false;
10831 } else
10832 kvm_x86_call(enable_smi_window)(vcpu);
10833 }
10834 #endif
10835
10836 if (vcpu->arch.nmi_pending) {
10837 r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
10838 -EBUSY;
10839 if (r < 0)
10840 goto out;
10841 if (r) {
10842 --vcpu->arch.nmi_pending;
10843 vcpu->arch.nmi_injected = true;
10844 kvm_x86_call(inject_nmi)(vcpu);
10845 can_inject = false;
10846 WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
10847 }
10848 if (vcpu->arch.nmi_pending)
10849 kvm_x86_call(enable_nmi_window)(vcpu);
10850 }
10851
10852 if (kvm_cpu_has_injectable_intr(vcpu)) {
10853 r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
10854 -EBUSY;
10855 if (r < 0)
10856 goto out;
10857 if (r) {
10858 int irq = kvm_cpu_get_interrupt(vcpu);
10859
10860 if (!WARN_ON_ONCE(irq == -1)) {
10861 kvm_queue_interrupt(vcpu, irq, false);
10862 kvm_x86_call(inject_irq)(vcpu, false);
10863 WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
10864 }
10865 }
10866 if (kvm_cpu_has_injectable_intr(vcpu))
10867 kvm_x86_call(enable_irq_window)(vcpu);
10868 }
10869
10870 if (is_guest_mode(vcpu) &&
10871 kvm_x86_ops.nested_ops->has_events &&
10872 kvm_x86_ops.nested_ops->has_events(vcpu, true))
10873 *req_immediate_exit = true;
10874
10875 /*
10876 * KVM must never queue a new exception while injecting an event; KVM
10877 * is done emulating and should only propagate the to-be-injected event
10878 * to the VMCS/VMCB. Queueing a new exception can put the vCPU into an
10879 * infinite loop as KVM will bail from VM-Enter to inject the pending
10880 * exception and start the cycle all over.
10881 *
10882 * Exempt triple faults as they have special handling and won't put the
10883 * vCPU into an infinite loop. Triple fault can be queued when running
10884 * VMX without unrestricted guest, as that requires KVM to emulate Real
10885 * Mode events (see kvm_inject_realmode_interrupt()).
10886 */
10887 WARN_ON_ONCE(vcpu->arch.exception.pending ||
10888 vcpu->arch.exception_vmexit.pending);
10889 return 0;
10890
10891 out:
10892 if (r == -EBUSY) {
10893 *req_immediate_exit = true;
10894 r = 0;
10895 }
10896 return r;
10897 }
10898
process_nmi(struct kvm_vcpu * vcpu)10899 static void process_nmi(struct kvm_vcpu *vcpu)
10900 {
10901 unsigned int limit;
10902
10903 /*
10904 * x86 is limited to one NMI pending, but because KVM can't react to
10905 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10906 * scheduled out, KVM needs to play nice with two queued NMIs showing
10907 * up at the same time. To handle this scenario, allow two NMIs to be
10908 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10909 * waiting for a previous NMI injection to complete (which effectively
10910 * blocks NMIs). KVM will immediately inject one of the two NMIs, and
10911 * will request an NMI window to handle the second NMI.
10912 */
10913 if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10914 limit = 1;
10915 else
10916 limit = 2;
10917
10918 /*
10919 * Adjust the limit to account for pending virtual NMIs, which aren't
10920 * tracked in vcpu->arch.nmi_pending.
10921 */
10922 if (kvm_x86_call(is_vnmi_pending)(vcpu))
10923 limit--;
10924
10925 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10926 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10927
10928 if (vcpu->arch.nmi_pending &&
10929 (kvm_x86_call(set_vnmi_pending)(vcpu)))
10930 vcpu->arch.nmi_pending--;
10931
10932 if (vcpu->arch.nmi_pending)
10933 kvm_make_request(KVM_REQ_EVENT, vcpu);
10934 }
10935
10936 /* Return total number of NMIs pending injection to the VM */
kvm_get_nr_pending_nmis(struct kvm_vcpu * vcpu)10937 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10938 {
10939 return vcpu->arch.nmi_pending +
10940 kvm_x86_call(is_vnmi_pending)(vcpu);
10941 }
10942
kvm_make_scan_ioapic_request_mask(struct kvm * kvm,unsigned long * vcpu_bitmap)10943 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10944 unsigned long *vcpu_bitmap)
10945 {
10946 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10947 }
10948
kvm_make_scan_ioapic_request(struct kvm * kvm)10949 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10950 {
10951 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10952 }
10953
__kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10954 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10955 {
10956 struct kvm_lapic *apic = vcpu->arch.apic;
10957 bool activate;
10958
10959 if (!lapic_in_kernel(vcpu))
10960 return;
10961
10962 down_read(&vcpu->kvm->arch.apicv_update_lock);
10963 preempt_disable();
10964
10965 /* Do not activate APICV when APIC is disabled */
10966 activate = kvm_vcpu_apicv_activated(vcpu) &&
10967 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10968
10969 if (apic->apicv_active == activate)
10970 goto out;
10971
10972 apic->apicv_active = activate;
10973 kvm_apic_update_apicv(vcpu);
10974 kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
10975
10976 /*
10977 * When APICv gets disabled, we may still have injected interrupts
10978 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10979 * still active when the interrupt got accepted. Make sure
10980 * kvm_check_and_inject_events() is called to check for that.
10981 */
10982 if (!apic->apicv_active)
10983 kvm_make_request(KVM_REQ_EVENT, vcpu);
10984
10985 out:
10986 preempt_enable();
10987 up_read(&vcpu->kvm->arch.apicv_update_lock);
10988 }
10989 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_vcpu_update_apicv);
10990
kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10991 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10992 {
10993 if (!lapic_in_kernel(vcpu))
10994 return;
10995
10996 /*
10997 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10998 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10999 * and hardware doesn't support x2APIC virtualization. E.g. some AMD
11000 * CPUs support AVIC but not x2APIC. KVM still allows enabling AVIC in
11001 * this case so that KVM can use the AVIC doorbell to inject interrupts
11002 * to running vCPUs, but KVM must not create SPTEs for the APIC base as
11003 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
11004 * despite being in x2APIC mode. For simplicity, inhibiting the APIC
11005 * access page is sticky.
11006 */
11007 if (apic_x2apic_mode(vcpu->arch.apic) &&
11008 kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
11009 kvm_inhibit_apic_access_page(vcpu);
11010
11011 __kvm_vcpu_update_apicv(vcpu);
11012 }
11013
__kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)11014 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
11015 enum kvm_apicv_inhibit reason, bool set)
11016 {
11017 unsigned long old, new;
11018
11019 lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
11020
11021 if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
11022 return;
11023
11024 old = new = kvm->arch.apicv_inhibit_reasons;
11025
11026 if (reason != APICV_INHIBIT_REASON_IRQWIN)
11027 set_or_clear_apicv_inhibit(&new, reason, set);
11028
11029 set_or_clear_apicv_inhibit(&new, APICV_INHIBIT_REASON_IRQWIN,
11030 atomic_read(&kvm->arch.apicv_nr_irq_window_req));
11031
11032 if (!!old != !!new) {
11033 /*
11034 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
11035 * false positives in the sanity check WARN in vcpu_enter_guest().
11036 * This task will wait for all vCPUs to ack the kick IRQ before
11037 * updating apicv_inhibit_reasons, and all other vCPUs will
11038 * block on acquiring apicv_update_lock so that vCPUs can't
11039 * redo vcpu_enter_guest() without seeing the new inhibit state.
11040 *
11041 * Note, holding apicv_update_lock and taking it in the read
11042 * side (handling the request) also prevents other vCPUs from
11043 * servicing the request with a stale apicv_inhibit_reasons.
11044 */
11045 kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
11046 kvm->arch.apicv_inhibit_reasons = new;
11047 if (new) {
11048 unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
11049 int idx = srcu_read_lock(&kvm->srcu);
11050
11051 kvm_zap_gfn_range(kvm, gfn, gfn+1);
11052 srcu_read_unlock(&kvm->srcu, idx);
11053 }
11054 } else {
11055 kvm->arch.apicv_inhibit_reasons = new;
11056 }
11057 }
11058
kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)11059 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
11060 enum kvm_apicv_inhibit reason, bool set)
11061 {
11062 if (!enable_apicv)
11063 return;
11064
11065 down_write(&kvm->arch.apicv_update_lock);
11066 __kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
11067 up_write(&kvm->arch.apicv_update_lock);
11068 }
11069 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_or_clear_apicv_inhibit);
11070
kvm_inc_or_dec_irq_window_inhibit(struct kvm * kvm,bool inc)11071 void kvm_inc_or_dec_irq_window_inhibit(struct kvm *kvm, bool inc)
11072 {
11073 int add = inc ? 1 : -1;
11074
11075 if (!enable_apicv)
11076 return;
11077
11078 /*
11079 * IRQ windows are requested either because of ExtINT injections, or
11080 * because APICv is already disabled/inhibited for another reason.
11081 * While ExtINT injections are rare and should not happen while the
11082 * vCPU is running its actual workload, it's worth avoiding thrashing
11083 * if the IRQ window is being requested because APICv is already
11084 * inhibited. So, toggle the actual inhibit (which requires taking
11085 * the lock for write) if and only if there's no other inhibit.
11086 * kvm_set_or_clear_apicv_inhibit() always evaluates the IRQ window
11087 * count; thus the IRQ window inhibit call _will_ be lazily updated on
11088 * the next call, if it ever happens.
11089 */
11090 if (READ_ONCE(kvm->arch.apicv_inhibit_reasons) & ~BIT(APICV_INHIBIT_REASON_IRQWIN)) {
11091 guard(rwsem_read)(&kvm->arch.apicv_update_lock);
11092 if (READ_ONCE(kvm->arch.apicv_inhibit_reasons) & ~BIT(APICV_INHIBIT_REASON_IRQWIN)) {
11093 atomic_add(add, &kvm->arch.apicv_nr_irq_window_req);
11094 return;
11095 }
11096 }
11097
11098 /*
11099 * Strictly speaking, the lock is only needed if going 0->1 or 1->0,
11100 * a la atomic_dec_and_mutex_lock. However, ExtINTs are rare and
11101 * only target a single CPU, so that is the common case; do not
11102 * bother eliding the down_write()/up_write() pair.
11103 */
11104 guard(rwsem_write)(&kvm->arch.apicv_update_lock);
11105 if (atomic_add_return(add, &kvm->arch.apicv_nr_irq_window_req) == inc)
11106 __kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_IRQWIN, inc);
11107 }
11108 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inc_or_dec_irq_window_inhibit);
11109
vcpu_scan_ioapic(struct kvm_vcpu * vcpu)11110 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
11111 {
11112 if (!kvm_apic_present(vcpu))
11113 return;
11114
11115 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
11116 vcpu->arch.highest_stale_pending_ioapic_eoi = -1;
11117
11118 kvm_x86_call(sync_pir_to_irr)(vcpu);
11119
11120 if (irqchip_split(vcpu->kvm))
11121 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
11122 #ifdef CONFIG_KVM_IOAPIC
11123 else if (ioapic_in_kernel(vcpu->kvm))
11124 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
11125 #endif
11126
11127 if (is_guest_mode(vcpu))
11128 vcpu->arch.load_eoi_exitmap_pending = true;
11129 else
11130 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
11131 }
11132
vcpu_load_eoi_exitmap(struct kvm_vcpu * vcpu)11133 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
11134 {
11135 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
11136 return;
11137
11138 #ifdef CONFIG_KVM_HYPERV
11139 if (to_hv_vcpu(vcpu)) {
11140 u64 eoi_exit_bitmap[4];
11141
11142 bitmap_or((ulong *)eoi_exit_bitmap,
11143 vcpu->arch.ioapic_handled_vectors,
11144 to_hv_synic(vcpu)->vec_bitmap, 256);
11145 kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
11146 return;
11147 }
11148 #endif
11149 kvm_x86_call(load_eoi_exitmap)(
11150 vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
11151 }
11152
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)11153 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
11154 {
11155 kvm_x86_call(guest_memory_reclaimed)(kvm);
11156 }
11157
kvm_vcpu_reload_apic_access_page(struct kvm_vcpu * vcpu)11158 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
11159 {
11160 if (!lapic_in_kernel(vcpu))
11161 return;
11162
11163 kvm_x86_call(set_apic_access_page_addr)(vcpu);
11164 }
11165
11166 /*
11167 * Called within kvm->srcu read side.
11168 * Returns 1 to let vcpu_run() continue the guest execution loop without
11169 * exiting to the userspace. Otherwise, the value will be returned to the
11170 * userspace.
11171 */
vcpu_enter_guest(struct kvm_vcpu * vcpu)11172 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
11173 {
11174 int r;
11175 bool req_int_win =
11176 dm_request_for_irq_injection(vcpu) &&
11177 kvm_cpu_accept_dm_intr(vcpu);
11178 fastpath_t exit_fastpath;
11179 u64 run_flags, debug_ctl;
11180
11181 bool req_immediate_exit = false;
11182
11183 if (kvm_request_pending(vcpu)) {
11184 if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
11185 r = -EIO;
11186 goto out;
11187 }
11188
11189 if (kvm_dirty_ring_check_request(vcpu)) {
11190 r = 0;
11191 goto out;
11192 }
11193
11194 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
11195 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
11196 r = 0;
11197 goto out;
11198 }
11199 }
11200 if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
11201 kvm_mmu_free_obsolete_roots(vcpu);
11202 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
11203 __kvm_migrate_timers(vcpu);
11204 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
11205 kvm_update_masterclock(vcpu->kvm);
11206 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
11207 kvm_gen_kvmclock_update(vcpu);
11208 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
11209 r = kvm_guest_time_update(vcpu);
11210 if (unlikely(r))
11211 goto out;
11212 }
11213 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
11214 kvm_mmu_sync_roots(vcpu);
11215 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
11216 kvm_mmu_load_pgd(vcpu);
11217
11218 /*
11219 * Note, the order matters here, as flushing "all" TLB entries
11220 * also flushes the "current" TLB entries, i.e. servicing the
11221 * flush "all" will clear any request to flush "current".
11222 */
11223 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
11224 kvm_vcpu_flush_tlb_all(vcpu);
11225
11226 kvm_service_local_tlb_flush_requests(vcpu);
11227
11228 /*
11229 * Fall back to a "full" guest flush if Hyper-V's precise
11230 * flushing fails. Note, Hyper-V's flushing is per-vCPU, but
11231 * the flushes are considered "remote" and not "local" because
11232 * the requests can be initiated from other vCPUs.
11233 */
11234 #ifdef CONFIG_KVM_HYPERV
11235 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
11236 kvm_hv_vcpu_flush_tlb(vcpu))
11237 kvm_vcpu_flush_tlb_guest(vcpu);
11238 #endif
11239
11240 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
11241 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
11242 r = 0;
11243 goto out;
11244 }
11245 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
11246 if (is_guest_mode(vcpu))
11247 kvm_x86_ops.nested_ops->triple_fault(vcpu);
11248
11249 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
11250 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
11251 vcpu->mmio_needed = 0;
11252 r = 0;
11253 goto out;
11254 }
11255 }
11256 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
11257 /* Page is swapped out. Do synthetic halt */
11258 vcpu->arch.apf.halted = true;
11259 r = 1;
11260 goto out;
11261 }
11262 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
11263 record_steal_time(vcpu);
11264 if (kvm_check_request(KVM_REQ_PMU, vcpu))
11265 kvm_pmu_handle_event(vcpu);
11266 if (kvm_check_request(KVM_REQ_PMI, vcpu))
11267 kvm_pmu_deliver_pmi(vcpu);
11268 #ifdef CONFIG_KVM_SMM
11269 if (kvm_check_request(KVM_REQ_SMI, vcpu))
11270 process_smi(vcpu);
11271 #endif
11272 if (kvm_check_request(KVM_REQ_NMI, vcpu))
11273 process_nmi(vcpu);
11274 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
11275 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
11276 if (test_bit(vcpu->arch.pending_ioapic_eoi,
11277 vcpu->arch.ioapic_handled_vectors)) {
11278 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
11279 vcpu->run->eoi.vector =
11280 vcpu->arch.pending_ioapic_eoi;
11281 r = 0;
11282 goto out;
11283 }
11284 }
11285 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
11286 vcpu_scan_ioapic(vcpu);
11287 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
11288 vcpu_load_eoi_exitmap(vcpu);
11289 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
11290 kvm_vcpu_reload_apic_access_page(vcpu);
11291 #ifdef CONFIG_KVM_HYPERV
11292 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
11293 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
11294 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
11295 vcpu->run->system_event.ndata = 0;
11296 r = 0;
11297 goto out;
11298 }
11299 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
11300 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
11301 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
11302 vcpu->run->system_event.ndata = 0;
11303 r = 0;
11304 goto out;
11305 }
11306 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
11307 struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
11308
11309 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
11310 vcpu->run->hyperv = hv_vcpu->exit;
11311 r = 0;
11312 goto out;
11313 }
11314
11315 /*
11316 * KVM_REQ_HV_STIMER has to be processed after
11317 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
11318 * depend on the guest clock being up-to-date
11319 */
11320 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
11321 kvm_hv_process_stimers(vcpu);
11322 #endif
11323 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
11324 kvm_vcpu_update_apicv(vcpu);
11325 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
11326 kvm_check_async_pf_completion(vcpu);
11327
11328 if (kvm_check_request(KVM_REQ_RECALC_INTERCEPTS, vcpu))
11329 kvm_x86_call(recalc_intercepts)(vcpu);
11330
11331 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
11332 kvm_x86_call(update_cpu_dirty_logging)(vcpu);
11333
11334 if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
11335 kvm_vcpu_reset(vcpu, true);
11336 if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
11337 r = 1;
11338 goto out;
11339 }
11340 }
11341 }
11342
11343 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
11344 kvm_xen_has_interrupt(vcpu)) {
11345 ++vcpu->stat.req_event;
11346 r = kvm_apic_accept_events(vcpu);
11347 if (r < 0) {
11348 r = 0;
11349 goto out;
11350 }
11351 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
11352 r = 1;
11353 goto out;
11354 }
11355
11356 r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
11357 if (r < 0) {
11358 r = 0;
11359 goto out;
11360 }
11361 if (req_int_win)
11362 kvm_x86_call(enable_irq_window)(vcpu);
11363
11364 if (kvm_lapic_enabled(vcpu)) {
11365 update_cr8_intercept(vcpu);
11366 kvm_lapic_sync_to_vapic(vcpu);
11367 }
11368 }
11369
11370 r = kvm_mmu_reload(vcpu);
11371 if (unlikely(r)) {
11372 goto cancel_injection;
11373 }
11374
11375 preempt_disable();
11376
11377 kvm_x86_call(prepare_switch_to_guest)(vcpu);
11378
11379 /*
11380 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
11381 * IPI are then delayed after guest entry, which ensures that they
11382 * result in virtual interrupt delivery.
11383 */
11384 local_irq_disable();
11385
11386 /* Store vcpu->apicv_active before vcpu->mode. */
11387 smp_store_release(&vcpu->mode, IN_GUEST_MODE);
11388
11389 kvm_vcpu_srcu_read_unlock(vcpu);
11390
11391 /*
11392 * 1) We should set ->mode before checking ->requests. Please see
11393 * the comment in kvm_vcpu_exiting_guest_mode().
11394 *
11395 * 2) For APICv, we should set ->mode before checking PID.ON. This
11396 * pairs with the memory barrier implicit in pi_test_and_set_on
11397 * (see vmx_deliver_posted_interrupt).
11398 *
11399 * 3) This also orders the write to mode from any reads to the page
11400 * tables done while the VCPU is running. Please see the comment
11401 * in kvm_flush_remote_tlbs.
11402 */
11403 smp_mb__after_srcu_read_unlock();
11404
11405 /*
11406 * Process pending posted interrupts to handle the case where the
11407 * notification IRQ arrived in the host, or was never sent (because the
11408 * target vCPU wasn't running). Do this regardless of the vCPU's APICv
11409 * status, KVM doesn't update assigned devices when APICv is inhibited,
11410 * i.e. they can post interrupts even if APICv is temporarily disabled.
11411 */
11412 if (kvm_lapic_enabled(vcpu))
11413 kvm_x86_call(sync_pir_to_irr)(vcpu);
11414
11415 if (kvm_vcpu_exit_request(vcpu)) {
11416 vcpu->mode = OUTSIDE_GUEST_MODE;
11417 smp_wmb();
11418 local_irq_enable();
11419 preempt_enable();
11420 kvm_vcpu_srcu_read_lock(vcpu);
11421 r = 1;
11422 goto cancel_injection;
11423 }
11424
11425 run_flags = 0;
11426 if (req_immediate_exit) {
11427 run_flags |= KVM_RUN_FORCE_IMMEDIATE_EXIT;
11428 kvm_make_request(KVM_REQ_EVENT, vcpu);
11429 }
11430
11431 fpregs_assert_state_consistent();
11432 if (test_thread_flag(TIF_NEED_FPU_LOAD))
11433 switch_fpu_return();
11434
11435 if (vcpu->arch.guest_fpu.xfd_err)
11436 wrmsrq(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
11437
11438 kvm_load_xfeatures(vcpu, true);
11439
11440 if (unlikely(vcpu->arch.switch_db_regs &&
11441 !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
11442 set_debugreg(DR7_FIXED_1, 7);
11443 set_debugreg(vcpu->arch.eff_db[0], 0);
11444 set_debugreg(vcpu->arch.eff_db[1], 1);
11445 set_debugreg(vcpu->arch.eff_db[2], 2);
11446 set_debugreg(vcpu->arch.eff_db[3], 3);
11447 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
11448 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
11449 run_flags |= KVM_RUN_LOAD_GUEST_DR6;
11450 } else if (unlikely(hw_breakpoint_active())) {
11451 set_debugreg(DR7_FIXED_1, 7);
11452 }
11453
11454 /*
11455 * Refresh the host DEBUGCTL snapshot after disabling IRQs, as DEBUGCTL
11456 * can be modified in IRQ context, e.g. via SMP function calls. Inform
11457 * vendor code if any host-owned bits were changed, e.g. so that the
11458 * value loaded into hardware while running the guest can be updated.
11459 */
11460 debug_ctl = get_debugctlmsr();
11461 if ((debug_ctl ^ vcpu->arch.host_debugctl) & kvm_x86_ops.HOST_OWNED_DEBUGCTL &&
11462 !vcpu->arch.guest_state_protected)
11463 run_flags |= KVM_RUN_LOAD_DEBUGCTL;
11464 vcpu->arch.host_debugctl = debug_ctl;
11465
11466 kvm_mediated_pmu_load(vcpu);
11467
11468 guest_timing_enter_irqoff();
11469
11470 /*
11471 * Swap PKRU with hardware breakpoints disabled to minimize the number
11472 * of flows where non-KVM code can run with guest state loaded.
11473 */
11474 kvm_load_guest_pkru(vcpu);
11475
11476 for (;;) {
11477 /*
11478 * Assert that vCPU vs. VM APICv state is consistent. An APICv
11479 * update must kick and wait for all vCPUs before toggling the
11480 * per-VM state, and responding vCPUs must wait for the update
11481 * to complete before servicing KVM_REQ_APICV_UPDATE.
11482 */
11483 WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11484 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
11485
11486 exit_fastpath = kvm_x86_call(vcpu_run)(vcpu, run_flags);
11487 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11488 break;
11489
11490 if (kvm_lapic_enabled(vcpu))
11491 kvm_x86_call(sync_pir_to_irr)(vcpu);
11492
11493 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
11494 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11495 break;
11496 }
11497
11498 run_flags = 0;
11499
11500 /* Note, VM-Exits that go down the "slow" path are accounted below. */
11501 ++vcpu->stat.exits;
11502 }
11503
11504 kvm_load_host_pkru(vcpu);
11505
11506 kvm_mediated_pmu_put(vcpu);
11507
11508 /*
11509 * Do this here before restoring debug registers on the host. And
11510 * since we do this before handling the vmexit, a DR access vmexit
11511 * can (a) read the correct value of the debug registers, (b) set
11512 * KVM_DEBUGREG_WONT_EXIT again.
11513 */
11514 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
11515 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
11516 WARN_ON(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH);
11517 kvm_x86_call(sync_dirty_debug_regs)(vcpu);
11518 kvm_update_dr0123(vcpu);
11519 kvm_update_dr7(vcpu);
11520 }
11521
11522 /*
11523 * If the guest has used debug registers, at least dr7
11524 * will be disabled while returning to the host.
11525 * If we don't have active breakpoints in the host, we don't
11526 * care about the messed up debug address registers. But if
11527 * we have some of them active, restore the old state.
11528 */
11529 if (hw_breakpoint_active())
11530 hw_breakpoint_restore();
11531
11532 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
11533 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
11534
11535 vcpu->mode = OUTSIDE_GUEST_MODE;
11536 smp_wmb();
11537
11538 kvm_load_xfeatures(vcpu, false);
11539
11540 /*
11541 * Sync xfd before calling handle_exit_irqoff() which may
11542 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11543 * in #NM irqoff handler).
11544 */
11545 if (vcpu->arch.xfd_no_write_intercept)
11546 fpu_sync_guest_vmexit_xfd_state();
11547
11548 kvm_x86_call(handle_exit_irqoff)(vcpu);
11549
11550 if (vcpu->arch.guest_fpu.xfd_err)
11551 wrmsrq(MSR_IA32_XFD_ERR, 0);
11552
11553 /*
11554 * Mark this CPU as needing a branch predictor flush before running
11555 * userspace. Must be done before enabling preemption to ensure it gets
11556 * set for the CPU that actually ran the guest, and not the CPU that it
11557 * may migrate to.
11558 */
11559 if (cpu_feature_enabled(X86_FEATURE_IBPB_EXIT_TO_USER))
11560 this_cpu_write(x86_ibpb_exit_to_user, true);
11561
11562 /*
11563 * Consume any pending interrupts, including the possible source of
11564 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11565 * An instruction is required after local_irq_enable() to fully unblock
11566 * interrupts on processors that implement an interrupt shadow, the
11567 * stat.exits increment will do nicely.
11568 */
11569 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
11570 local_irq_enable();
11571 ++vcpu->stat.exits;
11572 local_irq_disable();
11573 kvm_after_interrupt(vcpu);
11574
11575 /*
11576 * Wait until after servicing IRQs to account guest time so that any
11577 * ticks that occurred while running the guest are properly accounted
11578 * to the guest. Waiting until IRQs are enabled degrades the accuracy
11579 * of accounting via context tracking, but the loss of accuracy is
11580 * acceptable for all known use cases.
11581 */
11582 guest_timing_exit_irqoff();
11583
11584 local_irq_enable();
11585 preempt_enable();
11586
11587 kvm_vcpu_srcu_read_lock(vcpu);
11588
11589 /*
11590 * Call this to ensure WC buffers in guest are evicted after each VM
11591 * Exit, so that the evicted WC writes can be snooped across all cpus
11592 */
11593 smp_mb__after_srcu_read_lock();
11594
11595 /*
11596 * Profile KVM exit RIPs:
11597 */
11598 if (unlikely(prof_on == KVM_PROFILING &&
11599 !vcpu->arch.guest_state_protected)) {
11600 unsigned long rip = kvm_rip_read(vcpu);
11601 profile_hit(KVM_PROFILING, (void *)rip);
11602 }
11603
11604 if (unlikely(vcpu->arch.tsc_always_catchup))
11605 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11606
11607 if (vcpu->arch.apic_attention)
11608 kvm_lapic_sync_from_vapic(vcpu);
11609
11610 if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
11611 return 0;
11612
11613 r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
11614 return r;
11615
11616 cancel_injection:
11617 if (req_immediate_exit)
11618 kvm_make_request(KVM_REQ_EVENT, vcpu);
11619 kvm_x86_call(cancel_injection)(vcpu);
11620 if (unlikely(vcpu->arch.apic_attention))
11621 kvm_lapic_sync_from_vapic(vcpu);
11622 out:
11623 return r;
11624 }
11625
kvm_vcpu_running(struct kvm_vcpu * vcpu)11626 static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11627 {
11628 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11629 !vcpu->arch.apf.halted);
11630 }
11631
kvm_vcpu_has_events(struct kvm_vcpu * vcpu)11632 bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
11633 {
11634 if (!list_empty_careful(&vcpu->async_pf.done))
11635 return true;
11636
11637 if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
11638 kvm_apic_init_sipi_allowed(vcpu))
11639 return true;
11640
11641 if (kvm_is_exception_pending(vcpu))
11642 return true;
11643
11644 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11645 (vcpu->arch.nmi_pending &&
11646 kvm_x86_call(nmi_allowed)(vcpu, false)))
11647 return true;
11648
11649 #ifdef CONFIG_KVM_SMM
11650 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11651 (vcpu->arch.smi_pending &&
11652 kvm_x86_call(smi_allowed)(vcpu, false)))
11653 return true;
11654 #endif
11655
11656 if (kvm_test_request(KVM_REQ_PMI, vcpu))
11657 return true;
11658
11659 if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
11660 return true;
11661
11662 if (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
11663 return true;
11664
11665 if (kvm_hv_has_stimer_pending(vcpu))
11666 return true;
11667
11668 if (is_guest_mode(vcpu) &&
11669 kvm_x86_ops.nested_ops->has_events &&
11670 kvm_x86_ops.nested_ops->has_events(vcpu, false))
11671 return true;
11672
11673 if (kvm_xen_has_pending_events(vcpu))
11674 return true;
11675
11676 return false;
11677 }
11678 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_has_events);
11679
kvm_arch_vcpu_runnable(struct kvm_vcpu * vcpu)11680 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11681 {
11682 return kvm_vcpu_running(vcpu) || vcpu->arch.pv.pv_unhalted ||
11683 kvm_vcpu_has_events(vcpu);
11684 }
11685
11686 /* Called within kvm->srcu read side. */
vcpu_block(struct kvm_vcpu * vcpu)11687 static inline int vcpu_block(struct kvm_vcpu *vcpu)
11688 {
11689 bool hv_timer;
11690
11691 if (!kvm_arch_vcpu_runnable(vcpu)) {
11692 /*
11693 * Switch to the software timer before halt-polling/blocking as
11694 * the guest's timer may be a break event for the vCPU, and the
11695 * hypervisor timer runs only when the CPU is in guest mode.
11696 * Switch before halt-polling so that KVM recognizes an expired
11697 * timer before blocking.
11698 */
11699 hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11700 if (hv_timer)
11701 kvm_lapic_switch_to_sw_timer(vcpu);
11702
11703 kvm_vcpu_srcu_read_unlock(vcpu);
11704 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11705 kvm_vcpu_halt(vcpu);
11706 else
11707 kvm_vcpu_block(vcpu);
11708 kvm_vcpu_srcu_read_lock(vcpu);
11709
11710 if (hv_timer)
11711 kvm_lapic_switch_to_hv_timer(vcpu);
11712
11713 /*
11714 * If the vCPU is not runnable, a signal or another host event
11715 * of some kind is pending; service it without changing the
11716 * vCPU's activity state.
11717 */
11718 if (!kvm_arch_vcpu_runnable(vcpu))
11719 return 1;
11720 }
11721
11722 /*
11723 * Evaluate nested events before exiting the halted state. This allows
11724 * the halt state to be recorded properly in the VMCS12's activity
11725 * state field (AMD does not have a similar field and a VM-Exit always
11726 * causes a spurious wakeup from HLT).
11727 */
11728 if (is_guest_mode(vcpu)) {
11729 int r = kvm_check_nested_events(vcpu);
11730
11731 if (r < 0 && r != -EBUSY)
11732 return 0;
11733 }
11734
11735 if (kvm_apic_accept_events(vcpu) < 0)
11736 return 0;
11737 switch(vcpu->arch.mp_state) {
11738 case KVM_MP_STATE_HALTED:
11739 case KVM_MP_STATE_AP_RESET_HOLD:
11740 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
11741 fallthrough;
11742 case KVM_MP_STATE_RUNNABLE:
11743 vcpu->arch.apf.halted = false;
11744 break;
11745 case KVM_MP_STATE_INIT_RECEIVED:
11746 break;
11747 default:
11748 WARN_ON_ONCE(1);
11749 break;
11750 }
11751 return 1;
11752 }
11753
11754 /* Called within kvm->srcu read side. */
vcpu_run(struct kvm_vcpu * vcpu)11755 static int vcpu_run(struct kvm_vcpu *vcpu)
11756 {
11757 int r;
11758
11759 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
11760
11761 for (;;) {
11762 /*
11763 * If another guest vCPU requests a PV TLB flush in the middle
11764 * of instruction emulation, the rest of the emulation could
11765 * use a stale page translation. Assume that any code after
11766 * this point can start executing an instruction.
11767 */
11768 vcpu->arch.at_instruction_boundary = false;
11769 if (kvm_vcpu_running(vcpu)) {
11770 r = vcpu_enter_guest(vcpu);
11771 } else {
11772 r = vcpu_block(vcpu);
11773 }
11774
11775 if (r <= 0)
11776 break;
11777
11778 kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11779 if (kvm_xen_has_pending_events(vcpu))
11780 kvm_xen_inject_pending_events(vcpu);
11781
11782 if (kvm_cpu_has_pending_timer(vcpu))
11783 kvm_inject_pending_timer_irqs(vcpu);
11784
11785 if (dm_request_for_irq_injection(vcpu) &&
11786 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11787 r = 0;
11788 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11789 ++vcpu->stat.request_irq_exits;
11790 break;
11791 }
11792
11793 if (__xfer_to_guest_mode_work_pending()) {
11794 kvm_vcpu_srcu_read_unlock(vcpu);
11795 r = kvm_xfer_to_guest_mode_handle_work(vcpu);
11796 kvm_vcpu_srcu_read_lock(vcpu);
11797 if (r)
11798 return r;
11799 }
11800 }
11801
11802 return r;
11803 }
11804
__kvm_emulate_halt(struct kvm_vcpu * vcpu,int state,int reason)11805 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
11806 {
11807 /*
11808 * The vCPU has halted, e.g. executed HLT. Update the run state if the
11809 * local APIC is in-kernel, the run loop will detect the non-runnable
11810 * state and halt the vCPU. Exit to userspace if the local APIC is
11811 * managed by userspace, in which case userspace is responsible for
11812 * handling wake events.
11813 */
11814 ++vcpu->stat.halt_exits;
11815 if (lapic_in_kernel(vcpu)) {
11816 if (kvm_vcpu_has_events(vcpu) || vcpu->arch.pv.pv_unhalted)
11817 state = KVM_MP_STATE_RUNNABLE;
11818 kvm_set_mp_state(vcpu, state);
11819 return 1;
11820 } else {
11821 vcpu->run->exit_reason = reason;
11822 return 0;
11823 }
11824 }
11825
kvm_emulate_halt_noskip(struct kvm_vcpu * vcpu)11826 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
11827 {
11828 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
11829 }
11830 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt_noskip);
11831
kvm_emulate_halt(struct kvm_vcpu * vcpu)11832 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
11833 {
11834 int ret = kvm_skip_emulated_instruction(vcpu);
11835 /*
11836 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
11837 * KVM_EXIT_DEBUG here.
11838 */
11839 return kvm_emulate_halt_noskip(vcpu) && ret;
11840 }
11841 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt);
11842
handle_fastpath_hlt(struct kvm_vcpu * vcpu)11843 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
11844 {
11845 if (!kvm_pmu_is_fastpath_emulation_allowed(vcpu))
11846 return EXIT_FASTPATH_NONE;
11847
11848 if (!kvm_emulate_halt(vcpu))
11849 return EXIT_FASTPATH_EXIT_USERSPACE;
11850
11851 if (kvm_vcpu_running(vcpu))
11852 return EXIT_FASTPATH_REENTER_GUEST;
11853
11854 return EXIT_FASTPATH_EXIT_HANDLED;
11855 }
11856 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_hlt);
11857
kvm_emulate_ap_reset_hold(struct kvm_vcpu * vcpu)11858 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
11859 {
11860 int ret = kvm_skip_emulated_instruction(vcpu);
11861
11862 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
11863 KVM_EXIT_AP_RESET_HOLD) && ret;
11864 }
11865 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_ap_reset_hold);
11866
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)11867 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
11868 {
11869 return kvm_vcpu_apicv_active(vcpu) &&
11870 kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
11871 }
11872
kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu * vcpu)11873 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
11874 {
11875 return vcpu->arch.preempted_in_kernel;
11876 }
11877
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)11878 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11879 {
11880 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11881 return true;
11882
11883 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11884 #ifdef CONFIG_KVM_SMM
11885 kvm_test_request(KVM_REQ_SMI, vcpu) ||
11886 #endif
11887 kvm_test_request(KVM_REQ_EVENT, vcpu))
11888 return true;
11889
11890 return kvm_arch_dy_has_pending_interrupt(vcpu);
11891 }
11892
complete_emulated_io(struct kvm_vcpu * vcpu)11893 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11894 {
11895 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11896 }
11897
complete_emulated_pio(struct kvm_vcpu * vcpu)11898 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11899 {
11900 if (KVM_BUG_ON(!vcpu->arch.pio.count, vcpu->kvm))
11901 return -EIO;
11902
11903 return complete_emulated_io(vcpu);
11904 }
11905
11906 /*
11907 * Implements the following, as a state machine:
11908 *
11909 * read:
11910 * for each fragment
11911 * for each mmio piece in the fragment
11912 * write gpa, len
11913 * exit
11914 * copy data
11915 * execute insn
11916 *
11917 * write:
11918 * for each fragment
11919 * for each mmio piece in the fragment
11920 * write gpa, len
11921 * copy data
11922 * exit
11923 */
complete_emulated_mmio(struct kvm_vcpu * vcpu)11924 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11925 {
11926 struct kvm_run *run = vcpu->run;
11927 struct kvm_mmio_fragment *frag;
11928 unsigned len;
11929
11930 if (KVM_BUG_ON(!vcpu->mmio_needed, vcpu->kvm))
11931 return -EIO;
11932
11933 /* Complete previous fragment */
11934 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11935 len = min(8u, frag->len);
11936 if (!vcpu->mmio_is_write)
11937 memcpy(frag->data, run->mmio.data, len);
11938
11939 if (frag->len <= 8) {
11940 /* Switch to the next fragment. */
11941 frag++;
11942 vcpu->mmio_cur_fragment++;
11943 } else {
11944 if (WARN_ON_ONCE(frag->data == &frag->val))
11945 return -EIO;
11946
11947 /* Go forward to the next mmio piece. */
11948 frag->data += len;
11949 frag->gpa += len;
11950 frag->len -= len;
11951 }
11952
11953 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11954 vcpu->mmio_needed = 0;
11955
11956 /* FIXME: return into emulator if single-stepping. */
11957 if (vcpu->mmio_is_write)
11958 return 1;
11959 vcpu->mmio_read_completed = 1;
11960 return complete_emulated_io(vcpu);
11961 }
11962
11963 kvm_prepare_emulated_mmio_exit(vcpu, frag);
11964 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11965 return 0;
11966 }
11967
11968 /* Swap (qemu) user FPU context for the guest FPU context. */
kvm_load_guest_fpu(struct kvm_vcpu * vcpu)11969 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11970 {
11971 if (KVM_BUG_ON(vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
11972 return;
11973
11974 /* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11975 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11976 trace_kvm_fpu(1);
11977 }
11978
11979 /* When vcpu_run ends, restore user space FPU context. */
kvm_put_guest_fpu(struct kvm_vcpu * vcpu)11980 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11981 {
11982 if (KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
11983 return;
11984
11985 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11986 ++vcpu->stat.fpu_reload;
11987 trace_kvm_fpu(0);
11988 }
11989
kvm_x86_vcpu_pre_run(struct kvm_vcpu * vcpu)11990 static int kvm_x86_vcpu_pre_run(struct kvm_vcpu *vcpu)
11991 {
11992 /*
11993 * Userspace may have modified vCPU state, mark nested_run_pending as
11994 * "untrusted" to avoid triggering false-positive WARNs.
11995 */
11996 if (vcpu->arch.nested_run_pending == KVM_NESTED_RUN_PENDING)
11997 vcpu->arch.nested_run_pending = KVM_NESTED_RUN_PENDING_UNTRUSTED;
11998
11999 /*
12000 * SIPI_RECEIVED is obsolete; KVM leaves the vCPU in Wait-For-SIPI and
12001 * tracks the pending SIPI separately. SIPI_RECEIVED is still accepted
12002 * by KVM_SET_VCPU_EVENTS for backwards compatibility, but should be
12003 * converted to INIT_RECEIVED.
12004 */
12005 if (WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED))
12006 return -EINVAL;
12007
12008 /*
12009 * Disallow running the vCPU if userspace forced it into an impossible
12010 * MP_STATE, e.g. if the vCPU is in WFS but SIPI is blocked.
12011 */
12012 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED &&
12013 !kvm_apic_init_sipi_allowed(vcpu))
12014 return -EINVAL;
12015
12016 return kvm_x86_call(vcpu_pre_run)(vcpu);
12017 }
12018
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)12019 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
12020 {
12021 struct kvm_queued_exception *ex = &vcpu->arch.exception;
12022 struct kvm_run *kvm_run = vcpu->run;
12023 u64 sync_valid_fields;
12024 int r;
12025
12026 r = kvm_mmu_post_init_vm(vcpu->kvm);
12027 if (r)
12028 return r;
12029
12030 vcpu_load(vcpu);
12031 kvm_sigset_activate(vcpu);
12032 kvm_run->flags = 0;
12033 kvm_load_guest_fpu(vcpu);
12034
12035 kvm_vcpu_srcu_read_lock(vcpu);
12036 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
12037 if (!vcpu->wants_to_run) {
12038 r = -EINTR;
12039 goto out;
12040 }
12041
12042 /*
12043 * Don't bother switching APIC timer emulation from the
12044 * hypervisor timer to the software timer, the only way for the
12045 * APIC timer to be active is if userspace stuffed vCPU state,
12046 * i.e. put the vCPU into a nonsensical state. Only an INIT
12047 * will transition the vCPU out of UNINITIALIZED (without more
12048 * state stuffing from userspace), which will reset the local
12049 * APIC and thus cancel the timer or drop the IRQ (if the timer
12050 * already expired).
12051 */
12052 kvm_vcpu_srcu_read_unlock(vcpu);
12053 kvm_vcpu_block(vcpu);
12054 kvm_vcpu_srcu_read_lock(vcpu);
12055
12056 if (kvm_apic_accept_events(vcpu) < 0) {
12057 r = 0;
12058 goto out;
12059 }
12060 r = -EAGAIN;
12061 if (signal_pending(current)) {
12062 r = -EINTR;
12063 kvm_run->exit_reason = KVM_EXIT_INTR;
12064 ++vcpu->stat.signal_exits;
12065 }
12066 goto out;
12067 }
12068
12069 sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
12070 if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
12071 (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
12072 r = -EINVAL;
12073 goto out;
12074 }
12075
12076 if (kvm_run->kvm_dirty_regs) {
12077 r = sync_regs(vcpu);
12078 if (r != 0)
12079 goto out;
12080 }
12081
12082 /* re-sync apic's tpr */
12083 if (!lapic_in_kernel(vcpu)) {
12084 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
12085 r = -EINVAL;
12086 goto out;
12087 }
12088 }
12089
12090 /*
12091 * If userspace set a pending exception and L2 is active, convert it to
12092 * a pending VM-Exit if L1 wants to intercept the exception.
12093 */
12094 if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
12095 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
12096 ex->error_code)) {
12097 kvm_queue_exception_vmexit(vcpu, ex->vector,
12098 ex->has_error_code, ex->error_code,
12099 ex->has_payload, ex->payload);
12100 ex->injected = false;
12101 ex->pending = false;
12102 }
12103 vcpu->arch.exception_from_userspace = false;
12104
12105 if (unlikely(vcpu->arch.complete_userspace_io)) {
12106 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
12107 vcpu->arch.complete_userspace_io = NULL;
12108 r = cui(vcpu);
12109 if (r <= 0)
12110 goto out;
12111 } else {
12112 WARN_ON_ONCE(vcpu->arch.pio.count);
12113 WARN_ON_ONCE(vcpu->mmio_needed);
12114 }
12115
12116 if (!vcpu->wants_to_run) {
12117 r = -EINTR;
12118 goto out;
12119 }
12120
12121 r = kvm_x86_vcpu_pre_run(vcpu);
12122 if (r <= 0)
12123 goto out;
12124
12125 r = vcpu_run(vcpu);
12126
12127 out:
12128 kvm_put_guest_fpu(vcpu);
12129 if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
12130 store_regs(vcpu);
12131 post_kvm_run_save(vcpu);
12132 kvm_vcpu_srcu_read_unlock(vcpu);
12133
12134 kvm_sigset_deactivate(vcpu);
12135 vcpu_put(vcpu);
12136 return r;
12137 }
12138
__get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12139 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12140 {
12141 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
12142 /*
12143 * We are here if userspace calls get_regs() in the middle of
12144 * instruction emulation. Registers state needs to be copied
12145 * back from emulation context to vcpu. Userspace shouldn't do
12146 * that usually, but some bad designed PV devices (vmware
12147 * backdoor interface) need this to work
12148 */
12149 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
12150 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
12151 }
12152 regs->rax = kvm_rax_read(vcpu);
12153 regs->rbx = kvm_rbx_read(vcpu);
12154 regs->rcx = kvm_rcx_read(vcpu);
12155 regs->rdx = kvm_rdx_read(vcpu);
12156 regs->rsi = kvm_rsi_read(vcpu);
12157 regs->rdi = kvm_rdi_read(vcpu);
12158 regs->rsp = kvm_rsp_read(vcpu);
12159 regs->rbp = kvm_rbp_read(vcpu);
12160 #ifdef CONFIG_X86_64
12161 regs->r8 = kvm_r8_read(vcpu);
12162 regs->r9 = kvm_r9_read(vcpu);
12163 regs->r10 = kvm_r10_read(vcpu);
12164 regs->r11 = kvm_r11_read(vcpu);
12165 regs->r12 = kvm_r12_read(vcpu);
12166 regs->r13 = kvm_r13_read(vcpu);
12167 regs->r14 = kvm_r14_read(vcpu);
12168 regs->r15 = kvm_r15_read(vcpu);
12169 #endif
12170
12171 regs->rip = kvm_rip_read(vcpu);
12172 regs->rflags = kvm_get_rflags(vcpu);
12173 }
12174
kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12175 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12176 {
12177 if (vcpu->kvm->arch.has_protected_state &&
12178 vcpu->arch.guest_state_protected)
12179 return -EINVAL;
12180
12181 vcpu_load(vcpu);
12182 __get_regs(vcpu, regs);
12183 vcpu_put(vcpu);
12184 return 0;
12185 }
12186
__set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12187 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12188 {
12189 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
12190 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
12191
12192 kvm_rax_write(vcpu, regs->rax);
12193 kvm_rbx_write(vcpu, regs->rbx);
12194 kvm_rcx_write(vcpu, regs->rcx);
12195 kvm_rdx_write(vcpu, regs->rdx);
12196 kvm_rsi_write(vcpu, regs->rsi);
12197 kvm_rdi_write(vcpu, regs->rdi);
12198 kvm_rsp_write(vcpu, regs->rsp);
12199 kvm_rbp_write(vcpu, regs->rbp);
12200 #ifdef CONFIG_X86_64
12201 kvm_r8_write(vcpu, regs->r8);
12202 kvm_r9_write(vcpu, regs->r9);
12203 kvm_r10_write(vcpu, regs->r10);
12204 kvm_r11_write(vcpu, regs->r11);
12205 kvm_r12_write(vcpu, regs->r12);
12206 kvm_r13_write(vcpu, regs->r13);
12207 kvm_r14_write(vcpu, regs->r14);
12208 kvm_r15_write(vcpu, regs->r15);
12209 #endif
12210
12211 kvm_rip_write(vcpu, regs->rip);
12212 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
12213
12214 vcpu->arch.exception.pending = false;
12215 vcpu->arch.exception_vmexit.pending = false;
12216
12217 kvm_make_request(KVM_REQ_EVENT, vcpu);
12218 }
12219
kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12220 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12221 {
12222 if (vcpu->kvm->arch.has_protected_state &&
12223 vcpu->arch.guest_state_protected)
12224 return -EINVAL;
12225
12226 vcpu_load(vcpu);
12227 __set_regs(vcpu, regs);
12228 vcpu_put(vcpu);
12229 return 0;
12230 }
12231
__get_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12232 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12233 {
12234 struct desc_ptr dt;
12235
12236 if (vcpu->arch.guest_state_protected)
12237 goto skip_protected_regs;
12238
12239 kvm_handle_exception_payload_quirk(vcpu);
12240
12241 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12242 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12243 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12244 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12245 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12246 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12247
12248 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12249 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12250
12251 kvm_x86_call(get_idt)(vcpu, &dt);
12252 sregs->idt.limit = dt.size;
12253 sregs->idt.base = dt.address;
12254 kvm_x86_call(get_gdt)(vcpu, &dt);
12255 sregs->gdt.limit = dt.size;
12256 sregs->gdt.base = dt.address;
12257
12258 sregs->cr2 = vcpu->arch.cr2;
12259 sregs->cr3 = kvm_read_cr3(vcpu);
12260
12261 skip_protected_regs:
12262 sregs->cr0 = kvm_read_cr0(vcpu);
12263 sregs->cr4 = kvm_read_cr4(vcpu);
12264 sregs->cr8 = kvm_get_cr8(vcpu);
12265 sregs->efer = vcpu->arch.efer;
12266 sregs->apic_base = vcpu->arch.apic_base;
12267 }
12268
__get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12269 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12270 {
12271 __get_sregs_common(vcpu, sregs);
12272
12273 if (vcpu->arch.guest_state_protected)
12274 return;
12275
12276 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
12277 set_bit(vcpu->arch.interrupt.nr,
12278 (unsigned long *)sregs->interrupt_bitmap);
12279 }
12280
__get_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12281 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12282 {
12283 int i;
12284
12285 __get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
12286
12287 if (vcpu->arch.guest_state_protected)
12288 return;
12289
12290 if (is_pae_paging(vcpu)) {
12291 kvm_vcpu_srcu_read_lock(vcpu);
12292 for (i = 0 ; i < 4 ; i++)
12293 sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
12294 sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
12295 kvm_vcpu_srcu_read_unlock(vcpu);
12296 }
12297 }
12298
kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12299 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
12300 struct kvm_sregs *sregs)
12301 {
12302 if (vcpu->kvm->arch.has_protected_state &&
12303 vcpu->arch.guest_state_protected)
12304 return -EINVAL;
12305
12306 vcpu_load(vcpu);
12307 __get_sregs(vcpu, sregs);
12308 vcpu_put(vcpu);
12309 return 0;
12310 }
12311
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)12312 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
12313 struct kvm_mp_state *mp_state)
12314 {
12315 int r;
12316
12317 vcpu_load(vcpu);
12318 kvm_vcpu_srcu_read_lock(vcpu);
12319
12320 r = kvm_apic_accept_events(vcpu);
12321 if (r < 0)
12322 goto out;
12323 r = 0;
12324
12325 if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
12326 vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
12327 vcpu->arch.pv.pv_unhalted)
12328 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
12329 else
12330 mp_state->mp_state = vcpu->arch.mp_state;
12331
12332 out:
12333 kvm_vcpu_srcu_read_unlock(vcpu);
12334 vcpu_put(vcpu);
12335 return r;
12336 }
12337
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)12338 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
12339 struct kvm_mp_state *mp_state)
12340 {
12341 int ret = -EINVAL;
12342
12343 vcpu_load(vcpu);
12344
12345 switch (mp_state->mp_state) {
12346 case KVM_MP_STATE_UNINITIALIZED:
12347 case KVM_MP_STATE_HALTED:
12348 case KVM_MP_STATE_AP_RESET_HOLD:
12349 case KVM_MP_STATE_INIT_RECEIVED:
12350 case KVM_MP_STATE_SIPI_RECEIVED:
12351 if (!lapic_in_kernel(vcpu))
12352 goto out;
12353 break;
12354
12355 case KVM_MP_STATE_RUNNABLE:
12356 break;
12357
12358 default:
12359 goto out;
12360 }
12361
12362 /*
12363 * SIPI_RECEIVED is obsolete and no longer used internally; KVM instead
12364 * leaves the vCPU in INIT_RECIEVED (Wait-For-SIPI) and pends the SIPI.
12365 * Translate SIPI_RECEIVED as appropriate for backwards compatibility.
12366 */
12367 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
12368 mp_state->mp_state = KVM_MP_STATE_INIT_RECEIVED;
12369 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
12370 }
12371
12372 kvm_set_mp_state(vcpu, mp_state->mp_state);
12373 kvm_make_request(KVM_REQ_EVENT, vcpu);
12374
12375 ret = 0;
12376 out:
12377 vcpu_put(vcpu);
12378 return ret;
12379 }
12380
kvm_task_switch(struct kvm_vcpu * vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code)12381 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
12382 int reason, bool has_error_code, u32 error_code)
12383 {
12384 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
12385 int ret;
12386
12387 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_CET)) {
12388 u64 u_cet, s_cet;
12389
12390 /*
12391 * Check both User and Supervisor on task switches as inter-
12392 * privilege level task switches are impacted by CET at both
12393 * the current privilege level and the new privilege level, and
12394 * that information is not known at this time. The expectation
12395 * is that the guest won't require emulation of task switches
12396 * while using IBT or Shadow Stacks.
12397 */
12398 if (__kvm_emulate_msr_read(vcpu, MSR_IA32_U_CET, &u_cet) ||
12399 __kvm_emulate_msr_read(vcpu, MSR_IA32_S_CET, &s_cet))
12400 goto unhandled_task_switch;
12401
12402 if ((u_cet | s_cet) & (CET_ENDBR_EN | CET_SHSTK_EN))
12403 goto unhandled_task_switch;
12404 }
12405
12406 init_emulate_ctxt(vcpu);
12407
12408 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
12409 has_error_code, error_code);
12410
12411 /*
12412 * Report an error userspace if MMIO is needed, as KVM doesn't support
12413 * MMIO during a task switch (or any other complex operation).
12414 */
12415 if (ret || vcpu->mmio_needed)
12416 goto unhandled_task_switch;
12417
12418 kvm_rip_write(vcpu, ctxt->eip);
12419 kvm_set_rflags(vcpu, ctxt->eflags);
12420 return 1;
12421
12422 unhandled_task_switch:
12423 vcpu->mmio_needed = false;
12424 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
12425 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
12426 vcpu->run->internal.ndata = 0;
12427 return 0;
12428 }
12429 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_task_switch);
12430
kvm_is_valid_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12431 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12432 {
12433 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
12434 /*
12435 * When EFER.LME and CR0.PG are set, the processor is in
12436 * 64-bit mode (though maybe in a 32-bit code segment).
12437 * CR4.PAE and EFER.LMA must be set.
12438 */
12439 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
12440 return false;
12441 if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
12442 return false;
12443 } else {
12444 /*
12445 * Not in 64-bit mode: EFER.LMA is clear and the code
12446 * segment cannot be 64-bit.
12447 */
12448 if (sregs->efer & EFER_LMA || sregs->cs.l)
12449 return false;
12450 }
12451
12452 return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
12453 kvm_is_valid_cr0(vcpu, sregs->cr0);
12454 }
12455
__set_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs,int * mmu_reset_needed,bool update_pdptrs)12456 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
12457 int *mmu_reset_needed, bool update_pdptrs)
12458 {
12459 int idx;
12460 struct desc_ptr dt;
12461
12462 if (!kvm_is_valid_sregs(vcpu, sregs))
12463 return -EINVAL;
12464
12465 if (kvm_apic_set_base(vcpu, sregs->apic_base, true))
12466 return -EINVAL;
12467
12468 if (vcpu->arch.guest_state_protected)
12469 return 0;
12470
12471 dt.size = sregs->idt.limit;
12472 dt.address = sregs->idt.base;
12473 kvm_x86_call(set_idt)(vcpu, &dt);
12474 dt.size = sregs->gdt.limit;
12475 dt.address = sregs->gdt.base;
12476 kvm_x86_call(set_gdt)(vcpu, &dt);
12477
12478 vcpu->arch.cr2 = sregs->cr2;
12479 *mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
12480 vcpu->arch.cr3 = sregs->cr3;
12481 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12482 kvm_x86_call(post_set_cr3)(vcpu, sregs->cr3);
12483
12484 kvm_set_cr8(vcpu, sregs->cr8);
12485
12486 *mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
12487 kvm_x86_call(set_efer)(vcpu, sregs->efer);
12488
12489 *mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
12490 kvm_x86_call(set_cr0)(vcpu, sregs->cr0);
12491
12492 *mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
12493 kvm_x86_call(set_cr4)(vcpu, sregs->cr4);
12494
12495 if (update_pdptrs) {
12496 idx = srcu_read_lock(&vcpu->kvm->srcu);
12497 if (is_pae_paging(vcpu)) {
12498 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
12499 *mmu_reset_needed = 1;
12500 }
12501 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12502 }
12503
12504 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12505 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12506 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12507 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12508 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12509 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12510
12511 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12512 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12513
12514 update_cr8_intercept(vcpu);
12515
12516 /* Older userspace won't unhalt the vcpu on reset. */
12517 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
12518 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
12519 !is_protmode(vcpu))
12520 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12521
12522 return 0;
12523 }
12524
__set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12525 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12526 {
12527 int pending_vec, max_bits;
12528 int mmu_reset_needed = 0;
12529 int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
12530
12531 if (ret)
12532 return ret;
12533
12534 if (mmu_reset_needed) {
12535 kvm_mmu_reset_context(vcpu);
12536 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12537 }
12538
12539 max_bits = KVM_NR_INTERRUPTS;
12540 pending_vec = find_first_bit(
12541 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
12542
12543 if (pending_vec < max_bits) {
12544 kvm_queue_interrupt(vcpu, pending_vec, false);
12545 pr_debug("Set back pending irq %d\n", pending_vec);
12546 kvm_make_request(KVM_REQ_EVENT, vcpu);
12547 }
12548 return 0;
12549 }
12550
__set_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12551 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12552 {
12553 int mmu_reset_needed = 0;
12554 bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
12555 bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
12556 !(sregs2->efer & EFER_LMA);
12557 int i, ret;
12558
12559 if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
12560 return -EINVAL;
12561
12562 if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
12563 return -EINVAL;
12564
12565 ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
12566 &mmu_reset_needed, !valid_pdptrs);
12567 if (ret)
12568 return ret;
12569
12570 if (valid_pdptrs) {
12571 for (i = 0; i < 4 ; i++)
12572 kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
12573
12574 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
12575 mmu_reset_needed = 1;
12576 vcpu->arch.pdptrs_from_userspace = true;
12577 }
12578 if (mmu_reset_needed) {
12579 kvm_mmu_reset_context(vcpu);
12580 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12581 }
12582 return 0;
12583 }
12584
kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12585 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
12586 struct kvm_sregs *sregs)
12587 {
12588 int ret;
12589
12590 if (vcpu->kvm->arch.has_protected_state &&
12591 vcpu->arch.guest_state_protected)
12592 return -EINVAL;
12593
12594 vcpu_load(vcpu);
12595 ret = __set_sregs(vcpu, sregs);
12596 vcpu_put(vcpu);
12597 return ret;
12598 }
12599
kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm * kvm)12600 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
12601 {
12602 bool set = false;
12603 struct kvm_vcpu *vcpu;
12604 unsigned long i;
12605
12606 if (!enable_apicv)
12607 return;
12608
12609 down_write(&kvm->arch.apicv_update_lock);
12610
12611 kvm_for_each_vcpu(i, vcpu, kvm) {
12612 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
12613 set = true;
12614 break;
12615 }
12616 }
12617 __kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
12618 up_write(&kvm->arch.apicv_update_lock);
12619 }
12620
kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu * vcpu,struct kvm_guest_debug * dbg)12621 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
12622 struct kvm_guest_debug *dbg)
12623 {
12624 unsigned long rflags;
12625 int i, r;
12626
12627 if (vcpu->arch.guest_state_protected)
12628 return -EINVAL;
12629
12630 vcpu_load(vcpu);
12631
12632 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
12633 r = -EBUSY;
12634 if (kvm_is_exception_pending(vcpu) || vcpu->arch.exception.injected)
12635 goto out;
12636 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
12637 kvm_queue_exception(vcpu, DB_VECTOR);
12638 else
12639 kvm_queue_exception(vcpu, BP_VECTOR);
12640 }
12641
12642 /*
12643 * Read rflags as long as potentially injected trace flags are still
12644 * filtered out.
12645 */
12646 rflags = kvm_get_rflags(vcpu);
12647
12648 vcpu->guest_debug = dbg->control;
12649 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
12650 vcpu->guest_debug = 0;
12651
12652 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
12653 for (i = 0; i < KVM_NR_DB_REGS; ++i)
12654 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
12655 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
12656 } else {
12657 for (i = 0; i < KVM_NR_DB_REGS; i++)
12658 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
12659 }
12660 kvm_update_dr7(vcpu);
12661
12662 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12663 vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
12664
12665 /*
12666 * Trigger an rflags update that will inject or remove the trace
12667 * flags.
12668 */
12669 kvm_set_rflags(vcpu, rflags);
12670
12671 kvm_x86_call(update_exception_bitmap)(vcpu);
12672
12673 kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12674
12675 r = 0;
12676
12677 out:
12678 vcpu_put(vcpu);
12679 return r;
12680 }
12681
12682 /*
12683 * Translate a guest virtual address to a guest physical address.
12684 */
kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu * vcpu,struct kvm_translation * tr)12685 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12686 struct kvm_translation *tr)
12687 {
12688 unsigned long vaddr = tr->linear_address;
12689 gpa_t gpa;
12690 int idx;
12691
12692 vcpu_load(vcpu);
12693
12694 idx = srcu_read_lock(&vcpu->kvm->srcu);
12695 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
12696 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12697 tr->physical_address = gpa;
12698 tr->valid = gpa != INVALID_GPA;
12699 tr->writeable = 1;
12700 tr->usermode = 0;
12701
12702 vcpu_put(vcpu);
12703 return 0;
12704 }
12705
kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12706 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12707 {
12708 struct fxregs_state *fxsave;
12709
12710 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12711 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12712
12713 vcpu_load(vcpu);
12714
12715 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12716 memcpy(fpu->fpr, fxsave->st_space, 128);
12717 fpu->fcw = fxsave->cwd;
12718 fpu->fsw = fxsave->swd;
12719 fpu->ftwx = fxsave->twd;
12720 fpu->last_opcode = fxsave->fop;
12721 fpu->last_ip = fxsave->rip;
12722 fpu->last_dp = fxsave->rdp;
12723 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
12724
12725 vcpu_put(vcpu);
12726 return 0;
12727 }
12728
kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12729 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12730 {
12731 struct fxregs_state *fxsave;
12732
12733 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12734 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12735
12736 vcpu_load(vcpu);
12737
12738 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12739
12740 memcpy(fxsave->st_space, fpu->fpr, 128);
12741 fxsave->cwd = fpu->fcw;
12742 fxsave->swd = fpu->fsw;
12743 fxsave->twd = fpu->ftwx;
12744 fxsave->fop = fpu->last_opcode;
12745 fxsave->rip = fpu->last_ip;
12746 fxsave->rdp = fpu->last_dp;
12747 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
12748
12749 vcpu_put(vcpu);
12750 return 0;
12751 }
12752
store_regs(struct kvm_vcpu * vcpu)12753 static void store_regs(struct kvm_vcpu *vcpu)
12754 {
12755 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12756
12757 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12758 __get_regs(vcpu, &vcpu->run->s.regs.regs);
12759
12760 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12761 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12762
12763 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12764 kvm_vcpu_ioctl_x86_get_vcpu_events(
12765 vcpu, &vcpu->run->s.regs.events);
12766 }
12767
sync_regs(struct kvm_vcpu * vcpu)12768 static int sync_regs(struct kvm_vcpu *vcpu)
12769 {
12770 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12771 __set_regs(vcpu, &vcpu->run->s.regs.regs);
12772 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12773 }
12774
12775 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
12776 struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12777
12778 if (__set_sregs(vcpu, &sregs))
12779 return -EINVAL;
12780
12781 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12782 }
12783
12784 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
12785 struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12786
12787 if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
12788 return -EINVAL;
12789
12790 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12791 }
12792
12793 return 0;
12794 }
12795
12796 #define PERF_MEDIATED_PMU_MSG \
12797 "Failed to enable mediated vPMU, try disabling system wide perf events and nmi_watchdog.\n"
12798
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)12799 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
12800 {
12801 int r;
12802
12803 if (kvm_check_tsc_unstable() && kvm->created_vcpus)
12804 pr_warn_once("SMP vm created on host with unstable TSC; "
12805 "guest TSC will not be reliable\n");
12806
12807 if (!kvm->arch.max_vcpu_ids)
12808 kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12809
12810 if (id >= kvm->arch.max_vcpu_ids)
12811 return -EINVAL;
12812
12813 /*
12814 * Note, any actions done by .vcpu_create() must be idempotent with
12815 * respect to creating multiple vCPUs, and therefore are not undone if
12816 * creating a vCPU fails (including failure during pre-create).
12817 */
12818 r = kvm_x86_call(vcpu_precreate)(kvm);
12819 if (r)
12820 return r;
12821
12822 if (enable_mediated_pmu && kvm->arch.enable_pmu &&
12823 !kvm->arch.created_mediated_pmu) {
12824 if (irqchip_in_kernel(kvm)) {
12825 r = perf_create_mediated_pmu();
12826 if (r) {
12827 pr_warn_ratelimited(PERF_MEDIATED_PMU_MSG);
12828 return r;
12829 }
12830 kvm->arch.created_mediated_pmu = true;
12831 } else {
12832 kvm->arch.enable_pmu = false;
12833 }
12834 }
12835 return 0;
12836 }
12837
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)12838 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
12839 {
12840 struct page *page;
12841 int r;
12842
12843 vcpu->arch.last_vmentry_cpu = -1;
12844 vcpu->arch.regs_avail = ~0;
12845 vcpu->arch.regs_dirty = ~0;
12846
12847 kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
12848
12849 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
12850 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12851 else
12852 kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);
12853
12854 r = kvm_mmu_create(vcpu);
12855 if (r < 0)
12856 return r;
12857
12858 r = kvm_create_lapic(vcpu);
12859 if (r < 0)
12860 goto fail_mmu_destroy;
12861
12862 r = -ENOMEM;
12863
12864 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
12865 if (!page)
12866 goto fail_free_lapic;
12867 vcpu->arch.pio_data = page_address(page);
12868
12869 vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
12870 GFP_KERNEL_ACCOUNT);
12871 vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12872 GFP_KERNEL_ACCOUNT);
12873 if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
12874 goto fail_free_mce_banks;
12875 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12876
12877 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12878 GFP_KERNEL_ACCOUNT))
12879 goto fail_free_mce_banks;
12880
12881 if (!alloc_emulate_ctxt(vcpu))
12882 goto free_wbinvd_dirty_mask;
12883
12884 if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
12885 pr_err("failed to allocate vcpu's fpu\n");
12886 goto free_emulate_ctxt;
12887 }
12888
12889 kvm_async_pf_hash_reset(vcpu);
12890
12891 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) {
12892 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12893 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12894 vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12895 }
12896 kvm_pmu_init(vcpu);
12897
12898 vcpu->arch.pending_external_vector = -1;
12899 vcpu->arch.preempted_in_kernel = false;
12900
12901 #if IS_ENABLED(CONFIG_HYPERV)
12902 vcpu->arch.hv_root_tdp = INVALID_PAGE;
12903 #endif
12904
12905 r = kvm_x86_call(vcpu_create)(vcpu);
12906 if (r)
12907 goto free_guest_fpu;
12908
12909 kvm_xen_init_vcpu(vcpu);
12910 vcpu_load(vcpu);
12911 kvm_vcpu_after_set_cpuid(vcpu);
12912 kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12913 kvm_vcpu_reset(vcpu, false);
12914 kvm_init_mmu(vcpu);
12915 vcpu_put(vcpu);
12916 return 0;
12917
12918 free_guest_fpu:
12919 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12920 free_emulate_ctxt:
12921 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12922 free_wbinvd_dirty_mask:
12923 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12924 fail_free_mce_banks:
12925 kfree(vcpu->arch.mce_banks);
12926 kfree(vcpu->arch.mci_ctl2_banks);
12927 free_page((unsigned long)vcpu->arch.pio_data);
12928 fail_free_lapic:
12929 kvm_free_lapic(vcpu);
12930 fail_mmu_destroy:
12931 kvm_mmu_destroy(vcpu);
12932 return r;
12933 }
12934
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)12935 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12936 {
12937 if (mutex_lock_killable(&vcpu->mutex))
12938 return;
12939 vcpu_load(vcpu);
12940 kvm_synchronize_tsc(vcpu, NULL);
12941 vcpu_put(vcpu);
12942
12943 /* poll control enabled by default */
12944 vcpu->arch.msr_kvm_poll_control = 1;
12945
12946 mutex_unlock(&vcpu->mutex);
12947 }
12948
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)12949 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12950 {
12951 int idx, cpu;
12952
12953 kvm_clear_async_pf_completion_queue(vcpu);
12954 kvm_mmu_unload(vcpu);
12955
12956 kvmclock_reset(vcpu);
12957
12958 for_each_possible_cpu(cpu)
12959 cmpxchg(per_cpu_ptr(&last_vcpu, cpu), vcpu, NULL);
12960
12961 kvm_x86_call(vcpu_free)(vcpu);
12962
12963 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12964 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12965 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12966
12967 kvm_xen_destroy_vcpu(vcpu);
12968 kvm_hv_vcpu_uninit(vcpu);
12969 kvm_pmu_destroy(vcpu);
12970 kfree(vcpu->arch.mce_banks);
12971 kfree(vcpu->arch.mci_ctl2_banks);
12972 kvm_free_lapic(vcpu);
12973 idx = srcu_read_lock(&vcpu->kvm->srcu);
12974 kvm_mmu_destroy(vcpu);
12975 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12976 free_page((unsigned long)vcpu->arch.pio_data);
12977 kvfree(vcpu->arch.cpuid_entries);
12978 }
12979
kvm_xstate_reset(struct kvm_vcpu * vcpu,bool init_event)12980 static void kvm_xstate_reset(struct kvm_vcpu *vcpu, bool init_event)
12981 {
12982 struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12983 u64 xfeatures_mask;
12984 bool fpu_in_use;
12985 int i;
12986
12987 /*
12988 * Guest FPU state is zero allocated and so doesn't need to be manually
12989 * cleared on RESET, i.e. during vCPU creation.
12990 */
12991 if (!init_event || !fpstate)
12992 return;
12993
12994 /*
12995 * On INIT, only select XSTATE components are zeroed, most components
12996 * are unchanged. Currently, the only components that are zeroed and
12997 * supported by KVM are MPX and CET related.
12998 */
12999 xfeatures_mask = (kvm_caps.supported_xcr0 | kvm_caps.supported_xss) &
13000 (XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR |
13001 XFEATURE_MASK_CET_ALL);
13002 if (!xfeatures_mask)
13003 return;
13004
13005 BUILD_BUG_ON(sizeof(xfeatures_mask) * BITS_PER_BYTE <= XFEATURE_MAX);
13006
13007 /*
13008 * Unload guest FPU state (if necessary) before zeroing XSTATE fields
13009 * as the kernel can only modify the state when its resident in memory,
13010 * i.e. when it's not loaded into hardware.
13011 *
13012 * WARN if the vCPU's desire to run, i.e. whether or not its in KVM_RUN,
13013 * doesn't match the loaded/in-use state of the FPU, as KVM_RUN is the
13014 * only path that can trigger INIT emulation _and_ loads FPU state, and
13015 * KVM_RUN should _always_ load FPU state.
13016 */
13017 WARN_ON_ONCE(vcpu->wants_to_run != fpstate->in_use);
13018 fpu_in_use = fpstate->in_use;
13019 if (fpu_in_use)
13020 kvm_put_guest_fpu(vcpu);
13021 for_each_set_bit(i, (unsigned long *)&xfeatures_mask, XFEATURE_MAX)
13022 fpstate_clear_xstate_component(fpstate, i);
13023 if (fpu_in_use)
13024 kvm_load_guest_fpu(vcpu);
13025 }
13026
kvm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)13027 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
13028 {
13029 struct kvm_cpuid_entry2 *cpuid_0x1;
13030 unsigned long old_cr0 = kvm_read_cr0(vcpu);
13031 unsigned long new_cr0;
13032
13033 /*
13034 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
13035 * to handle side effects. RESET emulation hits those flows and relies
13036 * on emulated/virtualized registers, including those that are loaded
13037 * into hardware, to be zeroed at vCPU creation. Use CRs as a sentinel
13038 * to detect improper or missing initialization.
13039 */
13040 WARN_ON_ONCE(!init_event &&
13041 (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
13042
13043 /*
13044 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
13045 * possible to INIT the vCPU while L2 is active. Force the vCPU back
13046 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
13047 * bits), i.e. virtualization is disabled.
13048 */
13049 if (is_guest_mode(vcpu))
13050 kvm_leave_nested(vcpu);
13051
13052 kvm_lapic_reset(vcpu, init_event);
13053
13054 WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
13055 vcpu->arch.hflags = 0;
13056
13057 vcpu->arch.smi_pending = 0;
13058 vcpu->arch.smi_count = 0;
13059 atomic_set(&vcpu->arch.nmi_queued, 0);
13060 vcpu->arch.nmi_pending = 0;
13061 vcpu->arch.nmi_injected = false;
13062 kvm_clear_interrupt_queue(vcpu);
13063 kvm_clear_exception_queue(vcpu);
13064
13065 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
13066 kvm_update_dr0123(vcpu);
13067 vcpu->arch.dr6 = DR6_ACTIVE_LOW;
13068 vcpu->arch.dr7 = DR7_FIXED_1;
13069 kvm_update_dr7(vcpu);
13070
13071 vcpu->arch.cr2 = 0;
13072
13073 kvm_make_request(KVM_REQ_EVENT, vcpu);
13074 vcpu->arch.apf.msr_en_val = 0;
13075 vcpu->arch.apf.msr_int_val = 0;
13076 vcpu->arch.st.msr_val = 0;
13077
13078 kvmclock_reset(vcpu);
13079
13080 kvm_clear_async_pf_completion_queue(vcpu);
13081 kvm_async_pf_hash_reset(vcpu);
13082 vcpu->arch.apf.halted = false;
13083
13084 kvm_xstate_reset(vcpu, init_event);
13085
13086 if (!init_event) {
13087 vcpu->arch.smbase = 0x30000;
13088
13089 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
13090
13091 vcpu->arch.msr_misc_features_enables = 0;
13092 vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
13093 MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
13094
13095 __kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
13096 kvm_msr_write(vcpu, MSR_IA32_XSS, 0);
13097 }
13098
13099 /* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
13100 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
13101 kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
13102
13103 /*
13104 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
13105 * if no CPUID match is found. Note, it's impossible to get a match at
13106 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
13107 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
13108 * on RESET. But, go through the motions in case that's ever remedied.
13109 */
13110 cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
13111 kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
13112
13113 kvm_x86_call(vcpu_reset)(vcpu, init_event);
13114
13115 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
13116 kvm_rip_write(vcpu, 0xfff0);
13117
13118 vcpu->arch.cr3 = 0;
13119 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
13120
13121 /*
13122 * CR0.CD/NW are set on RESET, preserved on INIT. Note, some versions
13123 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
13124 * (or qualify) that with a footnote stating that CD/NW are preserved.
13125 */
13126 new_cr0 = X86_CR0_ET;
13127 if (init_event)
13128 new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
13129 else
13130 new_cr0 |= X86_CR0_NW | X86_CR0_CD;
13131
13132 kvm_x86_call(set_cr0)(vcpu, new_cr0);
13133 kvm_x86_call(set_cr4)(vcpu, 0);
13134 kvm_x86_call(set_efer)(vcpu, 0);
13135 kvm_x86_call(update_exception_bitmap)(vcpu);
13136
13137 /*
13138 * On the standard CR0/CR4/EFER modification paths, there are several
13139 * complex conditions determining whether the MMU has to be reset and/or
13140 * which PCIDs have to be flushed. However, CR0.WP and the paging-related
13141 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
13142 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
13143 * CR0 will be '0' prior to RESET). So we only need to check CR0.PG here.
13144 */
13145 if (old_cr0 & X86_CR0_PG) {
13146 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
13147 kvm_mmu_reset_context(vcpu);
13148 }
13149
13150 /*
13151 * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
13152 * APM states the TLBs are untouched by INIT, but it also states that
13153 * the TLBs are flushed on "External initialization of the processor."
13154 * Flush the guest TLB regardless of vendor, there is no meaningful
13155 * benefit in relying on the guest to flush the TLB immediately after
13156 * INIT. A spurious TLB flush is benign and likely negligible from a
13157 * performance perspective.
13158 */
13159 if (init_event)
13160 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
13161 }
13162 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_reset);
13163
kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)13164 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
13165 {
13166 struct kvm_segment cs;
13167
13168 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
13169 cs.selector = vector << 8;
13170 cs.base = vector << 12;
13171 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
13172 kvm_rip_write(vcpu, 0);
13173 }
13174 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_deliver_sipi_vector);
13175
kvm_arch_enable_virtualization(void)13176 void kvm_arch_enable_virtualization(void)
13177 {
13178 x86_virt_register_emergency_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
13179 }
13180
kvm_arch_disable_virtualization(void)13181 void kvm_arch_disable_virtualization(void)
13182 {
13183 x86_virt_unregister_emergency_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
13184 }
13185
kvm_arch_enable_virtualization_cpu(void)13186 int kvm_arch_enable_virtualization_cpu(void)
13187 {
13188 struct kvm *kvm;
13189 struct kvm_vcpu *vcpu;
13190 unsigned long i;
13191 int ret;
13192 u64 local_tsc;
13193 u64 max_tsc = 0;
13194 bool stable, backwards_tsc = false;
13195
13196 kvm_user_return_msr_cpu_online();
13197
13198 ret = kvm_x86_check_processor_compatibility();
13199 if (ret)
13200 return ret;
13201
13202 ret = kvm_x86_call(enable_virtualization_cpu)();
13203 if (ret != 0)
13204 return ret;
13205
13206 local_tsc = rdtsc();
13207 stable = !kvm_check_tsc_unstable();
13208 list_for_each_entry(kvm, &vm_list, vm_list) {
13209 kvm_for_each_vcpu(i, vcpu, kvm) {
13210 if (!stable && vcpu->cpu == smp_processor_id())
13211 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
13212 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
13213 backwards_tsc = true;
13214 if (vcpu->arch.last_host_tsc > max_tsc)
13215 max_tsc = vcpu->arch.last_host_tsc;
13216 }
13217 }
13218 }
13219
13220 /*
13221 * Sometimes, even reliable TSCs go backwards. This happens on
13222 * platforms that reset TSC during suspend or hibernate actions, but
13223 * maintain synchronization. We must compensate. Fortunately, we can
13224 * detect that condition here, which happens early in CPU bringup,
13225 * before any KVM threads can be running. Unfortunately, we can't
13226 * bring the TSCs fully up to date with real time, as we aren't yet far
13227 * enough into CPU bringup that we know how much real time has actually
13228 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
13229 * variables that haven't been updated yet.
13230 *
13231 * So we simply find the maximum observed TSC above, then record the
13232 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
13233 * the adjustment will be applied. Note that we accumulate
13234 * adjustments, in case multiple suspend cycles happen before some VCPU
13235 * gets a chance to run again. In the event that no KVM threads get a
13236 * chance to run, we will miss the entire elapsed period, as we'll have
13237 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
13238 * loose cycle time. This isn't too big a deal, since the loss will be
13239 * uniform across all VCPUs (not to mention the scenario is extremely
13240 * unlikely). It is possible that a second hibernate recovery happens
13241 * much faster than a first, causing the observed TSC here to be
13242 * smaller; this would require additional padding adjustment, which is
13243 * why we set last_host_tsc to the local tsc observed here.
13244 *
13245 * N.B. - this code below runs only on platforms with reliable TSC,
13246 * as that is the only way backwards_tsc is set above. Also note
13247 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
13248 * have the same delta_cyc adjustment applied if backwards_tsc
13249 * is detected. Note further, this adjustment is only done once,
13250 * as we reset last_host_tsc on all VCPUs to stop this from being
13251 * called multiple times (one for each physical CPU bringup).
13252 *
13253 * Platforms with unreliable TSCs don't have to deal with this, they
13254 * will be compensated by the logic in vcpu_load, which sets the TSC to
13255 * catchup mode. This will catchup all VCPUs to real time, but cannot
13256 * guarantee that they stay in perfect synchronization.
13257 */
13258 if (backwards_tsc) {
13259 u64 delta_cyc = max_tsc - local_tsc;
13260 list_for_each_entry(kvm, &vm_list, vm_list) {
13261 kvm->arch.backwards_tsc_observed = true;
13262 kvm_for_each_vcpu(i, vcpu, kvm) {
13263 vcpu->arch.tsc_offset_adjustment += delta_cyc;
13264 vcpu->arch.last_host_tsc = local_tsc;
13265 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
13266 }
13267
13268 /*
13269 * We have to disable TSC offset matching.. if you were
13270 * booting a VM while issuing an S4 host suspend....
13271 * you may have some problem. Solving this issue is
13272 * left as an exercise to the reader.
13273 */
13274 kvm->arch.last_tsc_nsec = 0;
13275 kvm->arch.last_tsc_write = 0;
13276 }
13277
13278 }
13279 return 0;
13280 }
13281
kvm_arch_shutdown(void)13282 void kvm_arch_shutdown(void)
13283 {
13284 /*
13285 * Set virt_rebooting to indicate that KVM has asynchronously disabled
13286 * hardware virtualization, i.e. that errors and/or exceptions on SVM
13287 * and VMX instructions are expected and should be ignored.
13288 */
13289 virt_rebooting = true;
13290
13291 /*
13292 * Ensure virt_rebooting is visible before IPIs are sent to other CPUs
13293 * to disable virtualization. Effectively pairs with the reception of
13294 * the IPI (virt_rebooting is read in task/exception context, but only
13295 * _needs_ to be read as %true after the IPI function callback disables
13296 * virtualization).
13297 */
13298 smp_wmb();
13299 }
13300
kvm_arch_disable_virtualization_cpu(void)13301 void kvm_arch_disable_virtualization_cpu(void)
13302 {
13303 kvm_x86_call(disable_virtualization_cpu)();
13304
13305 /*
13306 * Leave the user-return notifiers as-is when disabling virtualization
13307 * for reboot, i.e. when disabling via IPI function call, and instead
13308 * pin kvm.ko (if it's a module) to defend against use-after-free (in
13309 * the *very* unlikely scenario module unload is racing with reboot).
13310 * On a forced reboot, tasks aren't frozen before shutdown, and so KVM
13311 * could be actively modifying user-return MSR state when the IPI to
13312 * disable virtualization arrives. Handle the extreme edge case here
13313 * instead of trying to account for it in the normal flows.
13314 */
13315 if (in_task() || WARN_ON_ONCE(!virt_rebooting))
13316 drop_user_return_notifiers();
13317 else
13318 __module_get(THIS_MODULE);
13319 }
13320
kvm_vcpu_is_reset_bsp(struct kvm_vcpu * vcpu)13321 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
13322 {
13323 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
13324 }
13325 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_is_reset_bsp);
13326
kvm_vcpu_is_bsp(struct kvm_vcpu * vcpu)13327 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
13328 {
13329 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
13330 }
13331
kvm_arch_free_vm(struct kvm * kvm)13332 void kvm_arch_free_vm(struct kvm *kvm)
13333 {
13334 #if IS_ENABLED(CONFIG_HYPERV)
13335 kfree(kvm->arch.hv_pa_pg);
13336 #endif
13337 __kvm_arch_free_vm(kvm);
13338 }
13339
13340
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)13341 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
13342 {
13343 int ret;
13344 unsigned long flags;
13345
13346 if (!kvm_is_vm_type_supported(type))
13347 return -EINVAL;
13348
13349 kvm->arch.vm_type = type;
13350 kvm->arch.has_private_mem =
13351 (type == KVM_X86_SW_PROTECTED_VM);
13352 /* Decided by the vendor code for other VM types. */
13353 kvm->arch.pre_fault_allowed =
13354 type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
13355 kvm->arch.disabled_quirks = kvm_caps.inapplicable_quirks & kvm_caps.supported_quirks;
13356
13357 ret = kvm_page_track_init(kvm);
13358 if (ret)
13359 goto out;
13360
13361 ret = kvm_mmu_init_vm(kvm);
13362 if (ret)
13363 goto out_cleanup_page_track;
13364
13365 ret = kvm_x86_call(vm_init)(kvm);
13366 if (ret)
13367 goto out_uninit_mmu;
13368
13369 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
13370
13371 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
13372 mutex_init(&kvm->arch.apic_map_lock);
13373 seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
13374 ratelimit_state_init(&kvm->arch.kvmclock_update_rs, HZ, 10);
13375 ratelimit_set_flags(&kvm->arch.kvmclock_update_rs, RATELIMIT_MSG_ON_RELEASE);
13376 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
13377
13378 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
13379 pvclock_update_vm_gtod_copy(kvm);
13380 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
13381
13382 kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
13383 kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
13384 kvm->arch.guest_can_read_msr_platform_info = true;
13385 kvm->arch.enable_pmu = enable_pmu;
13386
13387 #if IS_ENABLED(CONFIG_HYPERV)
13388 spin_lock_init(&kvm->arch.hv_root_tdp_lock);
13389 kvm->arch.hv_root_tdp = INVALID_PAGE;
13390 #endif
13391
13392 kvm_apicv_init(kvm);
13393 kvm_hv_init_vm(kvm);
13394 kvm_xen_init_vm(kvm);
13395
13396 if (ignore_msrs && !report_ignored_msrs) {
13397 pr_warn_once("Running KVM with ignore_msrs=1 and report_ignored_msrs=0 is not a\n"
13398 "a supported configuration. Lying to the guest about the existence of MSRs\n"
13399 "may cause the guest operating system to hang or produce errors. If a guest\n"
13400 "does not run without ignore_msrs=1, please report it to kvm@vger.kernel.org.\n");
13401 }
13402
13403 once_init(&kvm->arch.nx_once);
13404 return 0;
13405
13406 out_uninit_mmu:
13407 kvm_mmu_uninit_vm(kvm);
13408 out_cleanup_page_track:
13409 kvm_page_track_cleanup(kvm);
13410 out:
13411 return ret;
13412 }
13413
13414 /**
13415 * __x86_set_memory_region: Setup KVM internal memory slot
13416 *
13417 * @kvm: the kvm pointer to the VM.
13418 * @id: the slot ID to setup.
13419 * @gpa: the GPA to install the slot (unused when @size == 0).
13420 * @size: the size of the slot. Set to zero to uninstall a slot.
13421 *
13422 * This function helps to setup a KVM internal memory slot. Specify
13423 * @size > 0 to install a new slot, while @size == 0 to uninstall a
13424 * slot. The return code can be one of the following:
13425 *
13426 * HVA: on success (uninstall will return a bogus HVA)
13427 * -errno: on error
13428 *
13429 * The caller should always use IS_ERR() to check the return value
13430 * before use. Note, the KVM internal memory slots are guaranteed to
13431 * remain valid and unchanged until the VM is destroyed, i.e., the
13432 * GPA->HVA translation will not change. However, the HVA is a user
13433 * address, i.e. its accessibility is not guaranteed, and must be
13434 * accessed via __copy_{to,from}_user().
13435 */
__x86_set_memory_region(struct kvm * kvm,int id,gpa_t gpa,u32 size)13436 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
13437 u32 size)
13438 {
13439 int i, r;
13440 unsigned long hva, old_npages;
13441 struct kvm_memslots *slots = kvm_memslots(kvm);
13442 struct kvm_memory_slot *slot;
13443
13444 lockdep_assert_held(&kvm->slots_lock);
13445
13446 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
13447 return ERR_PTR_USR(-EINVAL);
13448
13449 slot = id_to_memslot(slots, id);
13450 if (size) {
13451 if (slot && slot->npages)
13452 return ERR_PTR_USR(-EEXIST);
13453
13454 /*
13455 * MAP_SHARED to prevent internal slot pages from being moved
13456 * by fork()/COW.
13457 */
13458 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
13459 MAP_SHARED | MAP_ANONYMOUS, 0);
13460 if (IS_ERR_VALUE(hva))
13461 return (void __user *)hva;
13462 } else {
13463 if (!slot || !slot->npages)
13464 return NULL;
13465
13466 old_npages = slot->npages;
13467 hva = slot->userspace_addr;
13468 }
13469
13470 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
13471 struct kvm_userspace_memory_region2 m;
13472
13473 m.slot = id | (i << 16);
13474 m.flags = 0;
13475 m.guest_phys_addr = gpa;
13476 m.userspace_addr = hva;
13477 m.memory_size = size;
13478 r = kvm_set_internal_memslot(kvm, &m);
13479 if (r < 0)
13480 return ERR_PTR_USR(r);
13481 }
13482
13483 if (!size)
13484 vm_munmap(hva, old_npages * PAGE_SIZE);
13485
13486 return (void __user *)hva;
13487 }
13488 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__x86_set_memory_region);
13489
kvm_arch_pre_destroy_vm(struct kvm * kvm)13490 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
13491 {
13492 /*
13493 * Stop all background workers and kthreads before destroying vCPUs, as
13494 * iterating over vCPUs in a different task while vCPUs are being freed
13495 * is unsafe, i.e. will lead to use-after-free. The PIT also needs to
13496 * be stopped before IRQ routing is freed.
13497 */
13498 #ifdef CONFIG_KVM_IOAPIC
13499 kvm_free_pit(kvm);
13500 #endif
13501
13502 kvm_mmu_pre_destroy_vm(kvm);
13503 kvm_x86_call(vm_pre_destroy)(kvm);
13504 }
13505
kvm_arch_destroy_vm(struct kvm * kvm)13506 void kvm_arch_destroy_vm(struct kvm *kvm)
13507 {
13508 if (current->mm == kvm->mm) {
13509 /*
13510 * Free memory regions allocated on behalf of userspace,
13511 * unless the memory map has changed due to process exit
13512 * or fd copying.
13513 */
13514 mutex_lock(&kvm->slots_lock);
13515 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
13516 0, 0);
13517 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
13518 0, 0);
13519 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
13520 mutex_unlock(&kvm->slots_lock);
13521 }
13522 if (kvm->arch.created_mediated_pmu)
13523 perf_release_mediated_pmu();
13524 kvm_destroy_vcpus(kvm);
13525 kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
13526 #ifdef CONFIG_KVM_IOAPIC
13527 kvm_pic_destroy(kvm);
13528 kvm_ioapic_destroy(kvm);
13529 #endif
13530 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
13531 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
13532 kvm_mmu_uninit_vm(kvm);
13533 kvm_page_track_cleanup(kvm);
13534 kvm_xen_destroy_vm(kvm);
13535 kvm_hv_destroy_vm(kvm);
13536 kvm_x86_call(vm_destroy)(kvm);
13537 }
13538
memslot_rmap_free(struct kvm_memory_slot * slot)13539 static void memslot_rmap_free(struct kvm_memory_slot *slot)
13540 {
13541 int i;
13542
13543 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13544 vfree(slot->arch.rmap[i]);
13545 slot->arch.rmap[i] = NULL;
13546 }
13547 }
13548
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)13549 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
13550 {
13551 int i;
13552
13553 memslot_rmap_free(slot);
13554
13555 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13556 vfree(slot->arch.lpage_info[i - 1]);
13557 slot->arch.lpage_info[i - 1] = NULL;
13558 }
13559
13560 kvm_page_track_free_memslot(slot);
13561 }
13562
memslot_rmap_alloc(struct kvm_memory_slot * slot,unsigned long npages)13563 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
13564 {
13565 const int sz = sizeof(*slot->arch.rmap[0]);
13566 int i;
13567
13568 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13569 int level = i + 1;
13570 int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13571
13572 if (slot->arch.rmap[i])
13573 continue;
13574
13575 slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
13576 if (!slot->arch.rmap[i]) {
13577 memslot_rmap_free(slot);
13578 return -ENOMEM;
13579 }
13580 }
13581
13582 return 0;
13583 }
13584
kvm_alloc_memslot_metadata(struct kvm * kvm,struct kvm_memory_slot * slot)13585 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
13586 struct kvm_memory_slot *slot)
13587 {
13588 unsigned long npages = slot->npages;
13589 int i, r;
13590
13591 /*
13592 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
13593 * old arrays will be freed by kvm_set_memory_region() if installing
13594 * the new memslot is successful.
13595 */
13596 memset(&slot->arch, 0, sizeof(slot->arch));
13597
13598 if (kvm_memslots_have_rmaps(kvm)) {
13599 r = memslot_rmap_alloc(slot, npages);
13600 if (r)
13601 return r;
13602 }
13603
13604 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13605 struct kvm_lpage_info *linfo;
13606 unsigned long ugfn;
13607 int lpages;
13608 int level = i + 1;
13609
13610 lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13611
13612 linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
13613 if (!linfo)
13614 goto out_free;
13615
13616 slot->arch.lpage_info[i - 1] = linfo;
13617
13618 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
13619 linfo[0].disallow_lpage = 1;
13620 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
13621 linfo[lpages - 1].disallow_lpage = 1;
13622 ugfn = slot->userspace_addr >> PAGE_SHIFT;
13623 /*
13624 * If the gfn and userspace address are not aligned wrt each
13625 * other, disable large page support for this slot.
13626 */
13627 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
13628 unsigned long j;
13629
13630 for (j = 0; j < lpages; ++j)
13631 linfo[j].disallow_lpage = 1;
13632 }
13633 }
13634
13635 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
13636 kvm_mmu_init_memslot_memory_attributes(kvm, slot);
13637 #endif
13638
13639 if (kvm_page_track_create_memslot(kvm, slot, npages))
13640 goto out_free;
13641
13642 return 0;
13643
13644 out_free:
13645 memslot_rmap_free(slot);
13646
13647 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13648 vfree(slot->arch.lpage_info[i - 1]);
13649 slot->arch.lpage_info[i - 1] = NULL;
13650 }
13651 return -ENOMEM;
13652 }
13653
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)13654 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
13655 {
13656 struct kvm_vcpu *vcpu;
13657 unsigned long i;
13658
13659 /*
13660 * memslots->generation has been incremented.
13661 * mmio generation may have reached its maximum value.
13662 */
13663 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
13664
13665 /* Force re-initialization of steal_time cache */
13666 kvm_for_each_vcpu(i, vcpu, kvm)
13667 kvm_vcpu_kick(vcpu);
13668 }
13669
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)13670 int kvm_arch_prepare_memory_region(struct kvm *kvm,
13671 const struct kvm_memory_slot *old,
13672 struct kvm_memory_slot *new,
13673 enum kvm_mr_change change)
13674 {
13675 /*
13676 * KVM doesn't support moving memslots when there are external page
13677 * trackers attached to the VM, i.e. if KVMGT is in use.
13678 */
13679 if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
13680 return -EINVAL;
13681
13682 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
13683 if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
13684 return -EINVAL;
13685
13686 if (kvm_is_gfn_alias(kvm, new->base_gfn + new->npages - 1))
13687 return -EINVAL;
13688
13689 return kvm_alloc_memslot_metadata(kvm, new);
13690 }
13691
13692 if (change == KVM_MR_FLAGS_ONLY)
13693 memcpy(&new->arch, &old->arch, sizeof(old->arch));
13694 else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
13695 return -EIO;
13696
13697 return 0;
13698 }
13699
13700
kvm_mmu_update_cpu_dirty_logging(struct kvm * kvm,bool enable)13701 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
13702 {
13703 int nr_slots;
13704
13705 if (!kvm->arch.cpu_dirty_log_size)
13706 return;
13707
13708 nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
13709 if ((enable && nr_slots == 1) || !nr_slots)
13710 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
13711 }
13712
kvm_mmu_slot_apply_flags(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13713 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
13714 struct kvm_memory_slot *old,
13715 const struct kvm_memory_slot *new,
13716 enum kvm_mr_change change)
13717 {
13718 u32 old_flags = old ? old->flags : 0;
13719 u32 new_flags = new ? new->flags : 0;
13720 bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
13721
13722 /*
13723 * Update CPU dirty logging if dirty logging is being toggled. This
13724 * applies to all operations.
13725 */
13726 if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
13727 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
13728
13729 /*
13730 * Nothing more to do for RO slots (which can't be dirtied and can't be
13731 * made writable) or CREATE/MOVE/DELETE of a slot.
13732 *
13733 * For a memslot with dirty logging disabled:
13734 * CREATE: No dirty mappings will already exist.
13735 * MOVE/DELETE: The old mappings will already have been cleaned up by
13736 * kvm_arch_flush_shadow_memslot()
13737 *
13738 * For a memslot with dirty logging enabled:
13739 * CREATE: No shadow pages exist, thus nothing to write-protect
13740 * and no dirty bits to clear.
13741 * MOVE/DELETE: The old mappings will already have been cleaned up by
13742 * kvm_arch_flush_shadow_memslot().
13743 */
13744 if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
13745 return;
13746
13747 /*
13748 * READONLY and non-flags changes were filtered out above, and the only
13749 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13750 * logging isn't being toggled on or off.
13751 */
13752 if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
13753 return;
13754
13755 if (!log_dirty_pages) {
13756 /*
13757 * Recover huge page mappings in the slot now that dirty logging
13758 * is disabled, i.e. now that KVM does not have to track guest
13759 * writes at 4KiB granularity.
13760 *
13761 * Dirty logging might be disabled by userspace if an ongoing VM
13762 * live migration is cancelled and the VM must continue running
13763 * on the source.
13764 */
13765 kvm_mmu_recover_huge_pages(kvm, new);
13766 } else {
13767 /*
13768 * Initially-all-set does not require write protecting any page,
13769 * because they're all assumed to be dirty.
13770 */
13771 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13772 return;
13773
13774 if (READ_ONCE(eager_page_split))
13775 kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13776
13777 if (kvm->arch.cpu_dirty_log_size) {
13778 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13779 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13780 } else {
13781 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
13782 }
13783
13784 /*
13785 * Unconditionally flush the TLBs after enabling dirty logging.
13786 * A flush is almost always going to be necessary (see below),
13787 * and unconditionally flushing allows the helpers to omit
13788 * the subtly complex checks when removing write access.
13789 *
13790 * Do the flush outside of mmu_lock to reduce the amount of
13791 * time mmu_lock is held. Flushing after dropping mmu_lock is
13792 * safe as KVM only needs to guarantee the slot is fully
13793 * write-protected before returning to userspace, i.e. before
13794 * userspace can consume the dirty status.
13795 *
13796 * Flushing outside of mmu_lock requires KVM to be careful when
13797 * making decisions based on writable status of an SPTE, e.g. a
13798 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13799 *
13800 * Specifically, KVM also write-protects guest page tables to
13801 * monitor changes when using shadow paging, and must guarantee
13802 * no CPUs can write to those page before mmu_lock is dropped.
13803 * Because CPUs may have stale TLB entries at this point, a
13804 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13805 *
13806 * KVM also allows making SPTES writable outside of mmu_lock,
13807 * e.g. to allow dirty logging without taking mmu_lock.
13808 *
13809 * To handle these scenarios, KVM uses a separate software-only
13810 * bit (MMU-writable) to track if a SPTE is !writable due to
13811 * a guest page table being write-protected (KVM clears the
13812 * MMU-writable flag when write-protecting for shadow paging).
13813 *
13814 * The use of MMU-writable is also the primary motivation for
13815 * the unconditional flush. Because KVM must guarantee that a
13816 * CPU doesn't contain stale, writable TLB entries for a
13817 * !MMU-writable SPTE, KVM must flush if it encounters any
13818 * MMU-writable SPTE regardless of whether the actual hardware
13819 * writable bit was set. I.e. KVM is almost guaranteed to need
13820 * to flush, while unconditionally flushing allows the "remove
13821 * write access" helpers to ignore MMU-writable entirely.
13822 *
13823 * See is_writable_pte() for more details (the case involving
13824 * access-tracked SPTEs is particularly relevant).
13825 */
13826 kvm_flush_remote_tlbs_memslot(kvm, new);
13827 }
13828 }
13829
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13830 void kvm_arch_commit_memory_region(struct kvm *kvm,
13831 struct kvm_memory_slot *old,
13832 const struct kvm_memory_slot *new,
13833 enum kvm_mr_change change)
13834 {
13835 if (change == KVM_MR_DELETE)
13836 kvm_page_track_delete_slot(kvm, old);
13837
13838 if (!kvm->arch.n_requested_mmu_pages &&
13839 (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13840 unsigned long nr_mmu_pages;
13841
13842 nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13843 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13844 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13845 }
13846
13847 kvm_mmu_slot_apply_flags(kvm, old, new, change);
13848
13849 /* Free the arrays associated with the old memslot. */
13850 if (change == KVM_MR_MOVE)
13851 kvm_arch_free_memslot(kvm, old);
13852 }
13853
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)13854 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13855 {
13856 WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13857
13858 if (vcpu->arch.guest_state_protected)
13859 return true;
13860
13861 return kvm_x86_call(get_cpl)(vcpu) == 0;
13862 }
13863
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)13864 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13865 {
13866 WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13867
13868 if (vcpu->arch.guest_state_protected)
13869 return 0;
13870
13871 return kvm_rip_read(vcpu);
13872 }
13873
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)13874 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13875 {
13876 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13877 }
13878
kvm_arch_interrupt_allowed(struct kvm_vcpu * vcpu)13879 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13880 {
13881 return kvm_x86_call(interrupt_allowed)(vcpu, false);
13882 }
13883
kvm_get_linear_rip(struct kvm_vcpu * vcpu)13884 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13885 {
13886 /* Can't read the RIP when guest state is protected, just return 0 */
13887 if (vcpu->arch.guest_state_protected)
13888 return 0;
13889
13890 if (is_64_bit_mode(vcpu))
13891 return kvm_rip_read(vcpu);
13892 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13893 kvm_rip_read(vcpu));
13894 }
13895 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_linear_rip);
13896
kvm_is_linear_rip(struct kvm_vcpu * vcpu,unsigned long linear_rip)13897 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13898 {
13899 return kvm_get_linear_rip(vcpu) == linear_rip;
13900 }
13901 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_is_linear_rip);
13902
kvm_get_rflags(struct kvm_vcpu * vcpu)13903 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13904 {
13905 unsigned long rflags;
13906
13907 rflags = kvm_x86_call(get_rflags)(vcpu);
13908 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13909 rflags &= ~X86_EFLAGS_TF;
13910 return rflags;
13911 }
13912 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_rflags);
13913
__kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13914 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13915 {
13916 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13917 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13918 rflags |= X86_EFLAGS_TF;
13919 kvm_x86_call(set_rflags)(vcpu, rflags);
13920 }
13921
kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13922 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13923 {
13924 __kvm_set_rflags(vcpu, rflags);
13925 kvm_make_request(KVM_REQ_EVENT, vcpu);
13926 }
13927 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_rflags);
13928
kvm_async_pf_hash_fn(gfn_t gfn)13929 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13930 {
13931 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13932
13933 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13934 }
13935
kvm_async_pf_next_probe(u32 key)13936 static inline u32 kvm_async_pf_next_probe(u32 key)
13937 {
13938 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13939 }
13940
kvm_add_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13941 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13942 {
13943 u32 key = kvm_async_pf_hash_fn(gfn);
13944
13945 while (vcpu->arch.apf.gfns[key] != ~0)
13946 key = kvm_async_pf_next_probe(key);
13947
13948 vcpu->arch.apf.gfns[key] = gfn;
13949 }
13950
kvm_async_pf_gfn_slot(struct kvm_vcpu * vcpu,gfn_t gfn)13951 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13952 {
13953 int i;
13954 u32 key = kvm_async_pf_hash_fn(gfn);
13955
13956 for (i = 0; i < ASYNC_PF_PER_VCPU &&
13957 (vcpu->arch.apf.gfns[key] != gfn &&
13958 vcpu->arch.apf.gfns[key] != ~0); i++)
13959 key = kvm_async_pf_next_probe(key);
13960
13961 return key;
13962 }
13963
kvm_find_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13964 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13965 {
13966 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13967 }
13968
kvm_del_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13969 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13970 {
13971 u32 i, j, k;
13972
13973 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13974
13975 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13976 return;
13977
13978 while (true) {
13979 vcpu->arch.apf.gfns[i] = ~0;
13980 do {
13981 j = kvm_async_pf_next_probe(j);
13982 if (vcpu->arch.apf.gfns[j] == ~0)
13983 return;
13984 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13985 /*
13986 * k lies cyclically in ]i,j]
13987 * | i.k.j |
13988 * |....j i.k.| or |.k..j i...|
13989 */
13990 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13991 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13992 i = j;
13993 }
13994 }
13995
apf_put_user_notpresent(struct kvm_vcpu * vcpu)13996 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13997 {
13998 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13999
14000 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
14001 sizeof(reason));
14002 }
14003
apf_put_user_ready(struct kvm_vcpu * vcpu,u32 token)14004 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
14005 {
14006 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
14007
14008 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
14009 &token, offset, sizeof(token));
14010 }
14011
apf_pageready_slot_free(struct kvm_vcpu * vcpu)14012 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
14013 {
14014 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
14015 u32 val;
14016
14017 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
14018 &val, offset, sizeof(val)))
14019 return false;
14020
14021 return !val;
14022 }
14023
kvm_can_deliver_async_pf(struct kvm_vcpu * vcpu)14024 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
14025 {
14026
14027 if (!kvm_pv_async_pf_enabled(vcpu))
14028 return false;
14029
14030 if (!vcpu->arch.apf.send_always &&
14031 (vcpu->arch.guest_state_protected || !kvm_x86_call(get_cpl)(vcpu)))
14032 return false;
14033
14034 if (is_guest_mode(vcpu)) {
14035 /*
14036 * L1 needs to opt into the special #PF vmexits that are
14037 * used to deliver async page faults.
14038 */
14039 return vcpu->arch.apf.delivery_as_pf_vmexit;
14040 } else {
14041 /*
14042 * Play it safe in case the guest temporarily disables paging.
14043 * The real mode IDT in particular is unlikely to have a #PF
14044 * exception setup.
14045 */
14046 return is_paging(vcpu);
14047 }
14048 }
14049
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)14050 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
14051 {
14052 if (unlikely(!lapic_in_kernel(vcpu) ||
14053 kvm_event_needs_reinjection(vcpu) ||
14054 kvm_is_exception_pending(vcpu)))
14055 return false;
14056
14057 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
14058 return false;
14059
14060 /*
14061 * If interrupts are off we cannot even use an artificial
14062 * halt state.
14063 */
14064 return kvm_arch_interrupt_allowed(vcpu);
14065 }
14066
kvm_arch_async_page_not_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)14067 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
14068 struct kvm_async_pf *work)
14069 {
14070 struct x86_exception fault;
14071
14072 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
14073 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
14074
14075 if (kvm_can_deliver_async_pf(vcpu) &&
14076 !apf_put_user_notpresent(vcpu)) {
14077 fault.vector = PF_VECTOR;
14078 fault.error_code_valid = true;
14079 fault.error_code = 0;
14080 fault.nested_page_fault = false;
14081 fault.address = work->arch.token;
14082 fault.async_page_fault = true;
14083 kvm_inject_page_fault(vcpu, &fault);
14084 return true;
14085 } else {
14086 /*
14087 * It is not possible to deliver a paravirtualized asynchronous
14088 * page fault, but putting the guest in an artificial halt state
14089 * can be beneficial nevertheless: if an interrupt arrives, we
14090 * can deliver it timely and perhaps the guest will schedule
14091 * another process. When the instruction that triggered a page
14092 * fault is retried, hopefully the page will be ready in the host.
14093 */
14094 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
14095 return false;
14096 }
14097 }
14098
kvm_arch_async_page_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)14099 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
14100 struct kvm_async_pf *work)
14101 {
14102 struct kvm_lapic_irq irq = {
14103 .delivery_mode = APIC_DM_FIXED,
14104 .vector = vcpu->arch.apf.vec
14105 };
14106
14107 if (work->wakeup_all)
14108 work->arch.token = ~0; /* broadcast wakeup */
14109 else
14110 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
14111 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
14112
14113 if ((work->wakeup_all || work->notpresent_injected) &&
14114 kvm_pv_async_pf_enabled(vcpu) &&
14115 !apf_put_user_ready(vcpu, work->arch.token)) {
14116 WRITE_ONCE(vcpu->arch.apf.pageready_pending, true);
14117 kvm_apic_set_irq(vcpu, &irq, NULL);
14118 }
14119
14120 vcpu->arch.apf.halted = false;
14121 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
14122 }
14123
kvm_arch_async_page_present_queued(struct kvm_vcpu * vcpu)14124 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
14125 {
14126 kvm_make_request(KVM_REQ_APF_READY, vcpu);
14127
14128 /* Pairs with smp_store_mb() in kvm_set_msr_common(). */
14129 smp_mb__after_atomic();
14130
14131 if (!READ_ONCE(vcpu->arch.apf.pageready_pending))
14132 kvm_vcpu_kick(vcpu);
14133 }
14134
kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu * vcpu)14135 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
14136 {
14137 if (!kvm_pv_async_pf_enabled(vcpu))
14138 return true;
14139 else
14140 return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
14141 }
14142
kvm_noncoherent_dma_assignment_start_or_stop(struct kvm * kvm)14143 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
14144 {
14145 /*
14146 * Non-coherent DMA assignment and de-assignment may affect whether or
14147 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
14148 * due to toggling the "ignore PAT" bit. Zap all SPTEs when the first
14149 * (or last) non-coherent device is (un)registered to so that new SPTEs
14150 * with the correct "ignore guest PAT" setting are created.
14151 *
14152 * If KVM always honors guest PAT, however, there is nothing to do.
14153 */
14154 if (kvm_check_has_quirk(kvm, KVM_X86_QUIRK_IGNORE_GUEST_PAT))
14155 kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
14156 }
14157
kvm_arch_register_noncoherent_dma(struct kvm * kvm)14158 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
14159 {
14160 if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
14161 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
14162 }
14163
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)14164 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
14165 {
14166 if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
14167 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
14168 }
14169
kvm_arch_has_noncoherent_dma(struct kvm * kvm)14170 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
14171 {
14172 return atomic_read(&kvm->arch.noncoherent_dma_count);
14173 }
14174 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_arch_has_noncoherent_dma);
14175
kvm_arch_no_poll(struct kvm_vcpu * vcpu)14176 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
14177 {
14178 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
14179 }
14180
14181 #ifdef CONFIG_KVM_GUEST_MEMFD
14182 /*
14183 * KVM doesn't yet support initializing guest_memfd memory as shared for VMs
14184 * with private memory (the private vs. shared tracking needs to be moved into
14185 * guest_memfd).
14186 */
kvm_arch_supports_gmem_init_shared(struct kvm * kvm)14187 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm)
14188 {
14189 return !kvm_arch_has_private_mem(kvm);
14190 }
14191
14192 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
kvm_arch_gmem_prepare(struct kvm * kvm,gfn_t gfn,kvm_pfn_t pfn,int max_order)14193 int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
14194 {
14195 return kvm_x86_call(gmem_prepare)(kvm, pfn, gfn, max_order);
14196 }
14197 #endif
14198
14199 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
kvm_arch_gmem_invalidate(kvm_pfn_t start,kvm_pfn_t end)14200 void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
14201 {
14202 kvm_x86_call(gmem_invalidate)(start, end);
14203 }
14204 #endif
14205 #endif
14206
kvm_spec_ctrl_test_value(u64 value)14207 int kvm_spec_ctrl_test_value(u64 value)
14208 {
14209 /*
14210 * test that setting IA32_SPEC_CTRL to given value
14211 * is allowed by the host processor
14212 */
14213
14214 u64 saved_value;
14215 unsigned long flags;
14216 int ret = 0;
14217
14218 local_irq_save(flags);
14219
14220 if (rdmsrq_safe(MSR_IA32_SPEC_CTRL, &saved_value))
14221 ret = 1;
14222 else if (wrmsrq_safe(MSR_IA32_SPEC_CTRL, value))
14223 ret = 1;
14224 else
14225 wrmsrq(MSR_IA32_SPEC_CTRL, saved_value);
14226
14227 local_irq_restore(flags);
14228
14229 return ret;
14230 }
14231 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_spec_ctrl_test_value);
14232
kvm_fixup_and_inject_pf_error(struct kvm_vcpu * vcpu,gva_t gva,u16 error_code)14233 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
14234 {
14235 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
14236 struct x86_exception fault;
14237 u64 access = error_code &
14238 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
14239
14240 if (!(error_code & PFERR_PRESENT_MASK) ||
14241 mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
14242 /*
14243 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
14244 * tables probably do not match the TLB. Just proceed
14245 * with the error code that the processor gave.
14246 */
14247 fault.vector = PF_VECTOR;
14248 fault.error_code_valid = true;
14249 fault.error_code = error_code;
14250 fault.nested_page_fault = false;
14251 fault.address = gva;
14252 fault.async_page_fault = false;
14253 }
14254 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
14255 }
14256 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fixup_and_inject_pf_error);
14257
14258 /*
14259 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
14260 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
14261 * indicates whether exit to userspace is needed.
14262 */
kvm_handle_memory_failure(struct kvm_vcpu * vcpu,int r,struct x86_exception * e)14263 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
14264 struct x86_exception *e)
14265 {
14266 if (r == X86EMUL_PROPAGATE_FAULT) {
14267 if (KVM_BUG_ON(!e, vcpu->kvm))
14268 return -EIO;
14269
14270 kvm_inject_emulated_page_fault(vcpu, e);
14271 return 1;
14272 }
14273
14274 /*
14275 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
14276 * while handling a VMX instruction KVM could've handled the request
14277 * correctly by exiting to userspace and performing I/O but there
14278 * doesn't seem to be a real use-case behind such requests, just return
14279 * KVM_EXIT_INTERNAL_ERROR for now.
14280 */
14281 kvm_prepare_emulation_failure_exit(vcpu);
14282
14283 return 0;
14284 }
14285 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_memory_failure);
14286
kvm_handle_invpcid(struct kvm_vcpu * vcpu,unsigned long type,gva_t gva)14287 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
14288 {
14289 bool pcid_enabled;
14290 struct x86_exception e;
14291 struct {
14292 u64 pcid;
14293 u64 gla;
14294 } operand;
14295 int r;
14296
14297 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
14298 if (r != X86EMUL_CONTINUE)
14299 return kvm_handle_memory_failure(vcpu, r, &e);
14300
14301 if (operand.pcid >> 12 != 0) {
14302 kvm_inject_gp(vcpu, 0);
14303 return 1;
14304 }
14305
14306 pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
14307
14308 switch (type) {
14309 case INVPCID_TYPE_INDIV_ADDR:
14310 /*
14311 * LAM doesn't apply to addresses that are inputs to TLB
14312 * invalidation.
14313 */
14314 if ((!pcid_enabled && (operand.pcid != 0)) ||
14315 is_noncanonical_invlpg_address(operand.gla, vcpu)) {
14316 kvm_inject_gp(vcpu, 0);
14317 return 1;
14318 }
14319 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
14320 return kvm_skip_emulated_instruction(vcpu);
14321
14322 case INVPCID_TYPE_SINGLE_CTXT:
14323 if (!pcid_enabled && (operand.pcid != 0)) {
14324 kvm_inject_gp(vcpu, 0);
14325 return 1;
14326 }
14327
14328 /*
14329 * When ERAPS is supported, invalidating a specific PCID clears
14330 * the RAP (Return Address Predicator).
14331 */
14332 if (guest_cpu_cap_has(vcpu, X86_FEATURE_ERAPS))
14333 kvm_register_mark_dirty(vcpu, VCPU_EXREG_ERAPS);
14334
14335 kvm_invalidate_pcid(vcpu, operand.pcid);
14336 return kvm_skip_emulated_instruction(vcpu);
14337
14338 case INVPCID_TYPE_ALL_NON_GLOBAL:
14339 /*
14340 * Currently, KVM doesn't mark global entries in the shadow
14341 * page tables, so a non-global flush just degenerates to a
14342 * global flush. If needed, we could optimize this later by
14343 * keeping track of global entries in shadow page tables.
14344 */
14345
14346 fallthrough;
14347 case INVPCID_TYPE_ALL_INCL_GLOBAL:
14348 /*
14349 * Don't bother marking VCPU_EXREG_ERAPS dirty, SVM will take
14350 * care of doing so when emulating the full guest TLB flush
14351 * (the RAP is cleared on all implicit TLB flushes).
14352 */
14353 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
14354 return kvm_skip_emulated_instruction(vcpu);
14355
14356 default:
14357 kvm_inject_gp(vcpu, 0);
14358 return 1;
14359 }
14360 }
14361 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invpcid);
14362
complete_sev_es_emulated_mmio(struct kvm_vcpu * vcpu)14363 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
14364 {
14365 struct kvm_run *run = vcpu->run;
14366 struct kvm_mmio_fragment *frag;
14367 unsigned int len;
14368
14369 if (KVM_BUG_ON(!vcpu->mmio_needed, vcpu->kvm))
14370 return -EIO;
14371
14372 /* Complete previous fragment */
14373 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
14374 len = min(8u, frag->len);
14375 if (!vcpu->mmio_is_write)
14376 memcpy(frag->data, run->mmio.data, len);
14377
14378 if (frag->len <= 8) {
14379 /* Switch to the next fragment. */
14380 frag++;
14381 vcpu->mmio_cur_fragment++;
14382 } else {
14383 /* Go forward to the next mmio piece. */
14384 frag->data += len;
14385 frag->gpa += len;
14386 frag->len -= len;
14387 }
14388
14389 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
14390 vcpu->mmio_needed = 0;
14391
14392 /*
14393 * All done, as frag->data always points at the GHCB scratch
14394 * area and VMGEXIT is trap-like (RIP is advanced by hardware).
14395 */
14396 return 1;
14397 }
14398
14399 // More MMIO is needed
14400 kvm_prepare_emulated_mmio_exit(vcpu, frag);
14401 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14402 return 0;
14403 }
14404
kvm_sev_es_mmio(struct kvm_vcpu * vcpu,bool is_write,gpa_t gpa,unsigned int bytes,void * data)14405 int kvm_sev_es_mmio(struct kvm_vcpu *vcpu, bool is_write, gpa_t gpa,
14406 unsigned int bytes, void *data)
14407 {
14408 struct kvm_mmio_fragment *frag;
14409 int handled;
14410
14411 if (!data || WARN_ON_ONCE(object_is_on_stack(data)))
14412 return -EINVAL;
14413
14414 if (is_write)
14415 handled = vcpu_mmio_write(vcpu, gpa, bytes, data);
14416 else
14417 handled = vcpu_mmio_read(vcpu, gpa, bytes, data);
14418 if (handled == bytes)
14419 return 1;
14420
14421 bytes -= handled;
14422 gpa += handled;
14423 data += handled;
14424
14425 /*
14426 * TODO: Determine whether or not userspace plays nice with MMIO
14427 * requests that split a page boundary.
14428 */
14429 frag = vcpu->mmio_fragments;
14430 frag->len = bytes;
14431 frag->gpa = gpa;
14432 frag->data = data;
14433
14434 vcpu->mmio_needed = 1;
14435 vcpu->mmio_cur_fragment = 0;
14436 vcpu->mmio_nr_fragments = 1;
14437 vcpu->mmio_is_write = is_write;
14438
14439 kvm_prepare_emulated_mmio_exit(vcpu, frag);
14440 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14441 return 0;
14442 }
14443 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_mmio);
14444
advance_sev_es_emulated_pio(struct kvm_vcpu * vcpu,unsigned count,int size)14445 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
14446 {
14447 vcpu->arch.sev_pio_count -= count;
14448 vcpu->arch.sev_pio_data += count * size;
14449 }
14450
14451 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14452 unsigned int port);
14453
complete_sev_es_emulated_outs(struct kvm_vcpu * vcpu)14454 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
14455 {
14456 int size = vcpu->arch.pio.size;
14457 int port = vcpu->arch.pio.port;
14458
14459 vcpu->arch.pio.count = 0;
14460 if (vcpu->arch.sev_pio_count)
14461 return kvm_sev_es_outs(vcpu, size, port);
14462 return 1;
14463 }
14464
kvm_sev_es_outs(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14465 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14466 unsigned int port)
14467 {
14468 for (;;) {
14469 unsigned int count =
14470 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14471 int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
14472
14473 /* memcpy done already by emulator_pio_out. */
14474 advance_sev_es_emulated_pio(vcpu, count, size);
14475 if (!ret)
14476 break;
14477
14478 /* Emulation done by the kernel. */
14479 if (!vcpu->arch.sev_pio_count)
14480 return 1;
14481 }
14482
14483 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
14484 return 0;
14485 }
14486
14487 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14488 unsigned int port);
14489
complete_sev_es_emulated_ins(struct kvm_vcpu * vcpu)14490 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
14491 {
14492 unsigned count = vcpu->arch.pio.count;
14493 int size = vcpu->arch.pio.size;
14494 int port = vcpu->arch.pio.port;
14495
14496 complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
14497 advance_sev_es_emulated_pio(vcpu, count, size);
14498 if (vcpu->arch.sev_pio_count)
14499 return kvm_sev_es_ins(vcpu, size, port);
14500 return 1;
14501 }
14502
kvm_sev_es_ins(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14503 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14504 unsigned int port)
14505 {
14506 for (;;) {
14507 unsigned int count =
14508 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14509 if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
14510 break;
14511
14512 /* Emulation done by the kernel. */
14513 advance_sev_es_emulated_pio(vcpu, count, size);
14514 if (!vcpu->arch.sev_pio_count)
14515 return 1;
14516 }
14517
14518 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
14519 return 0;
14520 }
14521
kvm_sev_es_string_io(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port,void * data,unsigned int count,int in)14522 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
14523 unsigned int port, void *data, unsigned int count,
14524 int in)
14525 {
14526 vcpu->arch.sev_pio_data = data;
14527 vcpu->arch.sev_pio_count = count;
14528 return in ? kvm_sev_es_ins(vcpu, size, port)
14529 : kvm_sev_es_outs(vcpu, size, port);
14530 }
14531 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_string_io);
14532
14533 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
14534 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
14535 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_mmio);
14536 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
14537 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
14538 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
14539 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
14540 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
14541 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
14542 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
14543 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
14544 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
14545 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
14546 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
14547 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
14548 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
14549 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
14550 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
14551 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
14552 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
14553 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
14554 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
14555 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
14556 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
14557 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
14558 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
14559 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
14560 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
14561 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
14562 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
14563
kvm_x86_init(void)14564 static int __init kvm_x86_init(void)
14565 {
14566 kvm_init_xstate_sizes();
14567
14568 kvm_mmu_x86_module_init();
14569 mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
14570 return 0;
14571 }
14572 module_init(kvm_x86_init);
14573
kvm_x86_exit(void)14574 static void __exit kvm_x86_exit(void)
14575 {
14576 WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
14577 }
14578 module_exit(kvm_x86_exit);
14579