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/entry-kvm.h>
63 #include <linux/suspend.h>
64 #include <linux/smp.h>
65
66 #include <trace/events/ipi.h>
67 #include <trace/events/kvm.h>
68
69 #include <asm/debugreg.h>
70 #include <asm/msr.h>
71 #include <asm/desc.h>
72 #include <asm/mce.h>
73 #include <asm/pkru.h>
74 #include <linux/kernel_stat.h>
75 #include <asm/fpu/api.h>
76 #include <asm/fpu/xcr.h>
77 #include <asm/fpu/xstate.h>
78 #include <asm/pvclock.h>
79 #include <asm/div64.h>
80 #include <asm/irq_remapping.h>
81 #include <asm/mshyperv.h>
82 #include <asm/hypervisor.h>
83 #include <asm/tlbflush.h>
84 #include <asm/intel_pt.h>
85 #include <asm/emulate_prefix.h>
86 #include <asm/sgx.h>
87 #include <clocksource/hyperv_timer.h>
88
89 #define CREATE_TRACE_POINTS
90 #include "trace.h"
91
92 #define MAX_IO_MSRS 256
93
94 /*
95 * Note, kvm_caps fields should *never* have default values, all fields must be
96 * recomputed from scratch during vendor module load, e.g. to account for a
97 * vendor module being reloaded with different module parameters.
98 */
99 struct kvm_caps kvm_caps __read_mostly;
100 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_caps);
101
102 struct kvm_host_values kvm_host __read_mostly;
103 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_host);
104
105 #define ERR_PTR_USR(e) ((void __user *)ERR_PTR(e))
106
107 #define emul_to_vcpu(ctxt) \
108 ((struct kvm_vcpu *)(ctxt)->vcpu)
109
110 /* EFER defaults:
111 * - enable syscall per default because its emulated by KVM
112 * - enable LME and LMA per default on 64 bit KVM
113 */
114 #ifdef CONFIG_X86_64
115 static
116 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
117 #else
118 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
119 #endif
120
121 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
122
123 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
124
125 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
126 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
127
128 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
129 static void process_nmi(struct kvm_vcpu *vcpu);
130 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
131 static void store_regs(struct kvm_vcpu *vcpu);
132 static int sync_regs(struct kvm_vcpu *vcpu);
133 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
134
135 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
136 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
137
138 static DEFINE_MUTEX(vendor_module_lock);
139 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu);
140 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu);
141
142 struct kvm_x86_ops kvm_x86_ops __read_mostly;
143
144 #define KVM_X86_OP(func) \
145 DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
146 *(((struct kvm_x86_ops *)0)->func));
147 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
148 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
149 #include <asm/kvm-x86-ops.h>
150 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
151 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
152
153 static bool __read_mostly ignore_msrs = 0;
154 module_param(ignore_msrs, bool, 0644);
155
156 bool __read_mostly report_ignored_msrs = true;
157 module_param(report_ignored_msrs, bool, 0644);
158 EXPORT_SYMBOL_FOR_KVM_INTERNAL(report_ignored_msrs);
159
160 unsigned int min_timer_period_us = 200;
161 module_param(min_timer_period_us, uint, 0644);
162
163 static bool __read_mostly kvmclock_periodic_sync = true;
164 module_param(kvmclock_periodic_sync, bool, 0444);
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 bool __read_mostly eager_page_split = true;
191 module_param(eager_page_split, bool, 0644);
192
193 /* Enable/disable SMT_RSB bug mitigation */
194 static bool __read_mostly mitigate_smt_rsb;
195 module_param(mitigate_smt_rsb, bool, 0444);
196
197 /*
198 * Restoring the host value for MSRs that are only consumed when running in
199 * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
200 * returns to userspace, i.e. the kernel can run with the guest's value.
201 */
202 #define KVM_MAX_NR_USER_RETURN_MSRS 16
203
204 struct kvm_user_return_msrs {
205 struct user_return_notifier urn;
206 bool registered;
207 struct kvm_user_return_msr_values {
208 u64 host;
209 u64 curr;
210 } values[KVM_MAX_NR_USER_RETURN_MSRS];
211 };
212
213 u32 __read_mostly kvm_nr_uret_msrs;
214 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_nr_uret_msrs);
215 static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
216 static struct kvm_user_return_msrs __percpu *user_return_msrs;
217
218 #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
219 | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
220 | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
221 | XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
222
223 #define XFEATURE_MASK_CET_ALL (XFEATURE_MASK_CET_USER | XFEATURE_MASK_CET_KERNEL)
224 /*
225 * Note, KVM supports exposing PT to the guest, but does not support context
226 * switching PT via XSTATE (KVM's PT virtualization relies on perf; swapping
227 * PT via guest XSTATE would clobber perf state), i.e. KVM doesn't support
228 * IA32_XSS[bit 8] (guests can/must use RDMSR/WRMSR to save/restore PT MSRs).
229 */
230 #define KVM_SUPPORTED_XSS (XFEATURE_MASK_CET_ALL)
231
232 bool __read_mostly allow_smaller_maxphyaddr = 0;
233 EXPORT_SYMBOL_FOR_KVM_INTERNAL(allow_smaller_maxphyaddr);
234
235 bool __read_mostly enable_apicv = true;
236 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_apicv);
237
238 bool __read_mostly enable_ipiv = true;
239 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_ipiv);
240
241 bool __read_mostly enable_device_posted_irqs = true;
242 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_device_posted_irqs);
243
244 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
245 KVM_GENERIC_VM_STATS(),
246 STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
247 STATS_DESC_COUNTER(VM, mmu_pte_write),
248 STATS_DESC_COUNTER(VM, mmu_pde_zapped),
249 STATS_DESC_COUNTER(VM, mmu_flooded),
250 STATS_DESC_COUNTER(VM, mmu_recycled),
251 STATS_DESC_COUNTER(VM, mmu_cache_miss),
252 STATS_DESC_ICOUNTER(VM, mmu_unsync),
253 STATS_DESC_ICOUNTER(VM, pages_4k),
254 STATS_DESC_ICOUNTER(VM, pages_2m),
255 STATS_DESC_ICOUNTER(VM, pages_1g),
256 STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
257 STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
258 STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
259 };
260
261 const struct kvm_stats_header kvm_vm_stats_header = {
262 .name_size = KVM_STATS_NAME_SIZE,
263 .num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
264 .id_offset = sizeof(struct kvm_stats_header),
265 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
266 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
267 sizeof(kvm_vm_stats_desc),
268 };
269
270 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
271 KVM_GENERIC_VCPU_STATS(),
272 STATS_DESC_COUNTER(VCPU, pf_taken),
273 STATS_DESC_COUNTER(VCPU, pf_fixed),
274 STATS_DESC_COUNTER(VCPU, pf_emulate),
275 STATS_DESC_COUNTER(VCPU, pf_spurious),
276 STATS_DESC_COUNTER(VCPU, pf_fast),
277 STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
278 STATS_DESC_COUNTER(VCPU, pf_guest),
279 STATS_DESC_COUNTER(VCPU, tlb_flush),
280 STATS_DESC_COUNTER(VCPU, invlpg),
281 STATS_DESC_COUNTER(VCPU, exits),
282 STATS_DESC_COUNTER(VCPU, io_exits),
283 STATS_DESC_COUNTER(VCPU, mmio_exits),
284 STATS_DESC_COUNTER(VCPU, signal_exits),
285 STATS_DESC_COUNTER(VCPU, irq_window_exits),
286 STATS_DESC_COUNTER(VCPU, nmi_window_exits),
287 STATS_DESC_COUNTER(VCPU, l1d_flush),
288 STATS_DESC_COUNTER(VCPU, halt_exits),
289 STATS_DESC_COUNTER(VCPU, request_irq_exits),
290 STATS_DESC_COUNTER(VCPU, irq_exits),
291 STATS_DESC_COUNTER(VCPU, host_state_reload),
292 STATS_DESC_COUNTER(VCPU, fpu_reload),
293 STATS_DESC_COUNTER(VCPU, insn_emulation),
294 STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
295 STATS_DESC_COUNTER(VCPU, hypercalls),
296 STATS_DESC_COUNTER(VCPU, irq_injections),
297 STATS_DESC_COUNTER(VCPU, nmi_injections),
298 STATS_DESC_COUNTER(VCPU, req_event),
299 STATS_DESC_COUNTER(VCPU, nested_run),
300 STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
301 STATS_DESC_COUNTER(VCPU, directed_yield_successful),
302 STATS_DESC_COUNTER(VCPU, preemption_reported),
303 STATS_DESC_COUNTER(VCPU, preemption_other),
304 STATS_DESC_IBOOLEAN(VCPU, guest_mode),
305 STATS_DESC_COUNTER(VCPU, notify_window_exits),
306 };
307
308 const struct kvm_stats_header kvm_vcpu_stats_header = {
309 .name_size = KVM_STATS_NAME_SIZE,
310 .num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
311 .id_offset = sizeof(struct kvm_stats_header),
312 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
313 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
314 sizeof(kvm_vcpu_stats_desc),
315 };
316
317 static struct kmem_cache *x86_emulator_cache;
318
319 /*
320 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features) track
321 * the set of MSRs that KVM exposes to userspace through KVM_GET_MSRS,
322 * KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST. msrs_to_save holds MSRs that
323 * require host support, i.e. should be probed via RDMSR. emulated_msrs holds
324 * MSRs that KVM emulates without strictly requiring host support.
325 * msr_based_features holds MSRs that enumerate features, i.e. are effectively
326 * CPUID leafs. Note, msr_based_features isn't mutually exclusive with
327 * msrs_to_save and emulated_msrs.
328 */
329
330 static const u32 msrs_to_save_base[] = {
331 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
332 MSR_STAR,
333 #ifdef CONFIG_X86_64
334 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
335 #endif
336 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
337 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
338 MSR_IA32_SPEC_CTRL, MSR_IA32_TSX_CTRL,
339 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
340 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
341 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
342 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
343 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
344 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
345 MSR_IA32_UMWAIT_CONTROL,
346
347 MSR_IA32_XFD, MSR_IA32_XFD_ERR, MSR_IA32_XSS,
348
349 MSR_IA32_U_CET, MSR_IA32_S_CET,
350 MSR_IA32_PL0_SSP, MSR_IA32_PL1_SSP, MSR_IA32_PL2_SSP,
351 MSR_IA32_PL3_SSP, MSR_IA32_INT_SSP_TAB,
352 };
353
354 static const u32 msrs_to_save_pmu[] = {
355 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
356 MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
357 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
358 MSR_CORE_PERF_GLOBAL_CTRL,
359 MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
360
361 /* This part of MSRs should match KVM_MAX_NR_INTEL_GP_COUNTERS. */
362 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
363 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
364 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
365 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
366 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
367 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
368 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
369 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
370
371 MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
372 MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
373
374 /* This part of MSRs should match KVM_MAX_NR_AMD_GP_COUNTERS. */
375 MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
376 MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
377 MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
378 MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
379
380 MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
381 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
382 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
383 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET,
384 };
385
386 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_base) +
387 ARRAY_SIZE(msrs_to_save_pmu)];
388 static unsigned num_msrs_to_save;
389
390 static const u32 emulated_msrs_all[] = {
391 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
392 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
393
394 #ifdef CONFIG_KVM_HYPERV
395 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
396 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
397 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
398 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
399 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
400 HV_X64_MSR_RESET,
401 HV_X64_MSR_VP_INDEX,
402 HV_X64_MSR_VP_RUNTIME,
403 HV_X64_MSR_SCONTROL,
404 HV_X64_MSR_STIMER0_CONFIG,
405 HV_X64_MSR_VP_ASSIST_PAGE,
406 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
407 HV_X64_MSR_TSC_EMULATION_STATUS, HV_X64_MSR_TSC_INVARIANT_CONTROL,
408 HV_X64_MSR_SYNDBG_OPTIONS,
409 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
410 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
411 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
412 #endif
413
414 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
415 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
416
417 MSR_IA32_TSC_ADJUST,
418 MSR_IA32_TSC_DEADLINE,
419 MSR_IA32_ARCH_CAPABILITIES,
420 MSR_IA32_PERF_CAPABILITIES,
421 MSR_IA32_MISC_ENABLE,
422 MSR_IA32_MCG_STATUS,
423 MSR_IA32_MCG_CTL,
424 MSR_IA32_MCG_EXT_CTL,
425 MSR_IA32_SMBASE,
426 MSR_SMI_COUNT,
427 MSR_PLATFORM_INFO,
428 MSR_MISC_FEATURES_ENABLES,
429 MSR_AMD64_VIRT_SPEC_CTRL,
430 MSR_AMD64_TSC_RATIO,
431 MSR_IA32_POWER_CTL,
432 MSR_IA32_UCODE_REV,
433
434 /*
435 * KVM always supports the "true" VMX control MSRs, even if the host
436 * does not. The VMX MSRs as a whole are considered "emulated" as KVM
437 * doesn't strictly require them to exist in the host (ignoring that
438 * KVM would refuse to load in the first place if the core set of MSRs
439 * aren't supported).
440 */
441 MSR_IA32_VMX_BASIC,
442 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
443 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
444 MSR_IA32_VMX_TRUE_EXIT_CTLS,
445 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
446 MSR_IA32_VMX_MISC,
447 MSR_IA32_VMX_CR0_FIXED0,
448 MSR_IA32_VMX_CR4_FIXED0,
449 MSR_IA32_VMX_VMCS_ENUM,
450 MSR_IA32_VMX_PROCBASED_CTLS2,
451 MSR_IA32_VMX_EPT_VPID_CAP,
452 MSR_IA32_VMX_VMFUNC,
453
454 MSR_K7_HWCR,
455 MSR_KVM_POLL_CONTROL,
456 };
457
458 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
459 static unsigned num_emulated_msrs;
460
461 /*
462 * List of MSRs that control the existence of MSR-based features, i.e. MSRs
463 * that are effectively CPUID leafs. VMX MSRs are also included in the set of
464 * feature MSRs, but are handled separately to allow expedited lookups.
465 */
466 static const u32 msr_based_features_all_except_vmx[] = {
467 MSR_AMD64_DE_CFG,
468 MSR_IA32_UCODE_REV,
469 MSR_IA32_ARCH_CAPABILITIES,
470 MSR_IA32_PERF_CAPABILITIES,
471 MSR_PLATFORM_INFO,
472 };
473
474 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all_except_vmx) +
475 (KVM_LAST_EMULATED_VMX_MSR - KVM_FIRST_EMULATED_VMX_MSR + 1)];
476 static unsigned int num_msr_based_features;
477
478 /*
479 * All feature MSRs except uCode revID, which tracks the currently loaded uCode
480 * patch, are immutable once the vCPU model is defined.
481 */
kvm_is_immutable_feature_msr(u32 msr)482 static bool kvm_is_immutable_feature_msr(u32 msr)
483 {
484 int i;
485
486 if (msr >= KVM_FIRST_EMULATED_VMX_MSR && msr <= KVM_LAST_EMULATED_VMX_MSR)
487 return true;
488
489 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++) {
490 if (msr == msr_based_features_all_except_vmx[i])
491 return msr != MSR_IA32_UCODE_REV;
492 }
493
494 return false;
495 }
496
kvm_is_advertised_msr(u32 msr_index)497 static bool kvm_is_advertised_msr(u32 msr_index)
498 {
499 unsigned int i;
500
501 for (i = 0; i < num_msrs_to_save; i++) {
502 if (msrs_to_save[i] == msr_index)
503 return true;
504 }
505
506 for (i = 0; i < num_emulated_msrs; i++) {
507 if (emulated_msrs[i] == msr_index)
508 return true;
509 }
510
511 return false;
512 }
513
514 typedef int (*msr_access_t)(struct kvm_vcpu *vcpu, u32 index, u64 *data,
515 bool host_initiated);
516
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)517 static __always_inline int kvm_do_msr_access(struct kvm_vcpu *vcpu, u32 msr,
518 u64 *data, bool host_initiated,
519 enum kvm_msr_access rw,
520 msr_access_t msr_access_fn)
521 {
522 const char *op = rw == MSR_TYPE_W ? "wrmsr" : "rdmsr";
523 int ret;
524
525 BUILD_BUG_ON(rw != MSR_TYPE_R && rw != MSR_TYPE_W);
526
527 /*
528 * Zero the data on read failures to avoid leaking stack data to the
529 * guest and/or userspace, e.g. if the failure is ignored below.
530 */
531 ret = msr_access_fn(vcpu, msr, data, host_initiated);
532 if (ret && rw == MSR_TYPE_R)
533 *data = 0;
534
535 if (ret != KVM_MSR_RET_UNSUPPORTED)
536 return ret;
537
538 /*
539 * Userspace is allowed to read MSRs, and write '0' to MSRs, that KVM
540 * advertises to userspace, even if an MSR isn't fully supported.
541 * Simply check that @data is '0', which covers both the write '0' case
542 * and all reads (in which case @data is zeroed on failure; see above).
543 */
544 if (host_initiated && !*data && kvm_is_advertised_msr(msr))
545 return 0;
546
547 if (!ignore_msrs) {
548 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
549 op, msr, *data);
550 return ret;
551 }
552
553 if (report_ignored_msrs)
554 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n", op, msr, *data);
555
556 return 0;
557 }
558
kvm_alloc_emulator_cache(void)559 static struct kmem_cache *kvm_alloc_emulator_cache(void)
560 {
561 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
562 unsigned int size = sizeof(struct x86_emulate_ctxt);
563
564 return kmem_cache_create_usercopy("x86_emulator", size,
565 __alignof__(struct x86_emulate_ctxt),
566 SLAB_ACCOUNT, useroffset,
567 size - useroffset, NULL);
568 }
569
570 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
571
kvm_async_pf_hash_reset(struct kvm_vcpu * vcpu)572 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
573 {
574 int i;
575 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
576 vcpu->arch.apf.gfns[i] = ~0;
577 }
578
kvm_on_user_return(struct user_return_notifier * urn)579 static void kvm_on_user_return(struct user_return_notifier *urn)
580 {
581 unsigned slot;
582 struct kvm_user_return_msrs *msrs
583 = container_of(urn, struct kvm_user_return_msrs, urn);
584 struct kvm_user_return_msr_values *values;
585 unsigned long flags;
586
587 /*
588 * Disabling irqs at this point since the following code could be
589 * interrupted and executed through kvm_arch_disable_virtualization_cpu()
590 */
591 local_irq_save(flags);
592 if (msrs->registered) {
593 msrs->registered = false;
594 user_return_notifier_unregister(urn);
595 }
596 local_irq_restore(flags);
597 for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
598 values = &msrs->values[slot];
599 if (values->host != values->curr) {
600 wrmsrq(kvm_uret_msrs_list[slot], values->host);
601 values->curr = values->host;
602 }
603 }
604 }
605
kvm_probe_user_return_msr(u32 msr)606 static int kvm_probe_user_return_msr(u32 msr)
607 {
608 u64 val;
609 int ret;
610
611 preempt_disable();
612 ret = rdmsrq_safe(msr, &val);
613 if (ret)
614 goto out;
615 ret = wrmsrq_safe(msr, val);
616 out:
617 preempt_enable();
618 return ret;
619 }
620
kvm_add_user_return_msr(u32 msr)621 int kvm_add_user_return_msr(u32 msr)
622 {
623 BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
624
625 if (kvm_probe_user_return_msr(msr))
626 return -1;
627
628 kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
629 return kvm_nr_uret_msrs++;
630 }
631 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_add_user_return_msr);
632
kvm_find_user_return_msr(u32 msr)633 int kvm_find_user_return_msr(u32 msr)
634 {
635 int i;
636
637 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
638 if (kvm_uret_msrs_list[i] == msr)
639 return i;
640 }
641 return -1;
642 }
643 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_find_user_return_msr);
644
kvm_user_return_msr_cpu_online(void)645 static void kvm_user_return_msr_cpu_online(void)
646 {
647 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
648 u64 value;
649 int i;
650
651 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
652 rdmsrq_safe(kvm_uret_msrs_list[i], &value);
653 msrs->values[i].host = value;
654 msrs->values[i].curr = value;
655 }
656 }
657
kvm_user_return_register_notifier(struct kvm_user_return_msrs * msrs)658 static void kvm_user_return_register_notifier(struct kvm_user_return_msrs *msrs)
659 {
660 if (!msrs->registered) {
661 msrs->urn.on_user_return = kvm_on_user_return;
662 user_return_notifier_register(&msrs->urn);
663 msrs->registered = true;
664 }
665 }
666
kvm_set_user_return_msr(unsigned slot,u64 value,u64 mask)667 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
668 {
669 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
670 int err;
671
672 value = (value & mask) | (msrs->values[slot].host & ~mask);
673 if (value == msrs->values[slot].curr)
674 return 0;
675 err = wrmsrq_safe(kvm_uret_msrs_list[slot], value);
676 if (err)
677 return 1;
678
679 msrs->values[slot].curr = value;
680 kvm_user_return_register_notifier(msrs);
681 return 0;
682 }
683 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_user_return_msr);
684
kvm_user_return_msr_update_cache(unsigned int slot,u64 value)685 void kvm_user_return_msr_update_cache(unsigned int slot, u64 value)
686 {
687 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
688
689 msrs->values[slot].curr = value;
690 kvm_user_return_register_notifier(msrs);
691 }
692 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_user_return_msr_update_cache);
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(!kvm_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 if (!is_guest_mode(vcpu))
873 kvm_deliver_exception_payload(vcpu,
874 &vcpu->arch.exception);
875 return;
876 }
877
878 /* to check exception */
879 prev_nr = vcpu->arch.exception.vector;
880 if (prev_nr == DF_VECTOR) {
881 /* triple fault -> shutdown */
882 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
883 return;
884 }
885 class1 = exception_class(prev_nr);
886 class2 = exception_class(nr);
887 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
888 (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
889 /*
890 * Synthesize #DF. Clear the previously injected or pending
891 * exception so as not to incorrectly trigger shutdown.
892 */
893 vcpu->arch.exception.injected = false;
894 vcpu->arch.exception.pending = false;
895
896 kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
897 } else {
898 /* replace previous exception with a new one in a hope
899 that instruction re-execution will regenerate lost
900 exception */
901 goto queue;
902 }
903 }
904
kvm_queue_exception(struct kvm_vcpu * vcpu,unsigned nr)905 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
906 {
907 kvm_multiple_exception(vcpu, nr, false, 0, false, 0);
908 }
909 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception);
910
911
kvm_queue_exception_p(struct kvm_vcpu * vcpu,unsigned nr,unsigned long payload)912 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
913 unsigned long payload)
914 {
915 kvm_multiple_exception(vcpu, nr, false, 0, true, payload);
916 }
917 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_p);
918
kvm_queue_exception_e_p(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code,unsigned long payload)919 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
920 u32 error_code, unsigned long payload)
921 {
922 kvm_multiple_exception(vcpu, nr, true, error_code, true, payload);
923 }
924
kvm_requeue_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error_code,u32 error_code)925 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
926 bool has_error_code, u32 error_code)
927 {
928
929 /*
930 * On VM-Entry, an exception can be pending if and only if event
931 * injection was blocked by nested_run_pending. In that case, however,
932 * vcpu_enter_guest() requests an immediate exit, and the guest
933 * shouldn't proceed far enough to need reinjection.
934 */
935 WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
936
937 /*
938 * Do not check for interception when injecting an event for L2, as the
939 * exception was checked for intercept when it was original queued, and
940 * re-checking is incorrect if _L1_ injected the exception, in which
941 * case it's exempt from interception.
942 */
943 kvm_make_request(KVM_REQ_EVENT, vcpu);
944
945 vcpu->arch.exception.injected = true;
946 vcpu->arch.exception.has_error_code = has_error_code;
947 vcpu->arch.exception.vector = nr;
948 vcpu->arch.exception.error_code = error_code;
949 vcpu->arch.exception.has_payload = false;
950 vcpu->arch.exception.payload = 0;
951 }
952 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_requeue_exception);
953
kvm_complete_insn_gp(struct kvm_vcpu * vcpu,int err)954 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
955 {
956 if (err)
957 kvm_inject_gp(vcpu, 0);
958 else
959 return kvm_skip_emulated_instruction(vcpu);
960
961 return 1;
962 }
963 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_complete_insn_gp);
964
complete_emulated_insn_gp(struct kvm_vcpu * vcpu,int err)965 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
966 {
967 if (err) {
968 kvm_inject_gp(vcpu, 0);
969 return 1;
970 }
971
972 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
973 EMULTYPE_COMPLETE_USER_EXIT);
974 }
975
kvm_inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)976 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
977 {
978 ++vcpu->stat.pf_guest;
979
980 /*
981 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
982 * whether or not L1 wants to intercept "regular" #PF.
983 */
984 if (is_guest_mode(vcpu) && fault->async_page_fault)
985 kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
986 true, fault->error_code,
987 true, fault->address);
988 else
989 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
990 fault->address);
991 }
992
kvm_inject_emulated_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)993 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
994 struct x86_exception *fault)
995 {
996 struct kvm_mmu *fault_mmu;
997 WARN_ON_ONCE(fault->vector != PF_VECTOR);
998
999 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
1000 vcpu->arch.walk_mmu;
1001
1002 /*
1003 * Invalidate the TLB entry for the faulting address, if it exists,
1004 * else the access will fault indefinitely (and to emulate hardware).
1005 */
1006 if ((fault->error_code & PFERR_PRESENT_MASK) &&
1007 !(fault->error_code & PFERR_RSVD_MASK))
1008 kvm_mmu_invalidate_addr(vcpu, fault_mmu, fault->address,
1009 KVM_MMU_ROOT_CURRENT);
1010
1011 fault_mmu->inject_page_fault(vcpu, fault);
1012 }
1013 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_emulated_page_fault);
1014
kvm_inject_nmi(struct kvm_vcpu * vcpu)1015 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
1016 {
1017 atomic_inc(&vcpu->arch.nmi_queued);
1018 kvm_make_request(KVM_REQ_NMI, vcpu);
1019 }
1020
kvm_queue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)1021 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
1022 {
1023 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0);
1024 }
1025 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_e);
1026
1027 /*
1028 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
1029 * a #GP and return false.
1030 */
kvm_require_cpl(struct kvm_vcpu * vcpu,int required_cpl)1031 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
1032 {
1033 if (kvm_x86_call(get_cpl)(vcpu) <= required_cpl)
1034 return true;
1035 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
1036 return false;
1037 }
1038
kvm_require_dr(struct kvm_vcpu * vcpu,int dr)1039 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
1040 {
1041 if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
1042 return true;
1043
1044 kvm_queue_exception(vcpu, UD_VECTOR);
1045 return false;
1046 }
1047 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_require_dr);
1048
pdptr_rsvd_bits(struct kvm_vcpu * vcpu)1049 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
1050 {
1051 return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
1052 }
1053
1054 /*
1055 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
1056 */
load_pdptrs(struct kvm_vcpu * vcpu,unsigned long cr3)1057 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
1058 {
1059 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
1060 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
1061 gpa_t real_gpa;
1062 int i;
1063 int ret;
1064 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
1065
1066 /*
1067 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
1068 * to an L1 GPA.
1069 */
1070 real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
1071 PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
1072 if (real_gpa == INVALID_GPA)
1073 return 0;
1074
1075 /* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
1076 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
1077 cr3 & GENMASK(11, 5), sizeof(pdpte));
1078 if (ret < 0)
1079 return 0;
1080
1081 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
1082 if ((pdpte[i] & PT_PRESENT_MASK) &&
1083 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
1084 return 0;
1085 }
1086 }
1087
1088 /*
1089 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
1090 * Shadow page roots need to be reconstructed instead.
1091 */
1092 if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
1093 kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
1094
1095 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
1096 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
1097 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
1098 vcpu->arch.pdptrs_from_userspace = false;
1099
1100 return 1;
1101 }
1102 EXPORT_SYMBOL_FOR_KVM_INTERNAL(load_pdptrs);
1103
kvm_is_valid_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1104 static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1105 {
1106 #ifdef CONFIG_X86_64
1107 if (cr0 & 0xffffffff00000000UL)
1108 return false;
1109 #endif
1110
1111 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
1112 return false;
1113
1114 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
1115 return false;
1116
1117 return kvm_x86_call(is_valid_cr0)(vcpu, cr0);
1118 }
1119
kvm_post_set_cr0(struct kvm_vcpu * vcpu,unsigned long old_cr0,unsigned long cr0)1120 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
1121 {
1122 /*
1123 * CR0.WP is incorporated into the MMU role, but only for non-nested,
1124 * indirect shadow MMUs. If paging is disabled, no updates are needed
1125 * as there are no permission bits to emulate. If TDP is enabled, the
1126 * MMU's metadata needs to be updated, e.g. so that emulating guest
1127 * translations does the right thing, but there's no need to unload the
1128 * root as CR0.WP doesn't affect SPTEs.
1129 */
1130 if ((cr0 ^ old_cr0) == X86_CR0_WP) {
1131 if (!(cr0 & X86_CR0_PG))
1132 return;
1133
1134 if (tdp_enabled) {
1135 kvm_init_mmu(vcpu);
1136 return;
1137 }
1138 }
1139
1140 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
1141 kvm_clear_async_pf_completion_queue(vcpu);
1142 kvm_async_pf_hash_reset(vcpu);
1143
1144 /*
1145 * Clearing CR0.PG is defined to flush the TLB from the guest's
1146 * perspective.
1147 */
1148 if (!(cr0 & X86_CR0_PG))
1149 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1150 }
1151
1152 if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
1153 kvm_mmu_reset_context(vcpu);
1154 }
1155 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_post_set_cr0);
1156
kvm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1157 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1158 {
1159 unsigned long old_cr0 = kvm_read_cr0(vcpu);
1160
1161 if (!kvm_is_valid_cr0(vcpu, cr0))
1162 return 1;
1163
1164 cr0 |= X86_CR0_ET;
1165
1166 /* Write to CR0 reserved bits are ignored, even on Intel. */
1167 cr0 &= ~CR0_RESERVED_BITS;
1168
1169 #ifdef CONFIG_X86_64
1170 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
1171 (cr0 & X86_CR0_PG)) {
1172 int cs_db, cs_l;
1173
1174 if (!is_pae(vcpu))
1175 return 1;
1176 kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
1177 if (cs_l)
1178 return 1;
1179 }
1180 #endif
1181 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
1182 is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
1183 !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1184 return 1;
1185
1186 if (!(cr0 & X86_CR0_PG) &&
1187 (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
1188 return 1;
1189
1190 if (!(cr0 & X86_CR0_WP) && kvm_is_cr4_bit_set(vcpu, X86_CR4_CET))
1191 return 1;
1192
1193 kvm_x86_call(set_cr0)(vcpu, cr0);
1194
1195 kvm_post_set_cr0(vcpu, old_cr0, cr0);
1196
1197 return 0;
1198 }
1199 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr0);
1200
kvm_lmsw(struct kvm_vcpu * vcpu,unsigned long msw)1201 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
1202 {
1203 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
1204 }
1205 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_lmsw);
1206
kvm_load_guest_xsave_state(struct kvm_vcpu * vcpu)1207 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
1208 {
1209 if (vcpu->arch.guest_state_protected)
1210 return;
1211
1212 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1213
1214 if (vcpu->arch.xcr0 != kvm_host.xcr0)
1215 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
1216
1217 if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1218 vcpu->arch.ia32_xss != kvm_host.xss)
1219 wrmsrq(MSR_IA32_XSS, vcpu->arch.ia32_xss);
1220 }
1221
1222 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1223 vcpu->arch.pkru != vcpu->arch.host_pkru &&
1224 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1225 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
1226 wrpkru(vcpu->arch.pkru);
1227 }
1228 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_load_guest_xsave_state);
1229
kvm_load_host_xsave_state(struct kvm_vcpu * vcpu)1230 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
1231 {
1232 if (vcpu->arch.guest_state_protected)
1233 return;
1234
1235 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1236 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1237 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
1238 vcpu->arch.pkru = rdpkru();
1239 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1240 wrpkru(vcpu->arch.host_pkru);
1241 }
1242
1243 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1244
1245 if (vcpu->arch.xcr0 != kvm_host.xcr0)
1246 xsetbv(XCR_XFEATURE_ENABLED_MASK, kvm_host.xcr0);
1247
1248 if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1249 vcpu->arch.ia32_xss != kvm_host.xss)
1250 wrmsrq(MSR_IA32_XSS, kvm_host.xss);
1251 }
1252
1253 }
1254 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_load_host_xsave_state);
1255
1256 #ifdef CONFIG_X86_64
kvm_guest_supported_xfd(struct kvm_vcpu * vcpu)1257 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1258 {
1259 return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
1260 }
1261 #endif
1262
__kvm_set_xcr(struct kvm_vcpu * vcpu,u32 index,u64 xcr)1263 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1264 {
1265 u64 xcr0 = xcr;
1266 u64 old_xcr0 = vcpu->arch.xcr0;
1267 u64 valid_bits;
1268
1269 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
1270 if (index != XCR_XFEATURE_ENABLED_MASK)
1271 return 1;
1272 if (!(xcr0 & XFEATURE_MASK_FP))
1273 return 1;
1274 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1275 return 1;
1276
1277 /*
1278 * Do not allow the guest to set bits that we do not support
1279 * saving. However, xcr0 bit 0 is always set, even if the
1280 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1281 */
1282 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
1283 if (xcr0 & ~valid_bits)
1284 return 1;
1285
1286 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1287 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1288 return 1;
1289
1290 if (xcr0 & XFEATURE_MASK_AVX512) {
1291 if (!(xcr0 & XFEATURE_MASK_YMM))
1292 return 1;
1293 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1294 return 1;
1295 }
1296
1297 if ((xcr0 & XFEATURE_MASK_XTILE) &&
1298 ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1299 return 1;
1300
1301 vcpu->arch.xcr0 = xcr0;
1302
1303 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1304 vcpu->arch.cpuid_dynamic_bits_dirty = true;
1305 return 0;
1306 }
1307 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_set_xcr);
1308
kvm_emulate_xsetbv(struct kvm_vcpu * vcpu)1309 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1310 {
1311 /* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
1312 if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
1313 __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1314 kvm_inject_gp(vcpu, 0);
1315 return 1;
1316 }
1317
1318 return kvm_skip_emulated_instruction(vcpu);
1319 }
1320 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_xsetbv);
1321
kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1322 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1323 {
1324 return __kvm_is_valid_cr4(vcpu, cr4) &&
1325 kvm_x86_call(is_valid_cr4)(vcpu, cr4);
1326 }
1327
kvm_post_set_cr4(struct kvm_vcpu * vcpu,unsigned long old_cr4,unsigned long cr4)1328 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1329 {
1330 if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1331 kvm_mmu_reset_context(vcpu);
1332
1333 /*
1334 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1335 * according to the SDM; however, stale prev_roots could be reused
1336 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1337 * free them all. This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1338 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1339 * so fall through.
1340 */
1341 if (!tdp_enabled &&
1342 (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1343 kvm_mmu_unload(vcpu);
1344
1345 /*
1346 * The TLB has to be flushed for all PCIDs if any of the following
1347 * (architecturally required) changes happen:
1348 * - CR4.PCIDE is changed from 1 to 0
1349 * - CR4.PGE is toggled
1350 *
1351 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1352 */
1353 if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1354 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1355 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1356
1357 /*
1358 * The TLB has to be flushed for the current PCID if any of the
1359 * following (architecturally required) changes happen:
1360 * - CR4.SMEP is changed from 0 to 1
1361 * - CR4.PAE is toggled
1362 */
1363 else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1364 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1365 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1366
1367 }
1368 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_post_set_cr4);
1369
kvm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1370 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1371 {
1372 unsigned long old_cr4 = kvm_read_cr4(vcpu);
1373
1374 if (!kvm_is_valid_cr4(vcpu, cr4))
1375 return 1;
1376
1377 if (is_long_mode(vcpu)) {
1378 if (!(cr4 & X86_CR4_PAE))
1379 return 1;
1380 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1381 return 1;
1382 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1383 && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1384 && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1385 return 1;
1386
1387 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1388 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1389 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1390 return 1;
1391 }
1392
1393 if ((cr4 & X86_CR4_CET) && !kvm_is_cr0_bit_set(vcpu, X86_CR0_WP))
1394 return 1;
1395
1396 kvm_x86_call(set_cr4)(vcpu, cr4);
1397
1398 kvm_post_set_cr4(vcpu, old_cr4, cr4);
1399
1400 return 0;
1401 }
1402 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr4);
1403
kvm_invalidate_pcid(struct kvm_vcpu * vcpu,unsigned long pcid)1404 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1405 {
1406 struct kvm_mmu *mmu = vcpu->arch.mmu;
1407 unsigned long roots_to_free = 0;
1408 int i;
1409
1410 /*
1411 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1412 * this is reachable when running EPT=1 and unrestricted_guest=0, and
1413 * also via the emulator. KVM's TDP page tables are not in the scope of
1414 * the invalidation, but the guest's TLB entries need to be flushed as
1415 * the CPU may have cached entries in its TLB for the target PCID.
1416 */
1417 if (unlikely(tdp_enabled)) {
1418 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1419 return;
1420 }
1421
1422 /*
1423 * If neither the current CR3 nor any of the prev_roots use the given
1424 * PCID, then nothing needs to be done here because a resync will
1425 * happen anyway before switching to any other CR3.
1426 */
1427 if (kvm_get_active_pcid(vcpu) == pcid) {
1428 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1429 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1430 }
1431
1432 /*
1433 * If PCID is disabled, there is no need to free prev_roots even if the
1434 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1435 * with PCIDE=0.
1436 */
1437 if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
1438 return;
1439
1440 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1441 if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1442 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1443
1444 kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1445 }
1446
kvm_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)1447 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1448 {
1449 bool skip_tlb_flush = false;
1450 unsigned long pcid = 0;
1451 #ifdef CONFIG_X86_64
1452 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)) {
1453 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1454 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1455 pcid = cr3 & X86_CR3_PCID_MASK;
1456 }
1457 #endif
1458
1459 /* PDPTRs are always reloaded for PAE paging. */
1460 if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1461 goto handle_tlb_flush;
1462
1463 /*
1464 * Do not condition the GPA check on long mode, this helper is used to
1465 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1466 * the current vCPU mode is accurate.
1467 */
1468 if (!kvm_vcpu_is_legal_cr3(vcpu, cr3))
1469 return 1;
1470
1471 if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1472 return 1;
1473
1474 if (cr3 != kvm_read_cr3(vcpu))
1475 kvm_mmu_new_pgd(vcpu, cr3);
1476
1477 vcpu->arch.cr3 = cr3;
1478 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1479 /* Do not call post_set_cr3, we do not get here for confidential guests. */
1480
1481 handle_tlb_flush:
1482 /*
1483 * A load of CR3 that flushes the TLB flushes only the current PCID,
1484 * even if PCID is disabled, in which case PCID=0 is flushed. It's a
1485 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1486 * and it's impossible to use a non-zero PCID when PCID is disabled,
1487 * i.e. only PCID=0 can be relevant.
1488 */
1489 if (!skip_tlb_flush)
1490 kvm_invalidate_pcid(vcpu, pcid);
1491
1492 return 0;
1493 }
1494 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr3);
1495
kvm_set_cr8(struct kvm_vcpu * vcpu,unsigned long cr8)1496 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1497 {
1498 if (cr8 & CR8_RESERVED_BITS)
1499 return 1;
1500 if (lapic_in_kernel(vcpu))
1501 kvm_lapic_set_tpr(vcpu, cr8);
1502 else
1503 vcpu->arch.cr8 = cr8;
1504 return 0;
1505 }
1506 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr8);
1507
kvm_get_cr8(struct kvm_vcpu * vcpu)1508 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1509 {
1510 if (lapic_in_kernel(vcpu))
1511 return kvm_lapic_get_cr8(vcpu);
1512 else
1513 return vcpu->arch.cr8;
1514 }
1515 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_cr8);
1516
kvm_update_dr0123(struct kvm_vcpu * vcpu)1517 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1518 {
1519 int i;
1520
1521 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1522 for (i = 0; i < KVM_NR_DB_REGS; i++)
1523 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1524 }
1525 }
1526
kvm_update_dr7(struct kvm_vcpu * vcpu)1527 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1528 {
1529 unsigned long dr7;
1530
1531 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1532 dr7 = vcpu->arch.guest_debug_dr7;
1533 else
1534 dr7 = vcpu->arch.dr7;
1535 kvm_x86_call(set_dr7)(vcpu, dr7);
1536 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1537 if (dr7 & DR7_BP_EN_MASK)
1538 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1539 }
1540 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_update_dr7);
1541
kvm_dr6_fixed(struct kvm_vcpu * vcpu)1542 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1543 {
1544 u64 fixed = DR6_FIXED_1;
1545
1546 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_RTM))
1547 fixed |= DR6_RTM;
1548
1549 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1550 fixed |= DR6_BUS_LOCK;
1551 return fixed;
1552 }
1553
kvm_set_dr(struct kvm_vcpu * vcpu,int dr,unsigned long val)1554 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1555 {
1556 size_t size = ARRAY_SIZE(vcpu->arch.db);
1557
1558 switch (dr) {
1559 case 0 ... 3:
1560 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1561 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1562 vcpu->arch.eff_db[dr] = val;
1563 break;
1564 case 4:
1565 case 6:
1566 if (!kvm_dr6_valid(val))
1567 return 1; /* #GP */
1568 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1569 break;
1570 case 5:
1571 default: /* 7 */
1572 if (!kvm_dr7_valid(val))
1573 return 1; /* #GP */
1574 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1575 kvm_update_dr7(vcpu);
1576 break;
1577 }
1578
1579 return 0;
1580 }
1581 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_dr);
1582
kvm_get_dr(struct kvm_vcpu * vcpu,int dr)1583 unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr)
1584 {
1585 size_t size = ARRAY_SIZE(vcpu->arch.db);
1586
1587 switch (dr) {
1588 case 0 ... 3:
1589 return vcpu->arch.db[array_index_nospec(dr, size)];
1590 case 4:
1591 case 6:
1592 return vcpu->arch.dr6;
1593 case 5:
1594 default: /* 7 */
1595 return vcpu->arch.dr7;
1596 }
1597 }
1598 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_dr);
1599
kvm_emulate_rdpmc(struct kvm_vcpu * vcpu)1600 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1601 {
1602 u32 pmc = kvm_rcx_read(vcpu);
1603 u64 data;
1604
1605 if (kvm_pmu_rdpmc(vcpu, pmc, &data)) {
1606 kvm_inject_gp(vcpu, 0);
1607 return 1;
1608 }
1609
1610 kvm_rax_write(vcpu, (u32)data);
1611 kvm_rdx_write(vcpu, data >> 32);
1612 return kvm_skip_emulated_instruction(vcpu);
1613 }
1614 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdpmc);
1615
1616 /*
1617 * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1618 * does not yet virtualize. These include:
1619 * 10 - MISC_PACKAGE_CTRLS
1620 * 11 - ENERGY_FILTERING_CTL
1621 * 12 - DOITM
1622 * 18 - FB_CLEAR_CTRL
1623 * 21 - XAPIC_DISABLE_STATUS
1624 * 23 - OVERCLOCKING_STATUS
1625 */
1626
1627 #define KVM_SUPPORTED_ARCH_CAP \
1628 (ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1629 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1630 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1631 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1632 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
1633 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO | ARCH_CAP_ITS_NO)
1634
kvm_get_arch_capabilities(void)1635 static u64 kvm_get_arch_capabilities(void)
1636 {
1637 u64 data = kvm_host.arch_capabilities & KVM_SUPPORTED_ARCH_CAP;
1638
1639 /*
1640 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1641 * the nested hypervisor runs with NX huge pages. If it is not,
1642 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1643 * L1 guests, so it need not worry about its own (L2) guests.
1644 */
1645 data |= ARCH_CAP_PSCHANGE_MC_NO;
1646
1647 /*
1648 * If we're doing cache flushes (either "always" or "cond")
1649 * we will do one whenever the guest does a vmlaunch/vmresume.
1650 * If an outer hypervisor is doing the cache flush for us
1651 * (ARCH_CAP_SKIP_VMENTRY_L1DFLUSH), we can safely pass that
1652 * capability to the guest too, and if EPT is disabled we're not
1653 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1654 * require a nested hypervisor to do a flush of its own.
1655 */
1656 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1657 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1658
1659 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1660 data |= ARCH_CAP_RDCL_NO;
1661 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1662 data |= ARCH_CAP_SSB_NO;
1663 if (!boot_cpu_has_bug(X86_BUG_MDS))
1664 data |= ARCH_CAP_MDS_NO;
1665 if (!boot_cpu_has_bug(X86_BUG_RFDS))
1666 data |= ARCH_CAP_RFDS_NO;
1667 if (!boot_cpu_has_bug(X86_BUG_ITS))
1668 data |= ARCH_CAP_ITS_NO;
1669
1670 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1671 /*
1672 * If RTM=0 because the kernel has disabled TSX, the host might
1673 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1674 * and therefore knows that there cannot be TAA) but keep
1675 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1676 * and we want to allow migrating those guests to tsx=off hosts.
1677 */
1678 data &= ~ARCH_CAP_TAA_NO;
1679 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1680 data |= ARCH_CAP_TAA_NO;
1681 } else {
1682 /*
1683 * Nothing to do here; we emulate TSX_CTRL if present on the
1684 * host so the guest can choose between disabling TSX or
1685 * using VERW to clear CPU buffers.
1686 */
1687 }
1688
1689 if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1690 data |= ARCH_CAP_GDS_NO;
1691
1692 return data;
1693 }
1694
kvm_get_feature_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1695 static int kvm_get_feature_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1696 bool host_initiated)
1697 {
1698 WARN_ON_ONCE(!host_initiated);
1699
1700 switch (index) {
1701 case MSR_IA32_ARCH_CAPABILITIES:
1702 *data = kvm_get_arch_capabilities();
1703 break;
1704 case MSR_IA32_PERF_CAPABILITIES:
1705 *data = kvm_caps.supported_perf_cap;
1706 break;
1707 case MSR_PLATFORM_INFO:
1708 *data = MSR_PLATFORM_INFO_CPUID_FAULT;
1709 break;
1710 case MSR_IA32_UCODE_REV:
1711 rdmsrq_safe(index, data);
1712 break;
1713 default:
1714 return kvm_x86_call(get_feature_msr)(index, data);
1715 }
1716 return 0;
1717 }
1718
do_get_feature_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)1719 static int do_get_feature_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1720 {
1721 return kvm_do_msr_access(vcpu, index, data, true, MSR_TYPE_R,
1722 kvm_get_feature_msr);
1723 }
1724
__kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1725 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1726 {
1727 if (efer & EFER_AUTOIBRS && !guest_cpu_cap_has(vcpu, X86_FEATURE_AUTOIBRS))
1728 return false;
1729
1730 if (efer & EFER_FFXSR && !guest_cpu_cap_has(vcpu, X86_FEATURE_FXSR_OPT))
1731 return false;
1732
1733 if (efer & EFER_SVME && !guest_cpu_cap_has(vcpu, X86_FEATURE_SVM))
1734 return false;
1735
1736 if (efer & (EFER_LME | EFER_LMA) &&
1737 !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1738 return false;
1739
1740 if (efer & EFER_NX && !guest_cpu_cap_has(vcpu, X86_FEATURE_NX))
1741 return false;
1742
1743 return true;
1744
1745 }
kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1746 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1747 {
1748 if (efer & efer_reserved_bits)
1749 return false;
1750
1751 return __kvm_valid_efer(vcpu, efer);
1752 }
1753 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_valid_efer);
1754
set_efer(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1755 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1756 {
1757 u64 old_efer = vcpu->arch.efer;
1758 u64 efer = msr_info->data;
1759 int r;
1760
1761 if (efer & efer_reserved_bits)
1762 return 1;
1763
1764 if (!msr_info->host_initiated) {
1765 if (!__kvm_valid_efer(vcpu, efer))
1766 return 1;
1767
1768 if (is_paging(vcpu) &&
1769 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1770 return 1;
1771 }
1772
1773 efer &= ~EFER_LMA;
1774 efer |= vcpu->arch.efer & EFER_LMA;
1775
1776 r = kvm_x86_call(set_efer)(vcpu, efer);
1777 if (r) {
1778 WARN_ON(r > 0);
1779 return r;
1780 }
1781
1782 if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1783 kvm_mmu_reset_context(vcpu);
1784
1785 if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1786 (efer & EFER_SVME))
1787 kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1788
1789 return 0;
1790 }
1791
kvm_enable_efer_bits(u64 mask)1792 void kvm_enable_efer_bits(u64 mask)
1793 {
1794 efer_reserved_bits &= ~mask;
1795 }
1796 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_enable_efer_bits);
1797
kvm_msr_allowed(struct kvm_vcpu * vcpu,u32 index,u32 type)1798 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1799 {
1800 struct kvm_x86_msr_filter *msr_filter;
1801 struct msr_bitmap_range *ranges;
1802 struct kvm *kvm = vcpu->kvm;
1803 bool allowed;
1804 int idx;
1805 u32 i;
1806
1807 /* x2APIC MSRs do not support filtering. */
1808 if (index >= 0x800 && index <= 0x8ff)
1809 return true;
1810
1811 idx = srcu_read_lock(&kvm->srcu);
1812
1813 msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1814 if (!msr_filter) {
1815 allowed = true;
1816 goto out;
1817 }
1818
1819 allowed = msr_filter->default_allow;
1820 ranges = msr_filter->ranges;
1821
1822 for (i = 0; i < msr_filter->count; i++) {
1823 u32 start = ranges[i].base;
1824 u32 end = start + ranges[i].nmsrs;
1825 u32 flags = ranges[i].flags;
1826 unsigned long *bitmap = ranges[i].bitmap;
1827
1828 if ((index >= start) && (index < end) && (flags & type)) {
1829 allowed = test_bit(index - start, bitmap);
1830 break;
1831 }
1832 }
1833
1834 out:
1835 srcu_read_unlock(&kvm->srcu, idx);
1836
1837 return allowed;
1838 }
1839 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_msr_allowed);
1840
1841 /*
1842 * Write @data into the MSR specified by @index. Select MSR specific fault
1843 * checks are bypassed if @host_initiated is %true.
1844 * Returns 0 on success, non-0 otherwise.
1845 * Assumes vcpu_load() was already called.
1846 */
__kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1847 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1848 bool host_initiated)
1849 {
1850 struct msr_data msr;
1851
1852 switch (index) {
1853 case MSR_FS_BASE:
1854 case MSR_GS_BASE:
1855 case MSR_KERNEL_GS_BASE:
1856 case MSR_CSTAR:
1857 case MSR_LSTAR:
1858 if (is_noncanonical_msr_address(data, vcpu))
1859 return 1;
1860 break;
1861 case MSR_IA32_SYSENTER_EIP:
1862 case MSR_IA32_SYSENTER_ESP:
1863 /*
1864 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1865 * non-canonical address is written on Intel but not on
1866 * AMD (which ignores the top 32-bits, because it does
1867 * not implement 64-bit SYSENTER).
1868 *
1869 * 64-bit code should hence be able to write a non-canonical
1870 * value on AMD. Making the address canonical ensures that
1871 * vmentry does not fail on Intel after writing a non-canonical
1872 * value, and that something deterministic happens if the guest
1873 * invokes 64-bit SYSENTER.
1874 */
1875 data = __canonical_address(data, max_host_virt_addr_bits());
1876 break;
1877 case MSR_TSC_AUX:
1878 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1879 return 1;
1880
1881 if (!host_initiated &&
1882 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1883 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1884 return 1;
1885
1886 /*
1887 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1888 * incomplete and conflicting architectural behavior. Current
1889 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1890 * reserved and always read as zeros. Enforce Intel's reserved
1891 * bits check if the guest CPU is Intel compatible, otherwise
1892 * clear the bits. This ensures cross-vendor migration will
1893 * provide consistent behavior for the guest.
1894 */
1895 if (guest_cpuid_is_intel_compatible(vcpu) && (data >> 32) != 0)
1896 return 1;
1897
1898 data = (u32)data;
1899 break;
1900 case MSR_IA32_U_CET:
1901 case MSR_IA32_S_CET:
1902 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
1903 !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT))
1904 return KVM_MSR_RET_UNSUPPORTED;
1905 if (!kvm_is_valid_u_s_cet(vcpu, data))
1906 return 1;
1907 break;
1908 case MSR_KVM_INTERNAL_GUEST_SSP:
1909 if (!host_initiated)
1910 return 1;
1911 fallthrough;
1912 /*
1913 * Note that the MSR emulation here is flawed when a vCPU
1914 * doesn't support the Intel 64 architecture. The expected
1915 * architectural behavior in this case is that the upper 32
1916 * bits do not exist and should always read '0'. However,
1917 * because the actual hardware on which the virtual CPU is
1918 * running does support Intel 64, XRSTORS/XSAVES in the
1919 * guest could observe behavior that violates the
1920 * architecture. Intercepting XRSTORS/XSAVES for this
1921 * special case isn't deemed worthwhile.
1922 */
1923 case MSR_IA32_PL0_SSP ... MSR_IA32_INT_SSP_TAB:
1924 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
1925 return KVM_MSR_RET_UNSUPPORTED;
1926 /*
1927 * MSR_IA32_INT_SSP_TAB is not present on processors that do
1928 * not support Intel 64 architecture.
1929 */
1930 if (index == MSR_IA32_INT_SSP_TAB && !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1931 return KVM_MSR_RET_UNSUPPORTED;
1932 if (is_noncanonical_msr_address(data, vcpu))
1933 return 1;
1934 /* All SSP MSRs except MSR_IA32_INT_SSP_TAB must be 4-byte aligned */
1935 if (index != MSR_IA32_INT_SSP_TAB && !IS_ALIGNED(data, 4))
1936 return 1;
1937 break;
1938 }
1939
1940 msr.data = data;
1941 msr.index = index;
1942 msr.host_initiated = host_initiated;
1943
1944 return kvm_x86_call(set_msr)(vcpu, &msr);
1945 }
1946
_kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1947 static int _kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1948 bool host_initiated)
1949 {
1950 return __kvm_set_msr(vcpu, index, *data, host_initiated);
1951 }
1952
kvm_set_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1953 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1954 u32 index, u64 data, bool host_initiated)
1955 {
1956 return kvm_do_msr_access(vcpu, index, &data, host_initiated, MSR_TYPE_W,
1957 _kvm_set_msr);
1958 }
1959
1960 /*
1961 * Read the MSR specified by @index into @data. Select MSR specific fault
1962 * checks are bypassed if @host_initiated is %true.
1963 * Returns 0 on success, non-0 otherwise.
1964 * Assumes vcpu_load() was already called.
1965 */
__kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1966 static int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1967 bool host_initiated)
1968 {
1969 struct msr_data msr;
1970 int ret;
1971
1972 switch (index) {
1973 case MSR_TSC_AUX:
1974 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1975 return 1;
1976
1977 if (!host_initiated &&
1978 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1979 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1980 return 1;
1981 break;
1982 case MSR_IA32_U_CET:
1983 case MSR_IA32_S_CET:
1984 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
1985 !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT))
1986 return KVM_MSR_RET_UNSUPPORTED;
1987 break;
1988 case MSR_KVM_INTERNAL_GUEST_SSP:
1989 if (!host_initiated)
1990 return 1;
1991 fallthrough;
1992 case MSR_IA32_PL0_SSP ... MSR_IA32_INT_SSP_TAB:
1993 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
1994 return KVM_MSR_RET_UNSUPPORTED;
1995 break;
1996 }
1997
1998 msr.index = index;
1999 msr.host_initiated = host_initiated;
2000
2001 ret = kvm_x86_call(get_msr)(vcpu, &msr);
2002 if (!ret)
2003 *data = msr.data;
2004 return ret;
2005 }
2006
kvm_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2007 int kvm_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2008 {
2009 return __kvm_set_msr(vcpu, index, data, true);
2010 }
2011
kvm_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2012 int kvm_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2013 {
2014 return __kvm_get_msr(vcpu, index, data, true);
2015 }
2016
kvm_get_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)2017 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
2018 u32 index, u64 *data, bool host_initiated)
2019 {
2020 return kvm_do_msr_access(vcpu, index, data, host_initiated, MSR_TYPE_R,
2021 __kvm_get_msr);
2022 }
2023
__kvm_emulate_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2024 int __kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2025 {
2026 return kvm_get_msr_ignored_check(vcpu, index, data, false);
2027 }
2028 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_emulate_msr_read);
2029
__kvm_emulate_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2030 int __kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2031 {
2032 return kvm_set_msr_ignored_check(vcpu, index, data, false);
2033 }
2034 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_emulate_msr_write);
2035
kvm_emulate_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2036 int kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2037 {
2038 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
2039 return KVM_MSR_RET_FILTERED;
2040
2041 return __kvm_emulate_msr_read(vcpu, index, data);
2042 }
2043 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_read);
2044
kvm_emulate_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2045 int kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2046 {
2047 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
2048 return KVM_MSR_RET_FILTERED;
2049
2050 return __kvm_emulate_msr_write(vcpu, index, data);
2051 }
2052 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_write);
2053
2054
complete_userspace_rdmsr(struct kvm_vcpu * vcpu)2055 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
2056 {
2057 if (!vcpu->run->msr.error) {
2058 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
2059 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
2060 }
2061 }
2062
complete_emulated_msr_access(struct kvm_vcpu * vcpu)2063 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
2064 {
2065 return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
2066 }
2067
complete_emulated_rdmsr(struct kvm_vcpu * vcpu)2068 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
2069 {
2070 complete_userspace_rdmsr(vcpu);
2071 return complete_emulated_msr_access(vcpu);
2072 }
2073
complete_fast_msr_access(struct kvm_vcpu * vcpu)2074 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
2075 {
2076 return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
2077 }
2078
complete_fast_rdmsr(struct kvm_vcpu * vcpu)2079 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
2080 {
2081 complete_userspace_rdmsr(vcpu);
2082 return complete_fast_msr_access(vcpu);
2083 }
2084
complete_fast_rdmsr_imm(struct kvm_vcpu * vcpu)2085 static int complete_fast_rdmsr_imm(struct kvm_vcpu *vcpu)
2086 {
2087 if (!vcpu->run->msr.error)
2088 kvm_register_write(vcpu, vcpu->arch.cui_rdmsr_imm_reg,
2089 vcpu->run->msr.data);
2090
2091 return complete_fast_msr_access(vcpu);
2092 }
2093
kvm_msr_reason(int r)2094 static u64 kvm_msr_reason(int r)
2095 {
2096 switch (r) {
2097 case KVM_MSR_RET_UNSUPPORTED:
2098 return KVM_MSR_EXIT_REASON_UNKNOWN;
2099 case KVM_MSR_RET_FILTERED:
2100 return KVM_MSR_EXIT_REASON_FILTER;
2101 default:
2102 return KVM_MSR_EXIT_REASON_INVAL;
2103 }
2104 }
2105
kvm_msr_user_space(struct kvm_vcpu * vcpu,u32 index,u32 exit_reason,u64 data,int (* completion)(struct kvm_vcpu * vcpu),int r)2106 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
2107 u32 exit_reason, u64 data,
2108 int (*completion)(struct kvm_vcpu *vcpu),
2109 int r)
2110 {
2111 u64 msr_reason = kvm_msr_reason(r);
2112
2113 /* Check if the user wanted to know about this MSR fault */
2114 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2115 return 0;
2116
2117 vcpu->run->exit_reason = exit_reason;
2118 vcpu->run->msr.error = 0;
2119 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2120 vcpu->run->msr.reason = msr_reason;
2121 vcpu->run->msr.index = index;
2122 vcpu->run->msr.data = data;
2123 vcpu->arch.complete_userspace_io = completion;
2124
2125 return 1;
2126 }
2127
__kvm_emulate_rdmsr(struct kvm_vcpu * vcpu,u32 msr,int reg,int (* complete_rdmsr)(struct kvm_vcpu *))2128 static int __kvm_emulate_rdmsr(struct kvm_vcpu *vcpu, u32 msr, int reg,
2129 int (*complete_rdmsr)(struct kvm_vcpu *))
2130 {
2131 u64 data;
2132 int r;
2133
2134 r = kvm_emulate_msr_read(vcpu, msr, &data);
2135
2136 if (!r) {
2137 trace_kvm_msr_read(msr, data);
2138
2139 if (reg < 0) {
2140 kvm_rax_write(vcpu, data & -1u);
2141 kvm_rdx_write(vcpu, (data >> 32) & -1u);
2142 } else {
2143 kvm_register_write(vcpu, reg, data);
2144 }
2145 } else {
2146 /* MSR read failed? See if we should ask user space */
2147 if (kvm_msr_user_space(vcpu, msr, KVM_EXIT_X86_RDMSR, 0,
2148 complete_rdmsr, r))
2149 return 0;
2150 trace_kvm_msr_read_ex(msr);
2151 }
2152
2153 return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2154 }
2155
kvm_emulate_rdmsr(struct kvm_vcpu * vcpu)2156 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2157 {
2158 return __kvm_emulate_rdmsr(vcpu, kvm_rcx_read(vcpu), -1,
2159 complete_fast_rdmsr);
2160 }
2161 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdmsr);
2162
kvm_emulate_rdmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2163 int kvm_emulate_rdmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2164 {
2165 vcpu->arch.cui_rdmsr_imm_reg = reg;
2166
2167 return __kvm_emulate_rdmsr(vcpu, msr, reg, complete_fast_rdmsr_imm);
2168 }
2169 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdmsr_imm);
2170
__kvm_emulate_wrmsr(struct kvm_vcpu * vcpu,u32 msr,u64 data)2171 static int __kvm_emulate_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2172 {
2173 int r;
2174
2175 r = kvm_emulate_msr_write(vcpu, msr, data);
2176 if (!r) {
2177 trace_kvm_msr_write(msr, data);
2178 } else {
2179 /* MSR write failed? See if we should ask user space */
2180 if (kvm_msr_user_space(vcpu, msr, KVM_EXIT_X86_WRMSR, data,
2181 complete_fast_msr_access, r))
2182 return 0;
2183 /* Signal all other negative errors to userspace */
2184 if (r < 0)
2185 return r;
2186 trace_kvm_msr_write_ex(msr, data);
2187 }
2188
2189 return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2190 }
2191
kvm_emulate_wrmsr(struct kvm_vcpu * vcpu)2192 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2193 {
2194 return __kvm_emulate_wrmsr(vcpu, kvm_rcx_read(vcpu),
2195 kvm_read_edx_eax(vcpu));
2196 }
2197 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wrmsr);
2198
kvm_emulate_wrmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2199 int kvm_emulate_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2200 {
2201 return __kvm_emulate_wrmsr(vcpu, msr, kvm_register_read(vcpu, reg));
2202 }
2203 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wrmsr_imm);
2204
kvm_emulate_as_nop(struct kvm_vcpu * vcpu)2205 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2206 {
2207 return kvm_skip_emulated_instruction(vcpu);
2208 }
2209
kvm_emulate_invd(struct kvm_vcpu * vcpu)2210 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2211 {
2212 /* Treat an INVD instruction as a NOP and just skip it. */
2213 return kvm_emulate_as_nop(vcpu);
2214 }
2215 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_invd);
2216
handle_fastpath_invd(struct kvm_vcpu * vcpu)2217 fastpath_t handle_fastpath_invd(struct kvm_vcpu *vcpu)
2218 {
2219 if (!kvm_emulate_invd(vcpu))
2220 return EXIT_FASTPATH_EXIT_USERSPACE;
2221
2222 return EXIT_FASTPATH_REENTER_GUEST;
2223 }
2224 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_invd);
2225
kvm_handle_invalid_op(struct kvm_vcpu * vcpu)2226 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2227 {
2228 kvm_queue_exception(vcpu, UD_VECTOR);
2229 return 1;
2230 }
2231 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invalid_op);
2232
2233
kvm_emulate_monitor_mwait(struct kvm_vcpu * vcpu,const char * insn)2234 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2235 {
2236 bool enabled;
2237
2238 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS))
2239 goto emulate_as_nop;
2240
2241 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
2242 enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_MWAIT);
2243 else
2244 enabled = vcpu->arch.ia32_misc_enable_msr & MSR_IA32_MISC_ENABLE_MWAIT;
2245
2246 if (!enabled)
2247 return kvm_handle_invalid_op(vcpu);
2248
2249 emulate_as_nop:
2250 pr_warn_once("%s instruction emulated as NOP!\n", insn);
2251 return kvm_emulate_as_nop(vcpu);
2252 }
kvm_emulate_mwait(struct kvm_vcpu * vcpu)2253 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2254 {
2255 return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2256 }
2257 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_mwait);
2258
kvm_emulate_monitor(struct kvm_vcpu * vcpu)2259 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2260 {
2261 return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2262 }
2263 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_monitor);
2264
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu)2265 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2266 {
2267 xfer_to_guest_mode_prepare();
2268
2269 return READ_ONCE(vcpu->mode) == EXITING_GUEST_MODE ||
2270 kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending();
2271 }
2272
__handle_fastpath_wrmsr(struct kvm_vcpu * vcpu,u32 msr,u64 data)2273 static fastpath_t __handle_fastpath_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2274 {
2275 switch (msr) {
2276 case APIC_BASE_MSR + (APIC_ICR >> 4):
2277 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic) ||
2278 kvm_x2apic_icr_write_fast(vcpu->arch.apic, data))
2279 return EXIT_FASTPATH_NONE;
2280 break;
2281 case MSR_IA32_TSC_DEADLINE:
2282 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2283 break;
2284 default:
2285 return EXIT_FASTPATH_NONE;
2286 }
2287
2288 trace_kvm_msr_write(msr, data);
2289
2290 if (!kvm_skip_emulated_instruction(vcpu))
2291 return EXIT_FASTPATH_EXIT_USERSPACE;
2292
2293 return EXIT_FASTPATH_REENTER_GUEST;
2294 }
2295
handle_fastpath_wrmsr(struct kvm_vcpu * vcpu)2296 fastpath_t handle_fastpath_wrmsr(struct kvm_vcpu *vcpu)
2297 {
2298 return __handle_fastpath_wrmsr(vcpu, kvm_rcx_read(vcpu),
2299 kvm_read_edx_eax(vcpu));
2300 }
2301 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr);
2302
handle_fastpath_wrmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2303 fastpath_t handle_fastpath_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2304 {
2305 return __handle_fastpath_wrmsr(vcpu, msr, kvm_register_read(vcpu, reg));
2306 }
2307 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr_imm);
2308
2309 /*
2310 * Adapt set_msr() to msr_io()'s calling convention
2311 */
do_get_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2312 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2313 {
2314 return kvm_get_msr_ignored_check(vcpu, index, data, true);
2315 }
2316
do_set_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2317 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2318 {
2319 u64 val;
2320
2321 /*
2322 * Disallow writes to immutable feature MSRs after KVM_RUN. KVM does
2323 * not support modifying the guest vCPU model on the fly, e.g. changing
2324 * the nVMX capabilities while L2 is running is nonsensical. Allow
2325 * writes of the same value, e.g. to allow userspace to blindly stuff
2326 * all MSRs when emulating RESET.
2327 */
2328 if (kvm_vcpu_has_run(vcpu) && kvm_is_immutable_feature_msr(index) &&
2329 (do_get_msr(vcpu, index, &val) || *data != val))
2330 return -EINVAL;
2331
2332 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2333 }
2334
2335 #ifdef CONFIG_X86_64
2336 struct pvclock_clock {
2337 int vclock_mode;
2338 u64 cycle_last;
2339 u64 mask;
2340 u32 mult;
2341 u32 shift;
2342 u64 base_cycles;
2343 u64 offset;
2344 };
2345
2346 struct pvclock_gtod_data {
2347 seqcount_t seq;
2348
2349 struct pvclock_clock clock; /* extract of a clocksource struct */
2350 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2351
2352 ktime_t offs_boot;
2353 u64 wall_time_sec;
2354 };
2355
2356 static struct pvclock_gtod_data pvclock_gtod_data;
2357
update_pvclock_gtod(struct timekeeper * tk)2358 static void update_pvclock_gtod(struct timekeeper *tk)
2359 {
2360 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2361
2362 write_seqcount_begin(&vdata->seq);
2363
2364 /* copy pvclock gtod data */
2365 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
2366 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
2367 vdata->clock.mask = tk->tkr_mono.mask;
2368 vdata->clock.mult = tk->tkr_mono.mult;
2369 vdata->clock.shift = tk->tkr_mono.shift;
2370 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
2371 vdata->clock.offset = tk->tkr_mono.base;
2372
2373 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
2374 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
2375 vdata->raw_clock.mask = tk->tkr_raw.mask;
2376 vdata->raw_clock.mult = tk->tkr_raw.mult;
2377 vdata->raw_clock.shift = tk->tkr_raw.shift;
2378 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
2379 vdata->raw_clock.offset = tk->tkr_raw.base;
2380
2381 vdata->wall_time_sec = tk->xtime_sec;
2382
2383 vdata->offs_boot = tk->offs_boot;
2384
2385 write_seqcount_end(&vdata->seq);
2386 }
2387
get_kvmclock_base_ns(void)2388 static s64 get_kvmclock_base_ns(void)
2389 {
2390 /* Count up from boot time, but with the frequency of the raw clock. */
2391 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2392 }
2393 #else
get_kvmclock_base_ns(void)2394 static s64 get_kvmclock_base_ns(void)
2395 {
2396 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
2397 return ktime_get_boottime_ns();
2398 }
2399 #endif
2400
kvm_write_wall_clock(struct kvm * kvm,gpa_t wall_clock,int sec_hi_ofs)2401 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2402 {
2403 int version;
2404 int r;
2405 struct pvclock_wall_clock wc;
2406 u32 wc_sec_hi;
2407 u64 wall_nsec;
2408
2409 if (!wall_clock)
2410 return;
2411
2412 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2413 if (r)
2414 return;
2415
2416 if (version & 1)
2417 ++version; /* first time write, random junk */
2418
2419 ++version;
2420
2421 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2422 return;
2423
2424 wall_nsec = kvm_get_wall_clock_epoch(kvm);
2425
2426 wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
2427 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2428 wc.version = version;
2429
2430 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2431
2432 if (sec_hi_ofs) {
2433 wc_sec_hi = wall_nsec >> 32;
2434 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2435 &wc_sec_hi, sizeof(wc_sec_hi));
2436 }
2437
2438 version++;
2439 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2440 }
2441
kvm_write_system_time(struct kvm_vcpu * vcpu,gpa_t system_time,bool old_msr,bool host_initiated)2442 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2443 bool old_msr, bool host_initiated)
2444 {
2445 struct kvm_arch *ka = &vcpu->kvm->arch;
2446
2447 if (vcpu->vcpu_id == 0 && !host_initiated) {
2448 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2449 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2450
2451 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2452 }
2453
2454 vcpu->arch.time = system_time;
2455 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2456
2457 /* we verify if the enable bit is set... */
2458 if (system_time & 1)
2459 kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
2460 sizeof(struct pvclock_vcpu_time_info));
2461 else
2462 kvm_gpc_deactivate(&vcpu->arch.pv_time);
2463
2464 return;
2465 }
2466
div_frac(uint32_t dividend,uint32_t divisor)2467 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2468 {
2469 do_shl32_div32(dividend, divisor);
2470 return dividend;
2471 }
2472
kvm_get_time_scale(uint64_t scaled_hz,uint64_t base_hz,s8 * pshift,u32 * pmultiplier)2473 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2474 s8 *pshift, u32 *pmultiplier)
2475 {
2476 uint64_t scaled64;
2477 int32_t shift = 0;
2478 uint64_t tps64;
2479 uint32_t tps32;
2480
2481 tps64 = base_hz;
2482 scaled64 = scaled_hz;
2483 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2484 tps64 >>= 1;
2485 shift--;
2486 }
2487
2488 tps32 = (uint32_t)tps64;
2489 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2490 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2491 scaled64 >>= 1;
2492 else
2493 tps32 <<= 1;
2494 shift++;
2495 }
2496
2497 *pshift = shift;
2498 *pmultiplier = div_frac(scaled64, tps32);
2499 }
2500
2501 #ifdef CONFIG_X86_64
2502 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2503 #endif
2504
2505 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2506 static unsigned long max_tsc_khz;
2507
adjust_tsc_khz(u32 khz,s32 ppm)2508 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2509 {
2510 u64 v = (u64)khz * (1000000 + ppm);
2511 do_div(v, 1000000);
2512 return v;
2513 }
2514
2515 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2516
set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz,bool scale)2517 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2518 {
2519 u64 ratio;
2520
2521 /* Guest TSC same frequency as host TSC? */
2522 if (!scale) {
2523 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2524 return 0;
2525 }
2526
2527 /* TSC scaling supported? */
2528 if (!kvm_caps.has_tsc_control) {
2529 if (user_tsc_khz > tsc_khz) {
2530 vcpu->arch.tsc_catchup = 1;
2531 vcpu->arch.tsc_always_catchup = 1;
2532 return 0;
2533 } else {
2534 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2535 return -1;
2536 }
2537 }
2538
2539 /* TSC scaling required - calculate ratio */
2540 ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2541 user_tsc_khz, tsc_khz);
2542
2543 if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2544 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2545 user_tsc_khz);
2546 return -1;
2547 }
2548
2549 kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2550 return 0;
2551 }
2552
kvm_set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz)2553 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2554 {
2555 u32 thresh_lo, thresh_hi;
2556 int use_scaling = 0;
2557
2558 /* tsc_khz can be zero if TSC calibration fails */
2559 if (user_tsc_khz == 0) {
2560 /* set tsc_scaling_ratio to a safe value */
2561 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2562 return -1;
2563 }
2564
2565 /* Compute a scale to convert nanoseconds in TSC cycles */
2566 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2567 &vcpu->arch.virtual_tsc_shift,
2568 &vcpu->arch.virtual_tsc_mult);
2569 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2570
2571 /*
2572 * Compute the variation in TSC rate which is acceptable
2573 * within the range of tolerance and decide if the
2574 * rate being applied is within that bounds of the hardware
2575 * rate. If so, no scaling or compensation need be done.
2576 */
2577 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2578 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2579 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2580 pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2581 user_tsc_khz, thresh_lo, thresh_hi);
2582 use_scaling = 1;
2583 }
2584 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2585 }
2586
compute_guest_tsc(struct kvm_vcpu * vcpu,s64 kernel_ns)2587 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2588 {
2589 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2590 vcpu->arch.virtual_tsc_mult,
2591 vcpu->arch.virtual_tsc_shift);
2592 tsc += vcpu->arch.this_tsc_write;
2593 return tsc;
2594 }
2595
2596 #ifdef CONFIG_X86_64
gtod_is_based_on_tsc(int mode)2597 static inline bool gtod_is_based_on_tsc(int mode)
2598 {
2599 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2600 }
2601 #endif
2602
kvm_track_tsc_matching(struct kvm_vcpu * vcpu,bool new_generation)2603 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
2604 {
2605 #ifdef CONFIG_X86_64
2606 struct kvm_arch *ka = &vcpu->kvm->arch;
2607 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2608
2609 /*
2610 * To use the masterclock, the host clocksource must be based on TSC
2611 * and all vCPUs must have matching TSCs. Note, the count for matching
2612 * vCPUs doesn't include the reference vCPU, hence "+1".
2613 */
2614 bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2615 atomic_read(&vcpu->kvm->online_vcpus)) &&
2616 gtod_is_based_on_tsc(gtod->clock.vclock_mode);
2617
2618 /*
2619 * Request a masterclock update if the masterclock needs to be toggled
2620 * on/off, or when starting a new generation and the masterclock is
2621 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2622 * taken _after_ the new generation is created).
2623 */
2624 if ((ka->use_master_clock && new_generation) ||
2625 (ka->use_master_clock != use_master_clock))
2626 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2627
2628 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2629 atomic_read(&vcpu->kvm->online_vcpus),
2630 ka->use_master_clock, gtod->clock.vclock_mode);
2631 #endif
2632 }
2633
2634 /*
2635 * Multiply tsc by a fixed point number represented by ratio.
2636 *
2637 * The most significant 64-N bits (mult) of ratio represent the
2638 * integral part of the fixed point number; the remaining N bits
2639 * (frac) represent the fractional part, ie. ratio represents a fixed
2640 * point number (mult + frac * 2^(-N)).
2641 *
2642 * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2643 */
__scale_tsc(u64 ratio,u64 tsc)2644 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2645 {
2646 return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2647 }
2648
kvm_scale_tsc(u64 tsc,u64 ratio)2649 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2650 {
2651 u64 _tsc = tsc;
2652
2653 if (ratio != kvm_caps.default_tsc_scaling_ratio)
2654 _tsc = __scale_tsc(ratio, tsc);
2655
2656 return _tsc;
2657 }
2658
kvm_compute_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 target_tsc)2659 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2660 {
2661 u64 tsc;
2662
2663 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2664
2665 return target_tsc - tsc;
2666 }
2667
kvm_read_l1_tsc(struct kvm_vcpu * vcpu,u64 host_tsc)2668 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2669 {
2670 return vcpu->arch.l1_tsc_offset +
2671 kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2672 }
2673 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_l1_tsc);
2674
kvm_calc_nested_tsc_offset(u64 l1_offset,u64 l2_offset,u64 l2_multiplier)2675 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2676 {
2677 u64 nested_offset;
2678
2679 if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2680 nested_offset = l1_offset;
2681 else
2682 nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2683 kvm_caps.tsc_scaling_ratio_frac_bits);
2684
2685 nested_offset += l2_offset;
2686 return nested_offset;
2687 }
2688 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_offset);
2689
kvm_calc_nested_tsc_multiplier(u64 l1_multiplier,u64 l2_multiplier)2690 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2691 {
2692 if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2693 return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2694 kvm_caps.tsc_scaling_ratio_frac_bits);
2695
2696 return l1_multiplier;
2697 }
2698 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_multiplier);
2699
kvm_vcpu_write_tsc_offset(struct kvm_vcpu * vcpu,u64 l1_offset)2700 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2701 {
2702 if (vcpu->arch.guest_tsc_protected)
2703 return;
2704
2705 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2706 vcpu->arch.l1_tsc_offset,
2707 l1_offset);
2708
2709 vcpu->arch.l1_tsc_offset = l1_offset;
2710
2711 /*
2712 * If we are here because L1 chose not to trap WRMSR to TSC then
2713 * according to the spec this should set L1's TSC (as opposed to
2714 * setting L1's offset for L2).
2715 */
2716 if (is_guest_mode(vcpu))
2717 vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2718 l1_offset,
2719 kvm_x86_call(get_l2_tsc_offset)(vcpu),
2720 kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2721 else
2722 vcpu->arch.tsc_offset = l1_offset;
2723
2724 kvm_x86_call(write_tsc_offset)(vcpu);
2725 }
2726
kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu * vcpu,u64 l1_multiplier)2727 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2728 {
2729 vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2730
2731 /* Userspace is changing the multiplier while L2 is active */
2732 if (is_guest_mode(vcpu))
2733 vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2734 l1_multiplier,
2735 kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2736 else
2737 vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2738
2739 if (kvm_caps.has_tsc_control)
2740 kvm_x86_call(write_tsc_multiplier)(vcpu);
2741 }
2742
kvm_check_tsc_unstable(void)2743 static inline bool kvm_check_tsc_unstable(void)
2744 {
2745 #ifdef CONFIG_X86_64
2746 /*
2747 * TSC is marked unstable when we're running on Hyper-V,
2748 * 'TSC page' clocksource is good.
2749 */
2750 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2751 return false;
2752 #endif
2753 return check_tsc_unstable();
2754 }
2755
2756 /*
2757 * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2758 * offset for the vcpu and tracks the TSC matching generation that the vcpu
2759 * participates in.
2760 */
__kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 offset,u64 tsc,u64 ns,bool matched,bool user_set_tsc)2761 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2762 u64 ns, bool matched, bool user_set_tsc)
2763 {
2764 struct kvm *kvm = vcpu->kvm;
2765
2766 lockdep_assert_held(&kvm->arch.tsc_write_lock);
2767
2768 if (vcpu->arch.guest_tsc_protected)
2769 return;
2770
2771 if (user_set_tsc)
2772 vcpu->kvm->arch.user_set_tsc = true;
2773
2774 /*
2775 * We also track th most recent recorded KHZ, write and time to
2776 * allow the matching interval to be extended at each write.
2777 */
2778 kvm->arch.last_tsc_nsec = ns;
2779 kvm->arch.last_tsc_write = tsc;
2780 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2781 kvm->arch.last_tsc_offset = offset;
2782
2783 vcpu->arch.last_guest_tsc = tsc;
2784
2785 kvm_vcpu_write_tsc_offset(vcpu, offset);
2786
2787 if (!matched) {
2788 /*
2789 * We split periods of matched TSC writes into generations.
2790 * For each generation, we track the original measured
2791 * nanosecond time, offset, and write, so if TSCs are in
2792 * sync, we can match exact offset, and if not, we can match
2793 * exact software computation in compute_guest_tsc()
2794 *
2795 * These values are tracked in kvm->arch.cur_xxx variables.
2796 */
2797 kvm->arch.cur_tsc_generation++;
2798 kvm->arch.cur_tsc_nsec = ns;
2799 kvm->arch.cur_tsc_write = tsc;
2800 kvm->arch.cur_tsc_offset = offset;
2801 kvm->arch.nr_vcpus_matched_tsc = 0;
2802 } else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2803 kvm->arch.nr_vcpus_matched_tsc++;
2804 }
2805
2806 /* Keep track of which generation this VCPU has synchronized to */
2807 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2808 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2809 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2810
2811 kvm_track_tsc_matching(vcpu, !matched);
2812 }
2813
kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 * user_value)2814 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
2815 {
2816 u64 data = user_value ? *user_value : 0;
2817 struct kvm *kvm = vcpu->kvm;
2818 u64 offset, ns, elapsed;
2819 unsigned long flags;
2820 bool matched = false;
2821 bool synchronizing = false;
2822
2823 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2824 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2825 ns = get_kvmclock_base_ns();
2826 elapsed = ns - kvm->arch.last_tsc_nsec;
2827
2828 if (vcpu->arch.virtual_tsc_khz) {
2829 if (data == 0) {
2830 /*
2831 * Force synchronization when creating a vCPU, or when
2832 * userspace explicitly writes a zero value.
2833 */
2834 synchronizing = true;
2835 } else if (kvm->arch.user_set_tsc) {
2836 u64 tsc_exp = kvm->arch.last_tsc_write +
2837 nsec_to_cycles(vcpu, elapsed);
2838 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2839 /*
2840 * Here lies UAPI baggage: when a user-initiated TSC write has
2841 * a small delta (1 second) of virtual cycle time against the
2842 * previously set vCPU, we assume that they were intended to be
2843 * in sync and the delta was only due to the racy nature of the
2844 * legacy API.
2845 *
2846 * This trick falls down when restoring a guest which genuinely
2847 * has been running for less time than the 1 second of imprecision
2848 * which we allow for in the legacy API. In this case, the first
2849 * value written by userspace (on any vCPU) should not be subject
2850 * to this 'correction' to make it sync up with values that only
2851 * come from the kernel's default vCPU creation. Make the 1-second
2852 * slop hack only trigger if the user_set_tsc flag is already set.
2853 */
2854 synchronizing = data < tsc_exp + tsc_hz &&
2855 data + tsc_hz > tsc_exp;
2856 }
2857 }
2858
2859
2860 /*
2861 * For a reliable TSC, we can match TSC offsets, and for an unstable
2862 * TSC, we add elapsed time in this computation. We could let the
2863 * compensation code attempt to catch up if we fall behind, but
2864 * it's better to try to match offsets from the beginning.
2865 */
2866 if (synchronizing &&
2867 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2868 if (!kvm_check_tsc_unstable()) {
2869 offset = kvm->arch.cur_tsc_offset;
2870 } else {
2871 u64 delta = nsec_to_cycles(vcpu, elapsed);
2872 data += delta;
2873 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2874 }
2875 matched = true;
2876 }
2877
2878 __kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value);
2879 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2880 }
2881
adjust_tsc_offset_guest(struct kvm_vcpu * vcpu,s64 adjustment)2882 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2883 s64 adjustment)
2884 {
2885 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2886 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2887 }
2888
adjust_tsc_offset_host(struct kvm_vcpu * vcpu,s64 adjustment)2889 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2890 {
2891 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2892 WARN_ON(adjustment < 0);
2893 adjustment = kvm_scale_tsc((u64) adjustment,
2894 vcpu->arch.l1_tsc_scaling_ratio);
2895 adjust_tsc_offset_guest(vcpu, adjustment);
2896 }
2897
2898 #ifdef CONFIG_X86_64
2899
read_tsc(void)2900 static u64 read_tsc(void)
2901 {
2902 u64 ret = (u64)rdtsc_ordered();
2903 u64 last = pvclock_gtod_data.clock.cycle_last;
2904
2905 if (likely(ret >= last))
2906 return ret;
2907
2908 /*
2909 * GCC likes to generate cmov here, but this branch is extremely
2910 * predictable (it's just a function of time and the likely is
2911 * very likely) and there's a data dependence, so force GCC
2912 * to generate a branch instead. I don't barrier() because
2913 * we don't actually need a barrier, and if this function
2914 * ever gets inlined it will generate worse code.
2915 */
2916 asm volatile ("");
2917 return last;
2918 }
2919
vgettsc(struct pvclock_clock * clock,u64 * tsc_timestamp,int * mode)2920 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2921 int *mode)
2922 {
2923 u64 tsc_pg_val;
2924 long v;
2925
2926 switch (clock->vclock_mode) {
2927 case VDSO_CLOCKMODE_HVCLOCK:
2928 if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2929 tsc_timestamp, &tsc_pg_val)) {
2930 /* TSC page valid */
2931 *mode = VDSO_CLOCKMODE_HVCLOCK;
2932 v = (tsc_pg_val - clock->cycle_last) &
2933 clock->mask;
2934 } else {
2935 /* TSC page invalid */
2936 *mode = VDSO_CLOCKMODE_NONE;
2937 }
2938 break;
2939 case VDSO_CLOCKMODE_TSC:
2940 *mode = VDSO_CLOCKMODE_TSC;
2941 *tsc_timestamp = read_tsc();
2942 v = (*tsc_timestamp - clock->cycle_last) &
2943 clock->mask;
2944 break;
2945 default:
2946 *mode = VDSO_CLOCKMODE_NONE;
2947 }
2948
2949 if (*mode == VDSO_CLOCKMODE_NONE)
2950 *tsc_timestamp = v = 0;
2951
2952 return v * clock->mult;
2953 }
2954
2955 /*
2956 * As with get_kvmclock_base_ns(), this counts from boot time, at the
2957 * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2958 */
do_kvmclock_base(s64 * t,u64 * tsc_timestamp)2959 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
2960 {
2961 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2962 unsigned long seq;
2963 int mode;
2964 u64 ns;
2965
2966 do {
2967 seq = read_seqcount_begin(>od->seq);
2968 ns = gtod->raw_clock.base_cycles;
2969 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2970 ns >>= gtod->raw_clock.shift;
2971 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2972 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2973 *t = ns;
2974
2975 return mode;
2976 }
2977
2978 /*
2979 * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2980 * no boot time offset.
2981 */
do_monotonic(s64 * t,u64 * tsc_timestamp)2982 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2983 {
2984 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2985 unsigned long seq;
2986 int mode;
2987 u64 ns;
2988
2989 do {
2990 seq = read_seqcount_begin(>od->seq);
2991 ns = gtod->clock.base_cycles;
2992 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2993 ns >>= gtod->clock.shift;
2994 ns += ktime_to_ns(gtod->clock.offset);
2995 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2996 *t = ns;
2997
2998 return mode;
2999 }
3000
do_realtime(struct timespec64 * ts,u64 * tsc_timestamp)3001 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
3002 {
3003 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
3004 unsigned long seq;
3005 int mode;
3006 u64 ns;
3007
3008 do {
3009 seq = read_seqcount_begin(>od->seq);
3010 ts->tv_sec = gtod->wall_time_sec;
3011 ns = gtod->clock.base_cycles;
3012 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
3013 ns >>= gtod->clock.shift;
3014 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
3015
3016 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
3017 ts->tv_nsec = ns;
3018
3019 return mode;
3020 }
3021
3022 /*
3023 * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
3024 * reports the TSC value from which it do so. Returns true if host is
3025 * using TSC based clocksource.
3026 */
kvm_get_time_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)3027 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
3028 {
3029 /* checked again under seqlock below */
3030 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3031 return false;
3032
3033 return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
3034 tsc_timestamp));
3035 }
3036
3037 /*
3038 * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
3039 * so. Returns true if host is using TSC based clocksource.
3040 */
kvm_get_monotonic_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)3041 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
3042 {
3043 /* checked again under seqlock below */
3044 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3045 return false;
3046
3047 return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
3048 tsc_timestamp));
3049 }
3050
3051 /*
3052 * Calculates CLOCK_REALTIME and reports the TSC value from which it did
3053 * so. Returns true if host is using TSC based clocksource.
3054 *
3055 * DO NOT USE this for anything related to migration. You want CLOCK_TAI
3056 * for that.
3057 */
kvm_get_walltime_and_clockread(struct timespec64 * ts,u64 * tsc_timestamp)3058 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
3059 u64 *tsc_timestamp)
3060 {
3061 /* checked again under seqlock below */
3062 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3063 return false;
3064
3065 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
3066 }
3067 #endif
3068
3069 /*
3070 *
3071 * Assuming a stable TSC across physical CPUS, and a stable TSC
3072 * across virtual CPUs, the following condition is possible.
3073 * Each numbered line represents an event visible to both
3074 * CPUs at the next numbered event.
3075 *
3076 * "timespecX" represents host monotonic time. "tscX" represents
3077 * RDTSC value.
3078 *
3079 * VCPU0 on CPU0 | VCPU1 on CPU1
3080 *
3081 * 1. read timespec0,tsc0
3082 * 2. | timespec1 = timespec0 + N
3083 * | tsc1 = tsc0 + M
3084 * 3. transition to guest | transition to guest
3085 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
3086 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
3087 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
3088 *
3089 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
3090 *
3091 * - ret0 < ret1
3092 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
3093 * ...
3094 * - 0 < N - M => M < N
3095 *
3096 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
3097 * always the case (the difference between two distinct xtime instances
3098 * might be smaller then the difference between corresponding TSC reads,
3099 * when updating guest vcpus pvclock areas).
3100 *
3101 * To avoid that problem, do not allow visibility of distinct
3102 * system_timestamp/tsc_timestamp values simultaneously: use a master
3103 * copy of host monotonic time values. Update that master copy
3104 * in lockstep.
3105 *
3106 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
3107 *
3108 */
3109
pvclock_update_vm_gtod_copy(struct kvm * kvm)3110 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
3111 {
3112 #ifdef CONFIG_X86_64
3113 struct kvm_arch *ka = &kvm->arch;
3114 int vclock_mode;
3115 bool host_tsc_clocksource, vcpus_matched;
3116
3117 lockdep_assert_held(&kvm->arch.tsc_write_lock);
3118 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
3119 atomic_read(&kvm->online_vcpus));
3120
3121 /*
3122 * If the host uses TSC clock, then passthrough TSC as stable
3123 * to the guest.
3124 */
3125 host_tsc_clocksource = kvm_get_time_and_clockread(
3126 &ka->master_kernel_ns,
3127 &ka->master_cycle_now);
3128
3129 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
3130 && !ka->backwards_tsc_observed
3131 && !ka->boot_vcpu_runs_old_kvmclock;
3132
3133 if (ka->use_master_clock)
3134 atomic_set(&kvm_guest_has_master_clock, 1);
3135
3136 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
3137 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3138 vcpus_matched);
3139 #endif
3140 }
3141
kvm_make_mclock_inprogress_request(struct kvm * kvm)3142 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
3143 {
3144 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3145 }
3146
__kvm_start_pvclock_update(struct kvm * kvm)3147 static void __kvm_start_pvclock_update(struct kvm *kvm)
3148 {
3149 raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3150 write_seqcount_begin(&kvm->arch.pvclock_sc);
3151 }
3152
kvm_start_pvclock_update(struct kvm * kvm)3153 static void kvm_start_pvclock_update(struct kvm *kvm)
3154 {
3155 kvm_make_mclock_inprogress_request(kvm);
3156
3157 /* no guest entries from this point */
3158 __kvm_start_pvclock_update(kvm);
3159 }
3160
kvm_end_pvclock_update(struct kvm * kvm)3161 static void kvm_end_pvclock_update(struct kvm *kvm)
3162 {
3163 struct kvm_arch *ka = &kvm->arch;
3164 struct kvm_vcpu *vcpu;
3165 unsigned long i;
3166
3167 write_seqcount_end(&ka->pvclock_sc);
3168 raw_spin_unlock_irq(&ka->tsc_write_lock);
3169 kvm_for_each_vcpu(i, vcpu, kvm)
3170 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3171
3172 /* guest entries allowed */
3173 kvm_for_each_vcpu(i, vcpu, kvm)
3174 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
3175 }
3176
kvm_update_masterclock(struct kvm * kvm)3177 static void kvm_update_masterclock(struct kvm *kvm)
3178 {
3179 kvm_hv_request_tsc_page_update(kvm);
3180 kvm_start_pvclock_update(kvm);
3181 pvclock_update_vm_gtod_copy(kvm);
3182 kvm_end_pvclock_update(kvm);
3183 }
3184
3185 /*
3186 * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3187 * per-CPU value (which may be zero if a CPU is going offline). Note, tsc_khz
3188 * can change during boot even if the TSC is constant, as it's possible for KVM
3189 * to be loaded before TSC calibration completes. Ideally, KVM would get a
3190 * notification when calibration completes, but practically speaking calibration
3191 * will complete before userspace is alive enough to create VMs.
3192 */
get_cpu_tsc_khz(void)3193 static unsigned long get_cpu_tsc_khz(void)
3194 {
3195 if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3196 return tsc_khz;
3197 else
3198 return __this_cpu_read(cpu_tsc_khz);
3199 }
3200
3201 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc. */
__get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3202 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3203 {
3204 struct kvm_arch *ka = &kvm->arch;
3205 struct pvclock_vcpu_time_info hv_clock;
3206
3207 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
3208 get_cpu();
3209
3210 data->flags = 0;
3211 if (ka->use_master_clock &&
3212 (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
3213 #ifdef CONFIG_X86_64
3214 struct timespec64 ts;
3215
3216 if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3217 data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3218 data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3219 } else
3220 #endif
3221 data->host_tsc = rdtsc();
3222
3223 data->flags |= KVM_CLOCK_TSC_STABLE;
3224 hv_clock.tsc_timestamp = ka->master_cycle_now;
3225 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3226 kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
3227 &hv_clock.tsc_shift,
3228 &hv_clock.tsc_to_system_mul);
3229 data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3230 } else {
3231 data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3232 }
3233
3234 put_cpu();
3235 }
3236
get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3237 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3238 {
3239 struct kvm_arch *ka = &kvm->arch;
3240 unsigned seq;
3241
3242 do {
3243 seq = read_seqcount_begin(&ka->pvclock_sc);
3244 __get_kvmclock(kvm, data);
3245 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3246 }
3247
get_kvmclock_ns(struct kvm * kvm)3248 u64 get_kvmclock_ns(struct kvm *kvm)
3249 {
3250 struct kvm_clock_data data;
3251
3252 get_kvmclock(kvm, &data);
3253 return data.clock;
3254 }
3255
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)3256 static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
3257 struct kvm_vcpu *vcpu,
3258 struct gfn_to_pfn_cache *gpc,
3259 unsigned int offset)
3260 {
3261 struct pvclock_vcpu_time_info *guest_hv_clock;
3262 struct pvclock_vcpu_time_info hv_clock;
3263 unsigned long flags;
3264
3265 memcpy(&hv_clock, ref_hv_clock, sizeof(hv_clock));
3266
3267 read_lock_irqsave(&gpc->lock, flags);
3268 while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
3269 read_unlock_irqrestore(&gpc->lock, flags);
3270
3271 if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
3272 return;
3273
3274 read_lock_irqsave(&gpc->lock, flags);
3275 }
3276
3277 guest_hv_clock = (void *)(gpc->khva + offset);
3278
3279 /*
3280 * This VCPU is paused, but it's legal for a guest to read another
3281 * VCPU's kvmclock, so we really have to follow the specification where
3282 * it says that version is odd if data is being modified, and even after
3283 * it is consistent.
3284 */
3285
3286 guest_hv_clock->version = hv_clock.version = (guest_hv_clock->version + 1) | 1;
3287 smp_wmb();
3288
3289 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3290 hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3291
3292 memcpy(guest_hv_clock, &hv_clock, sizeof(*guest_hv_clock));
3293
3294 smp_wmb();
3295
3296 guest_hv_clock->version = ++hv_clock.version;
3297
3298 kvm_gpc_mark_dirty_in_slot(gpc);
3299 read_unlock_irqrestore(&gpc->lock, flags);
3300
3301 trace_kvm_pvclock_update(vcpu->vcpu_id, &hv_clock);
3302 }
3303
kvm_guest_time_update(struct kvm_vcpu * v)3304 int kvm_guest_time_update(struct kvm_vcpu *v)
3305 {
3306 struct pvclock_vcpu_time_info hv_clock = {};
3307 unsigned long flags, tgt_tsc_khz;
3308 unsigned seq;
3309 struct kvm_vcpu_arch *vcpu = &v->arch;
3310 struct kvm_arch *ka = &v->kvm->arch;
3311 s64 kernel_ns;
3312 u64 tsc_timestamp, host_tsc;
3313 bool use_master_clock;
3314
3315 kernel_ns = 0;
3316 host_tsc = 0;
3317
3318 /*
3319 * If the host uses TSC clock, then passthrough TSC as stable
3320 * to the guest.
3321 */
3322 do {
3323 seq = read_seqcount_begin(&ka->pvclock_sc);
3324 use_master_clock = ka->use_master_clock;
3325 if (use_master_clock) {
3326 host_tsc = ka->master_cycle_now;
3327 kernel_ns = ka->master_kernel_ns;
3328 }
3329 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3330
3331 /* Keep irq disabled to prevent changes to the clock */
3332 local_irq_save(flags);
3333 tgt_tsc_khz = get_cpu_tsc_khz();
3334 if (unlikely(tgt_tsc_khz == 0)) {
3335 local_irq_restore(flags);
3336 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3337 return 1;
3338 }
3339 if (!use_master_clock) {
3340 host_tsc = rdtsc();
3341 kernel_ns = get_kvmclock_base_ns();
3342 }
3343
3344 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3345
3346 /*
3347 * We may have to catch up the TSC to match elapsed wall clock
3348 * time for two reasons, even if kvmclock is used.
3349 * 1) CPU could have been running below the maximum TSC rate
3350 * 2) Broken TSC compensation resets the base at each VCPU
3351 * entry to avoid unknown leaps of TSC even when running
3352 * again on the same CPU. This may cause apparent elapsed
3353 * time to disappear, and the guest to stand still or run
3354 * very slowly.
3355 */
3356 if (vcpu->tsc_catchup) {
3357 u64 tsc = compute_guest_tsc(v, kernel_ns);
3358 if (tsc > tsc_timestamp) {
3359 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3360 tsc_timestamp = tsc;
3361 }
3362 }
3363
3364 local_irq_restore(flags);
3365
3366 /* With all the info we got, fill in the values */
3367
3368 if (kvm_caps.has_tsc_control) {
3369 tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3370 v->arch.l1_tsc_scaling_ratio);
3371 tgt_tsc_khz = tgt_tsc_khz ? : 1;
3372 }
3373
3374 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3375 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3376 &vcpu->pvclock_tsc_shift,
3377 &vcpu->pvclock_tsc_mul);
3378 vcpu->hw_tsc_khz = tgt_tsc_khz;
3379 }
3380
3381 hv_clock.tsc_shift = vcpu->pvclock_tsc_shift;
3382 hv_clock.tsc_to_system_mul = vcpu->pvclock_tsc_mul;
3383 hv_clock.tsc_timestamp = tsc_timestamp;
3384 hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3385 vcpu->last_guest_tsc = tsc_timestamp;
3386
3387 /* If the host uses TSC clocksource, then it is stable */
3388 hv_clock.flags = 0;
3389 if (use_master_clock)
3390 hv_clock.flags |= PVCLOCK_TSC_STABLE_BIT;
3391
3392 if (vcpu->pv_time.active) {
3393 /*
3394 * GUEST_STOPPED is only supported by kvmclock, and KVM's
3395 * historic behavior is to only process the request if kvmclock
3396 * is active/enabled.
3397 */
3398 if (vcpu->pvclock_set_guest_stopped_request) {
3399 hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3400 vcpu->pvclock_set_guest_stopped_request = false;
3401 }
3402 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->pv_time, 0);
3403
3404 hv_clock.flags &= ~PVCLOCK_GUEST_STOPPED;
3405 }
3406
3407 kvm_hv_setup_tsc_page(v->kvm, &hv_clock);
3408
3409 #ifdef CONFIG_KVM_XEN
3410 /*
3411 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3412 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3413 * This default behaviour led to bugs in some guest kernels which cause
3414 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3415 *
3416 * Note! Clear TSC_STABLE only for Xen clocks, i.e. the order matters!
3417 */
3418 if (ka->xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
3419 hv_clock.flags &= ~PVCLOCK_TSC_STABLE_BIT;
3420
3421 if (vcpu->xen.vcpu_info_cache.active)
3422 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_info_cache,
3423 offsetof(struct compat_vcpu_info, time));
3424 if (vcpu->xen.vcpu_time_info_cache.active)
3425 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_time_info_cache, 0);
3426 #endif
3427 return 0;
3428 }
3429
3430 /*
3431 * The pvclock_wall_clock ABI tells the guest the wall clock time at
3432 * which it started (i.e. its epoch, when its kvmclock was zero).
3433 *
3434 * In fact those clocks are subtly different; wall clock frequency is
3435 * adjusted by NTP and has leap seconds, while the kvmclock is a
3436 * simple function of the TSC without any such adjustment.
3437 *
3438 * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3439 * that and kvmclock, but even that would be subject to change over
3440 * time.
3441 *
3442 * Attempt to calculate the epoch at a given moment using the *same*
3443 * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3444 * wallclock and kvmclock times, and subtracting one from the other.
3445 *
3446 * Fall back to using their values at slightly different moments by
3447 * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3448 */
kvm_get_wall_clock_epoch(struct kvm * kvm)3449 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3450 {
3451 #ifdef CONFIG_X86_64
3452 struct pvclock_vcpu_time_info hv_clock;
3453 struct kvm_arch *ka = &kvm->arch;
3454 unsigned long seq, local_tsc_khz;
3455 struct timespec64 ts;
3456 uint64_t host_tsc;
3457
3458 do {
3459 seq = read_seqcount_begin(&ka->pvclock_sc);
3460
3461 local_tsc_khz = 0;
3462 if (!ka->use_master_clock)
3463 break;
3464
3465 /*
3466 * The TSC read and the call to get_cpu_tsc_khz() must happen
3467 * on the same CPU.
3468 */
3469 get_cpu();
3470
3471 local_tsc_khz = get_cpu_tsc_khz();
3472
3473 if (local_tsc_khz &&
3474 !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3475 local_tsc_khz = 0; /* Fall back to old method */
3476
3477 put_cpu();
3478
3479 /*
3480 * These values must be snapshotted within the seqcount loop.
3481 * After that, it's just mathematics which can happen on any
3482 * CPU at any time.
3483 */
3484 hv_clock.tsc_timestamp = ka->master_cycle_now;
3485 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3486
3487 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3488
3489 /*
3490 * If the conditions were right, and obtaining the wallclock+TSC was
3491 * successful, calculate the KVM clock at the corresponding time and
3492 * subtract one from the other to get the guest's epoch in nanoseconds
3493 * since 1970-01-01.
3494 */
3495 if (local_tsc_khz) {
3496 kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3497 &hv_clock.tsc_shift,
3498 &hv_clock.tsc_to_system_mul);
3499 return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3500 __pvclock_read_cycles(&hv_clock, host_tsc);
3501 }
3502 #endif
3503 return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3504 }
3505
3506 /*
3507 * kvmclock updates which are isolated to a given vcpu, such as
3508 * vcpu->cpu migration, should not allow system_timestamp from
3509 * the rest of the vcpus to remain static. Otherwise ntp frequency
3510 * correction applies to one vcpu's system_timestamp but not
3511 * the others.
3512 *
3513 * So in those cases, request a kvmclock update for all vcpus.
3514 * We need to rate-limit these requests though, as they can
3515 * considerably slow guests that have a large number of vcpus.
3516 * The time for a remote vcpu to update its kvmclock is bound
3517 * by the delay we use to rate-limit the updates.
3518 */
3519
3520 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3521
kvmclock_update_fn(struct work_struct * work)3522 static void kvmclock_update_fn(struct work_struct *work)
3523 {
3524 unsigned long i;
3525 struct delayed_work *dwork = to_delayed_work(work);
3526 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3527 kvmclock_update_work);
3528 struct kvm *kvm = container_of(ka, struct kvm, arch);
3529 struct kvm_vcpu *vcpu;
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
kvm_gen_kvmclock_update(struct kvm_vcpu * v)3537 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3538 {
3539 struct kvm *kvm = v->kvm;
3540
3541 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3542 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3543 KVMCLOCK_UPDATE_DELAY);
3544 }
3545
3546 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3547
kvmclock_sync_fn(struct work_struct * work)3548 static void kvmclock_sync_fn(struct work_struct *work)
3549 {
3550 struct delayed_work *dwork = to_delayed_work(work);
3551 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3552 kvmclock_sync_work);
3553 struct kvm *kvm = container_of(ka, struct kvm, arch);
3554
3555 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3556 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3557 KVMCLOCK_SYNC_PERIOD);
3558 }
3559
3560 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
is_mci_control_msr(u32 msr)3561 static bool is_mci_control_msr(u32 msr)
3562 {
3563 return (msr & 3) == 0;
3564 }
is_mci_status_msr(u32 msr)3565 static bool is_mci_status_msr(u32 msr)
3566 {
3567 return (msr & 3) == 1;
3568 }
3569
3570 /*
3571 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3572 */
can_set_mci_status(struct kvm_vcpu * vcpu)3573 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3574 {
3575 /* McStatusWrEn enabled? */
3576 if (guest_cpuid_is_amd_compatible(vcpu))
3577 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3578
3579 return false;
3580 }
3581
set_msr_mce(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3582 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3583 {
3584 u64 mcg_cap = vcpu->arch.mcg_cap;
3585 unsigned bank_num = mcg_cap & 0xff;
3586 u32 msr = msr_info->index;
3587 u64 data = msr_info->data;
3588 u32 offset, last_msr;
3589
3590 switch (msr) {
3591 case MSR_IA32_MCG_STATUS:
3592 vcpu->arch.mcg_status = data;
3593 break;
3594 case MSR_IA32_MCG_CTL:
3595 if (!(mcg_cap & MCG_CTL_P) &&
3596 (data || !msr_info->host_initiated))
3597 return 1;
3598 if (data != 0 && data != ~(u64)0)
3599 return 1;
3600 vcpu->arch.mcg_ctl = data;
3601 break;
3602 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3603 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3604 if (msr > last_msr)
3605 return 1;
3606
3607 if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3608 return 1;
3609 /* An attempt to write a 1 to a reserved bit raises #GP */
3610 if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3611 return 1;
3612 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3613 last_msr + 1 - MSR_IA32_MC0_CTL2);
3614 vcpu->arch.mci_ctl2_banks[offset] = data;
3615 break;
3616 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3617 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3618 if (msr > last_msr)
3619 return 1;
3620
3621 /*
3622 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3623 * values are architecturally undefined. But, some Linux
3624 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3625 * issue on AMD K8s, allow bit 10 to be clear when setting all
3626 * other bits in order to avoid an uncaught #GP in the guest.
3627 *
3628 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3629 * single-bit ECC data errors.
3630 */
3631 if (is_mci_control_msr(msr) &&
3632 data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3633 return 1;
3634
3635 /*
3636 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3637 * AMD-based CPUs allow non-zero values, but if and only if
3638 * HWCR[McStatusWrEn] is set.
3639 */
3640 if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3641 data != 0 && !can_set_mci_status(vcpu))
3642 return 1;
3643
3644 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3645 last_msr + 1 - MSR_IA32_MC0_CTL);
3646 vcpu->arch.mce_banks[offset] = data;
3647 break;
3648 default:
3649 return 1;
3650 }
3651 return 0;
3652 }
3653
kvm_pv_async_pf_enabled(struct kvm_vcpu * vcpu)3654 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3655 {
3656 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3657
3658 return (vcpu->arch.apf.msr_en_val & mask) == mask;
3659 }
3660
kvm_pv_enable_async_pf(struct kvm_vcpu * vcpu,u64 data)3661 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3662 {
3663 gpa_t gpa = data & ~0x3f;
3664
3665 /* Bits 4:5 are reserved, Should be zero */
3666 if (data & 0x30)
3667 return 1;
3668
3669 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3670 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3671 return 1;
3672
3673 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3674 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3675 return 1;
3676
3677 if (!lapic_in_kernel(vcpu))
3678 return data ? 1 : 0;
3679
3680 vcpu->arch.apf.msr_en_val = data;
3681
3682 if (!kvm_pv_async_pf_enabled(vcpu)) {
3683 kvm_clear_async_pf_completion_queue(vcpu);
3684 kvm_async_pf_hash_reset(vcpu);
3685 return 0;
3686 }
3687
3688 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3689 sizeof(u64)))
3690 return 1;
3691
3692 vcpu->arch.apf.send_always = (data & KVM_ASYNC_PF_SEND_ALWAYS);
3693 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3694
3695 kvm_async_pf_wakeup_all(vcpu);
3696
3697 return 0;
3698 }
3699
kvm_pv_enable_async_pf_int(struct kvm_vcpu * vcpu,u64 data)3700 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3701 {
3702 /* Bits 8-63 are reserved */
3703 if (data >> 8)
3704 return 1;
3705
3706 if (!lapic_in_kernel(vcpu))
3707 return 1;
3708
3709 vcpu->arch.apf.msr_int_val = data;
3710
3711 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3712
3713 return 0;
3714 }
3715
kvmclock_reset(struct kvm_vcpu * vcpu)3716 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3717 {
3718 kvm_gpc_deactivate(&vcpu->arch.pv_time);
3719 vcpu->arch.time = 0;
3720 }
3721
kvm_vcpu_flush_tlb_all(struct kvm_vcpu * vcpu)3722 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3723 {
3724 ++vcpu->stat.tlb_flush;
3725 kvm_x86_call(flush_tlb_all)(vcpu);
3726
3727 /* Flushing all ASIDs flushes the current ASID... */
3728 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3729 }
3730
kvm_vcpu_flush_tlb_guest(struct kvm_vcpu * vcpu)3731 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3732 {
3733 ++vcpu->stat.tlb_flush;
3734
3735 if (!tdp_enabled) {
3736 /*
3737 * A TLB flush on behalf of the guest is equivalent to
3738 * INVPCID(all), toggling CR4.PGE, etc., which requires
3739 * a forced sync of the shadow page tables. Ensure all the
3740 * roots are synced and the guest TLB in hardware is clean.
3741 */
3742 kvm_mmu_sync_roots(vcpu);
3743 kvm_mmu_sync_prev_roots(vcpu);
3744 }
3745
3746 kvm_x86_call(flush_tlb_guest)(vcpu);
3747
3748 /*
3749 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3750 * grained flushing.
3751 */
3752 kvm_hv_vcpu_purge_flush_tlb(vcpu);
3753 }
3754
3755
kvm_vcpu_flush_tlb_current(struct kvm_vcpu * vcpu)3756 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3757 {
3758 ++vcpu->stat.tlb_flush;
3759 kvm_x86_call(flush_tlb_current)(vcpu);
3760 }
3761
3762 /*
3763 * Service "local" TLB flush requests, which are specific to the current MMU
3764 * context. In addition to the generic event handling in vcpu_enter_guest(),
3765 * TLB flushes that are targeted at an MMU context also need to be serviced
3766 * prior before nested VM-Enter/VM-Exit.
3767 */
kvm_service_local_tlb_flush_requests(struct kvm_vcpu * vcpu)3768 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3769 {
3770 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3771 kvm_vcpu_flush_tlb_current(vcpu);
3772
3773 if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3774 kvm_vcpu_flush_tlb_guest(vcpu);
3775 }
3776 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_service_local_tlb_flush_requests);
3777
record_steal_time(struct kvm_vcpu * vcpu)3778 static void record_steal_time(struct kvm_vcpu *vcpu)
3779 {
3780 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3781 struct kvm_steal_time __user *st;
3782 struct kvm_memslots *slots;
3783 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3784 u64 steal;
3785 u32 version;
3786
3787 if (kvm_xen_msr_enabled(vcpu->kvm)) {
3788 kvm_xen_runstate_set_running(vcpu);
3789 return;
3790 }
3791
3792 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3793 return;
3794
3795 if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3796 return;
3797
3798 slots = kvm_memslots(vcpu->kvm);
3799
3800 if (unlikely(slots->generation != ghc->generation ||
3801 gpa != ghc->gpa ||
3802 kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3803 /* We rely on the fact that it fits in a single page. */
3804 BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3805
3806 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3807 kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3808 return;
3809 }
3810
3811 st = (struct kvm_steal_time __user *)ghc->hva;
3812 /*
3813 * Doing a TLB flush here, on the guest's behalf, can avoid
3814 * expensive IPIs.
3815 */
3816 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3817 u8 st_preempted = 0;
3818 int err = -EFAULT;
3819
3820 if (!user_access_begin(st, sizeof(*st)))
3821 return;
3822
3823 asm volatile("1: xchgb %0, %2\n"
3824 "xor %1, %1\n"
3825 "2:\n"
3826 _ASM_EXTABLE_UA(1b, 2b)
3827 : "+q" (st_preempted),
3828 "+&r" (err),
3829 "+m" (st->preempted));
3830 if (err)
3831 goto out;
3832
3833 user_access_end();
3834
3835 vcpu->arch.st.preempted = 0;
3836
3837 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3838 st_preempted & KVM_VCPU_FLUSH_TLB);
3839 if (st_preempted & KVM_VCPU_FLUSH_TLB)
3840 kvm_vcpu_flush_tlb_guest(vcpu);
3841
3842 if (!user_access_begin(st, sizeof(*st)))
3843 goto dirty;
3844 } else {
3845 if (!user_access_begin(st, sizeof(*st)))
3846 return;
3847
3848 unsafe_put_user(0, &st->preempted, out);
3849 vcpu->arch.st.preempted = 0;
3850 }
3851
3852 unsafe_get_user(version, &st->version, out);
3853 if (version & 1)
3854 version += 1; /* first time write, random junk */
3855
3856 version += 1;
3857 unsafe_put_user(version, &st->version, out);
3858
3859 smp_wmb();
3860
3861 unsafe_get_user(steal, &st->steal, out);
3862 steal += current->sched_info.run_delay -
3863 vcpu->arch.st.last_steal;
3864 vcpu->arch.st.last_steal = current->sched_info.run_delay;
3865 unsafe_put_user(steal, &st->steal, out);
3866
3867 version += 1;
3868 unsafe_put_user(version, &st->version, out);
3869
3870 out:
3871 user_access_end();
3872 dirty:
3873 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3874 }
3875
3876 /*
3877 * Returns true if the MSR in question is managed via XSTATE, i.e. is context
3878 * switched with the rest of guest FPU state. Note! S_CET is _not_ context
3879 * switched via XSTATE even though it _is_ saved/restored via XSAVES/XRSTORS.
3880 * Because S_CET is loaded on VM-Enter and VM-Exit via dedicated VMCS fields,
3881 * the value saved/restored via XSTATE is always the host's value. That detail
3882 * is _extremely_ important, as the guest's S_CET must _never_ be resident in
3883 * hardware while executing in the host. Loading guest values for U_CET and
3884 * PL[0-3]_SSP while executing in the kernel is safe, as U_CET is specific to
3885 * userspace, and PL[0-3]_SSP are only consumed when transitioning to lower
3886 * privilege levels, i.e. are effectively only consumed by userspace as well.
3887 */
is_xstate_managed_msr(struct kvm_vcpu * vcpu,u32 msr)3888 static bool is_xstate_managed_msr(struct kvm_vcpu *vcpu, u32 msr)
3889 {
3890 if (!vcpu)
3891 return false;
3892
3893 switch (msr) {
3894 case MSR_IA32_U_CET:
3895 return guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) ||
3896 guest_cpu_cap_has(vcpu, X86_FEATURE_IBT);
3897 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
3898 return guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK);
3899 default:
3900 return false;
3901 }
3902 }
3903
3904 /*
3905 * Lock (and if necessary, re-load) the guest FPU, i.e. XSTATE, and access an
3906 * MSR that is managed via XSTATE. Note, the caller is responsible for doing
3907 * the initial FPU load, this helper only ensures that guest state is resident
3908 * in hardware (the kernel can load its FPU state in IRQ context).
3909 */
kvm_access_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info,int access)3910 static __always_inline void kvm_access_xstate_msr(struct kvm_vcpu *vcpu,
3911 struct msr_data *msr_info,
3912 int access)
3913 {
3914 BUILD_BUG_ON(access != MSR_TYPE_R && access != MSR_TYPE_W);
3915
3916 KVM_BUG_ON(!is_xstate_managed_msr(vcpu, msr_info->index), vcpu->kvm);
3917 KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm);
3918
3919 kvm_fpu_get();
3920 if (access == MSR_TYPE_R)
3921 rdmsrq(msr_info->index, msr_info->data);
3922 else
3923 wrmsrq(msr_info->index, msr_info->data);
3924 kvm_fpu_put();
3925 }
3926
kvm_set_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3927 static void kvm_set_xstate_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3928 {
3929 kvm_access_xstate_msr(vcpu, msr_info, MSR_TYPE_W);
3930 }
3931
kvm_get_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3932 static void kvm_get_xstate_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3933 {
3934 kvm_access_xstate_msr(vcpu, msr_info, MSR_TYPE_R);
3935 }
3936
kvm_set_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3937 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3938 {
3939 u32 msr = msr_info->index;
3940 u64 data = msr_info->data;
3941
3942 /*
3943 * Do not allow host-initiated writes to trigger the Xen hypercall
3944 * page setup; it could incur locking paths which are not expected
3945 * if userspace sets the MSR in an unusual location.
3946 */
3947 if (kvm_xen_is_hypercall_page_msr(vcpu->kvm, msr) &&
3948 !msr_info->host_initiated)
3949 return kvm_xen_write_hypercall_page(vcpu, data);
3950
3951 switch (msr) {
3952 case MSR_AMD64_NB_CFG:
3953 case MSR_IA32_UCODE_WRITE:
3954 case MSR_VM_HSAVE_PA:
3955 case MSR_AMD64_PATCH_LOADER:
3956 case MSR_AMD64_BU_CFG2:
3957 case MSR_AMD64_DC_CFG:
3958 case MSR_AMD64_TW_CFG:
3959 case MSR_F15H_EX_CFG:
3960 break;
3961
3962 case MSR_IA32_UCODE_REV:
3963 if (msr_info->host_initiated)
3964 vcpu->arch.microcode_version = data;
3965 break;
3966 case MSR_IA32_ARCH_CAPABILITIES:
3967 if (!msr_info->host_initiated ||
3968 !guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3969 return KVM_MSR_RET_UNSUPPORTED;
3970 vcpu->arch.arch_capabilities = data;
3971 break;
3972 case MSR_IA32_PERF_CAPABILITIES:
3973 if (!msr_info->host_initiated ||
3974 !guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
3975 return KVM_MSR_RET_UNSUPPORTED;
3976
3977 if (data & ~kvm_caps.supported_perf_cap)
3978 return 1;
3979
3980 /*
3981 * Note, this is not just a performance optimization! KVM
3982 * disallows changing feature MSRs after the vCPU has run; PMU
3983 * refresh will bug the VM if called after the vCPU has run.
3984 */
3985 if (vcpu->arch.perf_capabilities == data)
3986 break;
3987
3988 vcpu->arch.perf_capabilities = data;
3989 kvm_pmu_refresh(vcpu);
3990 break;
3991 case MSR_IA32_PRED_CMD: {
3992 u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3993
3994 if (!msr_info->host_initiated) {
3995 if ((!guest_has_pred_cmd_msr(vcpu)))
3996 return 1;
3997
3998 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3999 !guest_cpu_cap_has(vcpu, X86_FEATURE_AMD_IBPB))
4000 reserved_bits |= PRED_CMD_IBPB;
4001
4002 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SBPB))
4003 reserved_bits |= PRED_CMD_SBPB;
4004 }
4005
4006 if (!boot_cpu_has(X86_FEATURE_IBPB))
4007 reserved_bits |= PRED_CMD_IBPB;
4008
4009 if (!boot_cpu_has(X86_FEATURE_SBPB))
4010 reserved_bits |= PRED_CMD_SBPB;
4011
4012 if (data & reserved_bits)
4013 return 1;
4014
4015 if (!data)
4016 break;
4017
4018 wrmsrq(MSR_IA32_PRED_CMD, data);
4019 break;
4020 }
4021 case MSR_IA32_FLUSH_CMD:
4022 if (!msr_info->host_initiated &&
4023 !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D))
4024 return 1;
4025
4026 if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
4027 return 1;
4028 if (!data)
4029 break;
4030
4031 wrmsrq(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
4032 break;
4033 case MSR_EFER:
4034 return set_efer(vcpu, msr_info);
4035 case MSR_K7_HWCR:
4036 data &= ~(u64)0x40; /* ignore flush filter disable */
4037 data &= ~(u64)0x100; /* ignore ignne emulation enable */
4038 data &= ~(u64)0x8; /* ignore TLB cache disable */
4039
4040 /*
4041 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
4042 * through at least v6.6 whine if TscFreqSel is clear,
4043 * depending on F/M/S.
4044 */
4045 if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
4046 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4047 return 1;
4048 }
4049 vcpu->arch.msr_hwcr = data;
4050 break;
4051 case MSR_FAM10H_MMIO_CONF_BASE:
4052 if (data != 0) {
4053 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4054 return 1;
4055 }
4056 break;
4057 case MSR_IA32_CR_PAT:
4058 if (!kvm_pat_valid(data))
4059 return 1;
4060
4061 vcpu->arch.pat = data;
4062 break;
4063 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4064 case MSR_MTRRdefType:
4065 return kvm_mtrr_set_msr(vcpu, msr, data);
4066 case MSR_IA32_APICBASE:
4067 return kvm_apic_set_base(vcpu, data, msr_info->host_initiated);
4068 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4069 return kvm_x2apic_msr_write(vcpu, msr, data);
4070 case MSR_IA32_TSC_DEADLINE:
4071 kvm_set_lapic_tscdeadline_msr(vcpu, data);
4072 break;
4073 case MSR_IA32_TSC_ADJUST:
4074 if (guest_cpu_cap_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
4075 if (!msr_info->host_initiated) {
4076 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
4077 adjust_tsc_offset_guest(vcpu, adj);
4078 /* Before back to guest, tsc_timestamp must be adjusted
4079 * as well, otherwise guest's percpu pvclock time could jump.
4080 */
4081 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4082 }
4083 vcpu->arch.ia32_tsc_adjust_msr = data;
4084 }
4085 break;
4086 case MSR_IA32_MISC_ENABLE: {
4087 u64 old_val = vcpu->arch.ia32_misc_enable_msr;
4088
4089 if (!msr_info->host_initiated) {
4090 /* RO bits */
4091 if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
4092 return 1;
4093
4094 /* R bits, i.e. writes are ignored, but don't fault. */
4095 data = data & ~MSR_IA32_MISC_ENABLE_EMON;
4096 data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
4097 }
4098
4099 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
4100 ((old_val ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
4101 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_XMM3))
4102 return 1;
4103 vcpu->arch.ia32_misc_enable_msr = data;
4104 vcpu->arch.cpuid_dynamic_bits_dirty = true;
4105 } else {
4106 vcpu->arch.ia32_misc_enable_msr = data;
4107 }
4108 break;
4109 }
4110 case MSR_IA32_SMBASE:
4111 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4112 return 1;
4113 vcpu->arch.smbase = data;
4114 break;
4115 case MSR_IA32_POWER_CTL:
4116 vcpu->arch.msr_ia32_power_ctl = data;
4117 break;
4118 case MSR_IA32_TSC:
4119 if (msr_info->host_initiated) {
4120 kvm_synchronize_tsc(vcpu, &data);
4121 } else if (!vcpu->arch.guest_tsc_protected) {
4122 u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
4123 adjust_tsc_offset_guest(vcpu, adj);
4124 vcpu->arch.ia32_tsc_adjust_msr += adj;
4125 }
4126 break;
4127 case MSR_IA32_XSS:
4128 if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4129 return KVM_MSR_RET_UNSUPPORTED;
4130
4131 if (data & ~vcpu->arch.guest_supported_xss)
4132 return 1;
4133 if (vcpu->arch.ia32_xss == data)
4134 break;
4135 vcpu->arch.ia32_xss = data;
4136 vcpu->arch.cpuid_dynamic_bits_dirty = true;
4137 break;
4138 case MSR_SMI_COUNT:
4139 if (!msr_info->host_initiated)
4140 return 1;
4141 vcpu->arch.smi_count = data;
4142 break;
4143 case MSR_KVM_WALL_CLOCK_NEW:
4144 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4145 return 1;
4146
4147 vcpu->kvm->arch.wall_clock = data;
4148 kvm_write_wall_clock(vcpu->kvm, data, 0);
4149 break;
4150 case MSR_KVM_WALL_CLOCK:
4151 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4152 return 1;
4153
4154 vcpu->kvm->arch.wall_clock = data;
4155 kvm_write_wall_clock(vcpu->kvm, data, 0);
4156 break;
4157 case MSR_KVM_SYSTEM_TIME_NEW:
4158 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4159 return 1;
4160
4161 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
4162 break;
4163 case MSR_KVM_SYSTEM_TIME:
4164 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4165 return 1;
4166
4167 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
4168 break;
4169 case MSR_KVM_ASYNC_PF_EN:
4170 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4171 return 1;
4172
4173 if (kvm_pv_enable_async_pf(vcpu, data))
4174 return 1;
4175 break;
4176 case MSR_KVM_ASYNC_PF_INT:
4177 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4178 return 1;
4179
4180 if (kvm_pv_enable_async_pf_int(vcpu, data))
4181 return 1;
4182 break;
4183 case MSR_KVM_ASYNC_PF_ACK:
4184 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4185 return 1;
4186 if (data & 0x1) {
4187 vcpu->arch.apf.pageready_pending = false;
4188 kvm_check_async_pf_completion(vcpu);
4189 }
4190 break;
4191 case MSR_KVM_STEAL_TIME:
4192 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4193 return 1;
4194
4195 if (unlikely(!sched_info_on()))
4196 return 1;
4197
4198 if (data & KVM_STEAL_RESERVED_MASK)
4199 return 1;
4200
4201 vcpu->arch.st.msr_val = data;
4202
4203 if (!(data & KVM_MSR_ENABLED))
4204 break;
4205
4206 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4207
4208 break;
4209 case MSR_KVM_PV_EOI_EN:
4210 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4211 return 1;
4212
4213 if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
4214 return 1;
4215 break;
4216
4217 case MSR_KVM_POLL_CONTROL:
4218 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4219 return 1;
4220
4221 /* only enable bit supported */
4222 if (data & (-1ULL << 1))
4223 return 1;
4224
4225 vcpu->arch.msr_kvm_poll_control = data;
4226 break;
4227
4228 case MSR_IA32_MCG_CTL:
4229 case MSR_IA32_MCG_STATUS:
4230 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4231 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4232 return set_msr_mce(vcpu, msr_info);
4233
4234 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4235 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4236 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4237 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4238 if (kvm_pmu_is_valid_msr(vcpu, msr))
4239 return kvm_pmu_set_msr(vcpu, msr_info);
4240
4241 if (data)
4242 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4243 break;
4244 case MSR_K7_CLK_CTL:
4245 /*
4246 * Ignore all writes to this no longer documented MSR.
4247 * Writes are only relevant for old K7 processors,
4248 * all pre-dating SVM, but a recommended workaround from
4249 * AMD for these chips. It is possible to specify the
4250 * affected processor models on the command line, hence
4251 * the need to ignore the workaround.
4252 */
4253 break;
4254 #ifdef CONFIG_KVM_HYPERV
4255 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4256 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4257 case HV_X64_MSR_SYNDBG_OPTIONS:
4258 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4259 case HV_X64_MSR_CRASH_CTL:
4260 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4261 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4262 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4263 case HV_X64_MSR_TSC_EMULATION_STATUS:
4264 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4265 return kvm_hv_set_msr_common(vcpu, msr, data,
4266 msr_info->host_initiated);
4267 #endif
4268 case MSR_IA32_BBL_CR_CTL3:
4269 /* Drop writes to this legacy MSR -- see rdmsr
4270 * counterpart for further detail.
4271 */
4272 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4273 break;
4274 case MSR_AMD64_OSVW_ID_LENGTH:
4275 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4276 return 1;
4277 vcpu->arch.osvw.length = data;
4278 break;
4279 case MSR_AMD64_OSVW_STATUS:
4280 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4281 return 1;
4282 vcpu->arch.osvw.status = data;
4283 break;
4284 case MSR_PLATFORM_INFO:
4285 if (!msr_info->host_initiated)
4286 return 1;
4287 vcpu->arch.msr_platform_info = data;
4288 break;
4289 case MSR_MISC_FEATURES_ENABLES:
4290 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4291 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4292 !supports_cpuid_fault(vcpu)))
4293 return 1;
4294 vcpu->arch.msr_misc_features_enables = data;
4295 break;
4296 #ifdef CONFIG_X86_64
4297 case MSR_IA32_XFD:
4298 if (!msr_info->host_initiated &&
4299 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4300 return 1;
4301
4302 if (data & ~kvm_guest_supported_xfd(vcpu))
4303 return 1;
4304
4305 fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4306 break;
4307 case MSR_IA32_XFD_ERR:
4308 if (!msr_info->host_initiated &&
4309 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4310 return 1;
4311
4312 if (data & ~kvm_guest_supported_xfd(vcpu))
4313 return 1;
4314
4315 vcpu->arch.guest_fpu.xfd_err = data;
4316 break;
4317 #endif
4318 case MSR_IA32_U_CET:
4319 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
4320 kvm_set_xstate_msr(vcpu, msr_info);
4321 break;
4322 default:
4323 if (kvm_pmu_is_valid_msr(vcpu, msr))
4324 return kvm_pmu_set_msr(vcpu, msr_info);
4325
4326 return KVM_MSR_RET_UNSUPPORTED;
4327 }
4328 return 0;
4329 }
4330 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_msr_common);
4331
get_msr_mce(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)4332 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
4333 {
4334 u64 data;
4335 u64 mcg_cap = vcpu->arch.mcg_cap;
4336 unsigned bank_num = mcg_cap & 0xff;
4337 u32 offset, last_msr;
4338
4339 switch (msr) {
4340 case MSR_IA32_P5_MC_ADDR:
4341 case MSR_IA32_P5_MC_TYPE:
4342 data = 0;
4343 break;
4344 case MSR_IA32_MCG_CAP:
4345 data = vcpu->arch.mcg_cap;
4346 break;
4347 case MSR_IA32_MCG_CTL:
4348 if (!(mcg_cap & MCG_CTL_P) && !host)
4349 return 1;
4350 data = vcpu->arch.mcg_ctl;
4351 break;
4352 case MSR_IA32_MCG_STATUS:
4353 data = vcpu->arch.mcg_status;
4354 break;
4355 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4356 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4357 if (msr > last_msr)
4358 return 1;
4359
4360 if (!(mcg_cap & MCG_CMCI_P) && !host)
4361 return 1;
4362 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4363 last_msr + 1 - MSR_IA32_MC0_CTL2);
4364 data = vcpu->arch.mci_ctl2_banks[offset];
4365 break;
4366 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4367 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4368 if (msr > last_msr)
4369 return 1;
4370
4371 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4372 last_msr + 1 - MSR_IA32_MC0_CTL);
4373 data = vcpu->arch.mce_banks[offset];
4374 break;
4375 default:
4376 return 1;
4377 }
4378 *pdata = data;
4379 return 0;
4380 }
4381
kvm_get_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4382 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4383 {
4384 switch (msr_info->index) {
4385 case MSR_IA32_PLATFORM_ID:
4386 case MSR_IA32_EBL_CR_POWERON:
4387 case MSR_IA32_LASTBRANCHFROMIP:
4388 case MSR_IA32_LASTBRANCHTOIP:
4389 case MSR_IA32_LASTINTFROMIP:
4390 case MSR_IA32_LASTINTTOIP:
4391 case MSR_AMD64_SYSCFG:
4392 case MSR_K8_TSEG_ADDR:
4393 case MSR_K8_TSEG_MASK:
4394 case MSR_VM_HSAVE_PA:
4395 case MSR_K8_INT_PENDING_MSG:
4396 case MSR_AMD64_NB_CFG:
4397 case MSR_FAM10H_MMIO_CONF_BASE:
4398 case MSR_AMD64_BU_CFG2:
4399 case MSR_IA32_PERF_CTL:
4400 case MSR_AMD64_DC_CFG:
4401 case MSR_AMD64_TW_CFG:
4402 case MSR_F15H_EX_CFG:
4403 /*
4404 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4405 * limit) MSRs. Just return 0, as we do not want to expose the host
4406 * data here. Do not conditionalize this on CPUID, as KVM does not do
4407 * so for existing CPU-specific MSRs.
4408 */
4409 case MSR_RAPL_POWER_UNIT:
4410 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
4411 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
4412 case MSR_PKG_ENERGY_STATUS: /* Total package */
4413 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
4414 msr_info->data = 0;
4415 break;
4416 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4417 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4418 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4419 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4420 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4421 return kvm_pmu_get_msr(vcpu, msr_info);
4422 msr_info->data = 0;
4423 break;
4424 case MSR_IA32_UCODE_REV:
4425 msr_info->data = vcpu->arch.microcode_version;
4426 break;
4427 case MSR_IA32_ARCH_CAPABILITIES:
4428 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4429 return KVM_MSR_RET_UNSUPPORTED;
4430 msr_info->data = vcpu->arch.arch_capabilities;
4431 break;
4432 case MSR_IA32_PERF_CAPABILITIES:
4433 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
4434 return KVM_MSR_RET_UNSUPPORTED;
4435 msr_info->data = vcpu->arch.perf_capabilities;
4436 break;
4437 case MSR_IA32_POWER_CTL:
4438 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4439 break;
4440 case MSR_IA32_TSC: {
4441 /*
4442 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4443 * even when not intercepted. AMD manual doesn't explicitly
4444 * state this but appears to behave the same.
4445 *
4446 * On userspace reads and writes, however, we unconditionally
4447 * return L1's TSC value to ensure backwards-compatible
4448 * behavior for migration.
4449 */
4450 u64 offset, ratio;
4451
4452 if (msr_info->host_initiated) {
4453 offset = vcpu->arch.l1_tsc_offset;
4454 ratio = vcpu->arch.l1_tsc_scaling_ratio;
4455 } else {
4456 offset = vcpu->arch.tsc_offset;
4457 ratio = vcpu->arch.tsc_scaling_ratio;
4458 }
4459
4460 msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4461 break;
4462 }
4463 case MSR_IA32_CR_PAT:
4464 msr_info->data = vcpu->arch.pat;
4465 break;
4466 case MSR_MTRRcap:
4467 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4468 case MSR_MTRRdefType:
4469 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4470 case 0xcd: /* fsb frequency */
4471 msr_info->data = 3;
4472 break;
4473 /*
4474 * MSR_EBC_FREQUENCY_ID
4475 * Conservative value valid for even the basic CPU models.
4476 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4477 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4478 * and 266MHz for model 3, or 4. Set Core Clock
4479 * Frequency to System Bus Frequency Ratio to 1 (bits
4480 * 31:24) even though these are only valid for CPU
4481 * models > 2, however guests may end up dividing or
4482 * multiplying by zero otherwise.
4483 */
4484 case MSR_EBC_FREQUENCY_ID:
4485 msr_info->data = 1 << 24;
4486 break;
4487 case MSR_IA32_APICBASE:
4488 msr_info->data = vcpu->arch.apic_base;
4489 break;
4490 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4491 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4492 case MSR_IA32_TSC_DEADLINE:
4493 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4494 break;
4495 case MSR_IA32_TSC_ADJUST:
4496 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4497 break;
4498 case MSR_IA32_MISC_ENABLE:
4499 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4500 break;
4501 case MSR_IA32_SMBASE:
4502 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4503 return 1;
4504 msr_info->data = vcpu->arch.smbase;
4505 break;
4506 case MSR_SMI_COUNT:
4507 msr_info->data = vcpu->arch.smi_count;
4508 break;
4509 case MSR_IA32_PERF_STATUS:
4510 /* TSC increment by tick */
4511 msr_info->data = 1000ULL;
4512 /* CPU multiplier */
4513 msr_info->data |= (((uint64_t)4ULL) << 40);
4514 break;
4515 case MSR_EFER:
4516 msr_info->data = vcpu->arch.efer;
4517 break;
4518 case MSR_KVM_WALL_CLOCK:
4519 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4520 return 1;
4521
4522 msr_info->data = vcpu->kvm->arch.wall_clock;
4523 break;
4524 case MSR_KVM_WALL_CLOCK_NEW:
4525 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4526 return 1;
4527
4528 msr_info->data = vcpu->kvm->arch.wall_clock;
4529 break;
4530 case MSR_KVM_SYSTEM_TIME:
4531 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4532 return 1;
4533
4534 msr_info->data = vcpu->arch.time;
4535 break;
4536 case MSR_KVM_SYSTEM_TIME_NEW:
4537 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4538 return 1;
4539
4540 msr_info->data = vcpu->arch.time;
4541 break;
4542 case MSR_KVM_ASYNC_PF_EN:
4543 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4544 return 1;
4545
4546 msr_info->data = vcpu->arch.apf.msr_en_val;
4547 break;
4548 case MSR_KVM_ASYNC_PF_INT:
4549 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4550 return 1;
4551
4552 msr_info->data = vcpu->arch.apf.msr_int_val;
4553 break;
4554 case MSR_KVM_ASYNC_PF_ACK:
4555 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4556 return 1;
4557
4558 msr_info->data = 0;
4559 break;
4560 case MSR_KVM_STEAL_TIME:
4561 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4562 return 1;
4563
4564 msr_info->data = vcpu->arch.st.msr_val;
4565 break;
4566 case MSR_KVM_PV_EOI_EN:
4567 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4568 return 1;
4569
4570 msr_info->data = vcpu->arch.pv_eoi.msr_val;
4571 break;
4572 case MSR_KVM_POLL_CONTROL:
4573 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4574 return 1;
4575
4576 msr_info->data = vcpu->arch.msr_kvm_poll_control;
4577 break;
4578 case MSR_IA32_P5_MC_ADDR:
4579 case MSR_IA32_P5_MC_TYPE:
4580 case MSR_IA32_MCG_CAP:
4581 case MSR_IA32_MCG_CTL:
4582 case MSR_IA32_MCG_STATUS:
4583 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4584 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4585 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4586 msr_info->host_initiated);
4587 case MSR_IA32_XSS:
4588 if (!msr_info->host_initiated &&
4589 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4590 return 1;
4591 msr_info->data = vcpu->arch.ia32_xss;
4592 break;
4593 case MSR_K7_CLK_CTL:
4594 /*
4595 * Provide expected ramp-up count for K7. All other
4596 * are set to zero, indicating minimum divisors for
4597 * every field.
4598 *
4599 * This prevents guest kernels on AMD host with CPU
4600 * type 6, model 8 and higher from exploding due to
4601 * the rdmsr failing.
4602 */
4603 msr_info->data = 0x20000000;
4604 break;
4605 #ifdef CONFIG_KVM_HYPERV
4606 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4607 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4608 case HV_X64_MSR_SYNDBG_OPTIONS:
4609 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4610 case HV_X64_MSR_CRASH_CTL:
4611 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4612 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4613 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4614 case HV_X64_MSR_TSC_EMULATION_STATUS:
4615 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4616 return kvm_hv_get_msr_common(vcpu,
4617 msr_info->index, &msr_info->data,
4618 msr_info->host_initiated);
4619 #endif
4620 case MSR_IA32_BBL_CR_CTL3:
4621 /* This legacy MSR exists but isn't fully documented in current
4622 * silicon. It is however accessed by winxp in very narrow
4623 * scenarios where it sets bit #19, itself documented as
4624 * a "reserved" bit. Best effort attempt to source coherent
4625 * read data here should the balance of the register be
4626 * interpreted by the guest:
4627 *
4628 * L2 cache control register 3: 64GB range, 256KB size,
4629 * enabled, latency 0x1, configured
4630 */
4631 msr_info->data = 0xbe702111;
4632 break;
4633 case MSR_AMD64_OSVW_ID_LENGTH:
4634 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4635 return 1;
4636 msr_info->data = vcpu->arch.osvw.length;
4637 break;
4638 case MSR_AMD64_OSVW_STATUS:
4639 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4640 return 1;
4641 msr_info->data = vcpu->arch.osvw.status;
4642 break;
4643 case MSR_PLATFORM_INFO:
4644 if (!msr_info->host_initiated &&
4645 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4646 return 1;
4647 msr_info->data = vcpu->arch.msr_platform_info;
4648 break;
4649 case MSR_MISC_FEATURES_ENABLES:
4650 msr_info->data = vcpu->arch.msr_misc_features_enables;
4651 break;
4652 case MSR_K7_HWCR:
4653 msr_info->data = vcpu->arch.msr_hwcr;
4654 break;
4655 #ifdef CONFIG_X86_64
4656 case MSR_IA32_XFD:
4657 if (!msr_info->host_initiated &&
4658 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4659 return 1;
4660
4661 msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4662 break;
4663 case MSR_IA32_XFD_ERR:
4664 if (!msr_info->host_initiated &&
4665 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4666 return 1;
4667
4668 msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4669 break;
4670 #endif
4671 case MSR_IA32_U_CET:
4672 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
4673 kvm_get_xstate_msr(vcpu, msr_info);
4674 break;
4675 default:
4676 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4677 return kvm_pmu_get_msr(vcpu, msr_info);
4678
4679 return KVM_MSR_RET_UNSUPPORTED;
4680 }
4681 return 0;
4682 }
4683 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_msr_common);
4684
4685 /*
4686 * Read or write a bunch of msrs. All parameters are kernel addresses.
4687 *
4688 * @return number of msrs set successfully.
4689 */
__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))4690 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4691 struct kvm_msr_entry *entries,
4692 int (*do_msr)(struct kvm_vcpu *vcpu,
4693 unsigned index, u64 *data))
4694 {
4695 bool fpu_loaded = false;
4696 int i;
4697
4698 for (i = 0; i < msrs->nmsrs; ++i) {
4699 /*
4700 * If userspace is accessing one or more XSTATE-managed MSRs,
4701 * temporarily load the guest's FPU state so that the guest's
4702 * MSR value(s) is resident in hardware and thus can be accessed
4703 * via RDMSR/WRMSR.
4704 */
4705 if (!fpu_loaded && is_xstate_managed_msr(vcpu, entries[i].index)) {
4706 kvm_load_guest_fpu(vcpu);
4707 fpu_loaded = true;
4708 }
4709 if (do_msr(vcpu, entries[i].index, &entries[i].data))
4710 break;
4711 }
4712 if (fpu_loaded)
4713 kvm_put_guest_fpu(vcpu);
4714
4715 return i;
4716 }
4717
4718 /*
4719 * Read or write a bunch of msrs. Parameters are user addresses.
4720 *
4721 * @return number of msrs set successfully.
4722 */
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)4723 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4724 int (*do_msr)(struct kvm_vcpu *vcpu,
4725 unsigned index, u64 *data),
4726 int writeback)
4727 {
4728 struct kvm_msrs msrs;
4729 struct kvm_msr_entry *entries;
4730 unsigned size;
4731 int r;
4732
4733 r = -EFAULT;
4734 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4735 goto out;
4736
4737 r = -E2BIG;
4738 if (msrs.nmsrs >= MAX_IO_MSRS)
4739 goto out;
4740
4741 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4742 entries = memdup_user(user_msrs->entries, size);
4743 if (IS_ERR(entries)) {
4744 r = PTR_ERR(entries);
4745 goto out;
4746 }
4747
4748 r = __msr_io(vcpu, &msrs, entries, do_msr);
4749
4750 if (writeback && copy_to_user(user_msrs->entries, entries, size))
4751 r = -EFAULT;
4752
4753 kfree(entries);
4754 out:
4755 return r;
4756 }
4757
kvm_can_mwait_in_guest(void)4758 static inline bool kvm_can_mwait_in_guest(void)
4759 {
4760 return boot_cpu_has(X86_FEATURE_MWAIT) &&
4761 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
4762 boot_cpu_has(X86_FEATURE_ARAT);
4763 }
4764
kvm_get_allowed_disable_exits(void)4765 static u64 kvm_get_allowed_disable_exits(void)
4766 {
4767 u64 r = KVM_X86_DISABLE_EXITS_PAUSE;
4768
4769 if (boot_cpu_has(X86_FEATURE_APERFMPERF))
4770 r |= KVM_X86_DISABLE_EXITS_APERFMPERF;
4771
4772 if (!mitigate_smt_rsb) {
4773 r |= KVM_X86_DISABLE_EXITS_HLT |
4774 KVM_X86_DISABLE_EXITS_CSTATE;
4775
4776 if (kvm_can_mwait_in_guest())
4777 r |= KVM_X86_DISABLE_EXITS_MWAIT;
4778 }
4779 return r;
4780 }
4781
4782 #ifdef CONFIG_KVM_HYPERV
kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 __user * cpuid_arg)4783 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4784 struct kvm_cpuid2 __user *cpuid_arg)
4785 {
4786 struct kvm_cpuid2 cpuid;
4787 int r;
4788
4789 r = -EFAULT;
4790 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4791 return r;
4792
4793 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4794 if (r)
4795 return r;
4796
4797 r = -EFAULT;
4798 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4799 return r;
4800
4801 return 0;
4802 }
4803 #endif
4804
kvm_is_vm_type_supported(unsigned long type)4805 static bool kvm_is_vm_type_supported(unsigned long type)
4806 {
4807 return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
4808 }
4809
kvm_sync_valid_fields(struct kvm * kvm)4810 static inline u64 kvm_sync_valid_fields(struct kvm *kvm)
4811 {
4812 return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
4813 }
4814
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)4815 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4816 {
4817 int r = 0;
4818
4819 switch (ext) {
4820 case KVM_CAP_IRQCHIP:
4821 case KVM_CAP_HLT:
4822 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4823 case KVM_CAP_SET_TSS_ADDR:
4824 case KVM_CAP_EXT_CPUID:
4825 case KVM_CAP_EXT_EMUL_CPUID:
4826 case KVM_CAP_CLOCKSOURCE:
4827 #ifdef CONFIG_KVM_IOAPIC
4828 case KVM_CAP_PIT:
4829 case KVM_CAP_PIT2:
4830 case KVM_CAP_PIT_STATE2:
4831 case KVM_CAP_REINJECT_CONTROL:
4832 #endif
4833 case KVM_CAP_NOP_IO_DELAY:
4834 case KVM_CAP_MP_STATE:
4835 case KVM_CAP_SYNC_MMU:
4836 case KVM_CAP_USER_NMI:
4837 case KVM_CAP_IRQ_INJECT_STATUS:
4838 case KVM_CAP_IOEVENTFD:
4839 case KVM_CAP_IOEVENTFD_NO_LENGTH:
4840
4841 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4842 case KVM_CAP_VCPU_EVENTS:
4843 #ifdef CONFIG_KVM_HYPERV
4844 case KVM_CAP_HYPERV:
4845 case KVM_CAP_HYPERV_VAPIC:
4846 case KVM_CAP_HYPERV_SPIN:
4847 case KVM_CAP_HYPERV_TIME:
4848 case KVM_CAP_HYPERV_SYNIC:
4849 case KVM_CAP_HYPERV_SYNIC2:
4850 case KVM_CAP_HYPERV_VP_INDEX:
4851 case KVM_CAP_HYPERV_EVENTFD:
4852 case KVM_CAP_HYPERV_TLBFLUSH:
4853 case KVM_CAP_HYPERV_SEND_IPI:
4854 case KVM_CAP_HYPERV_CPUID:
4855 case KVM_CAP_HYPERV_ENFORCE_CPUID:
4856 case KVM_CAP_SYS_HYPERV_CPUID:
4857 #endif
4858 case KVM_CAP_PCI_SEGMENT:
4859 case KVM_CAP_DEBUGREGS:
4860 case KVM_CAP_X86_ROBUST_SINGLESTEP:
4861 case KVM_CAP_XSAVE:
4862 case KVM_CAP_ASYNC_PF:
4863 case KVM_CAP_ASYNC_PF_INT:
4864 case KVM_CAP_GET_TSC_KHZ:
4865 case KVM_CAP_KVMCLOCK_CTRL:
4866 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4867 case KVM_CAP_TSC_DEADLINE_TIMER:
4868 case KVM_CAP_DISABLE_QUIRKS:
4869 case KVM_CAP_SET_BOOT_CPU_ID:
4870 case KVM_CAP_SPLIT_IRQCHIP:
4871 case KVM_CAP_IMMEDIATE_EXIT:
4872 case KVM_CAP_PMU_EVENT_FILTER:
4873 case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
4874 case KVM_CAP_GET_MSR_FEATURES:
4875 case KVM_CAP_MSR_PLATFORM_INFO:
4876 case KVM_CAP_EXCEPTION_PAYLOAD:
4877 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4878 case KVM_CAP_SET_GUEST_DEBUG:
4879 case KVM_CAP_LAST_CPU:
4880 case KVM_CAP_X86_USER_SPACE_MSR:
4881 case KVM_CAP_X86_MSR_FILTER:
4882 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4883 #ifdef CONFIG_X86_SGX_KVM
4884 case KVM_CAP_SGX_ATTRIBUTE:
4885 #endif
4886 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4887 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4888 case KVM_CAP_SREGS2:
4889 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4890 case KVM_CAP_VCPU_ATTRIBUTES:
4891 case KVM_CAP_SYS_ATTRIBUTES:
4892 case KVM_CAP_VAPIC:
4893 case KVM_CAP_ENABLE_CAP:
4894 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4895 case KVM_CAP_IRQFD_RESAMPLE:
4896 case KVM_CAP_MEMORY_FAULT_INFO:
4897 case KVM_CAP_X86_GUEST_MODE:
4898 case KVM_CAP_ONE_REG:
4899 r = 1;
4900 break;
4901 case KVM_CAP_PRE_FAULT_MEMORY:
4902 r = tdp_enabled;
4903 break;
4904 case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
4905 r = APIC_BUS_CYCLE_NS_DEFAULT;
4906 break;
4907 case KVM_CAP_EXIT_HYPERCALL:
4908 r = KVM_EXIT_HYPERCALL_VALID_MASK;
4909 break;
4910 case KVM_CAP_SET_GUEST_DEBUG2:
4911 return KVM_GUESTDBG_VALID_MASK;
4912 #ifdef CONFIG_KVM_XEN
4913 case KVM_CAP_XEN_HVM:
4914 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4915 KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4916 KVM_XEN_HVM_CONFIG_SHARED_INFO |
4917 KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4918 KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
4919 KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4920 KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
4921 if (sched_info_on())
4922 r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4923 KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
4924 break;
4925 #endif
4926 case KVM_CAP_SYNC_REGS:
4927 r = kvm_sync_valid_fields(kvm);
4928 break;
4929 case KVM_CAP_ADJUST_CLOCK:
4930 r = KVM_CLOCK_VALID_FLAGS;
4931 break;
4932 case KVM_CAP_X86_DISABLE_EXITS:
4933 r = kvm_get_allowed_disable_exits();
4934 break;
4935 case KVM_CAP_X86_SMM:
4936 if (!IS_ENABLED(CONFIG_KVM_SMM))
4937 break;
4938
4939 /* SMBASE is usually relocated above 1M on modern chipsets,
4940 * and SMM handlers might indeed rely on 4G segment limits,
4941 * so do not report SMM to be available if real mode is
4942 * emulated via vm86 mode. Still, do not go to great lengths
4943 * to avoid userspace's usage of the feature, because it is a
4944 * fringe case that is not enabled except via specific settings
4945 * of the module parameters.
4946 */
4947 r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4948 break;
4949 case KVM_CAP_NR_VCPUS:
4950 r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4951 break;
4952 case KVM_CAP_MAX_VCPUS:
4953 r = KVM_MAX_VCPUS;
4954 if (kvm)
4955 r = kvm->max_vcpus;
4956 break;
4957 case KVM_CAP_MAX_VCPU_ID:
4958 r = KVM_MAX_VCPU_IDS;
4959 break;
4960 case KVM_CAP_PV_MMU: /* obsolete */
4961 r = 0;
4962 break;
4963 case KVM_CAP_MCE:
4964 r = KVM_MAX_MCE_BANKS;
4965 break;
4966 case KVM_CAP_XCRS:
4967 r = boot_cpu_has(X86_FEATURE_XSAVE);
4968 break;
4969 case KVM_CAP_TSC_CONTROL:
4970 case KVM_CAP_VM_TSC_CONTROL:
4971 r = kvm_caps.has_tsc_control;
4972 break;
4973 case KVM_CAP_X2APIC_API:
4974 r = KVM_X2APIC_API_VALID_FLAGS;
4975 break;
4976 case KVM_CAP_NESTED_STATE:
4977 r = kvm_x86_ops.nested_ops->get_state ?
4978 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4979 break;
4980 #ifdef CONFIG_KVM_HYPERV
4981 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4982 r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
4983 break;
4984 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4985 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4986 break;
4987 #endif
4988 case KVM_CAP_SMALLER_MAXPHYADDR:
4989 r = (int) allow_smaller_maxphyaddr;
4990 break;
4991 case KVM_CAP_STEAL_TIME:
4992 r = sched_info_on();
4993 break;
4994 case KVM_CAP_X86_BUS_LOCK_EXIT:
4995 if (kvm_caps.has_bus_lock_exit)
4996 r = KVM_BUS_LOCK_DETECTION_OFF |
4997 KVM_BUS_LOCK_DETECTION_EXIT;
4998 else
4999 r = 0;
5000 break;
5001 case KVM_CAP_XSAVE2: {
5002 r = xstate_required_size(kvm_get_filtered_xcr0(), false);
5003 if (r < sizeof(struct kvm_xsave))
5004 r = sizeof(struct kvm_xsave);
5005 break;
5006 }
5007 case KVM_CAP_PMU_CAPABILITY:
5008 r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
5009 break;
5010 case KVM_CAP_DISABLE_QUIRKS2:
5011 r = kvm_caps.supported_quirks;
5012 break;
5013 case KVM_CAP_X86_NOTIFY_VMEXIT:
5014 r = kvm_caps.has_notify_vmexit;
5015 break;
5016 case KVM_CAP_VM_TYPES:
5017 r = kvm_caps.supported_vm_types;
5018 break;
5019 case KVM_CAP_READONLY_MEM:
5020 r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
5021 break;
5022 default:
5023 break;
5024 }
5025 return r;
5026 }
5027
__kvm_x86_dev_get_attr(struct kvm_device_attr * attr,u64 * val)5028 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
5029 {
5030 if (attr->group) {
5031 if (kvm_x86_ops.dev_get_attr)
5032 return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
5033 return -ENXIO;
5034 }
5035
5036 switch (attr->attr) {
5037 case KVM_X86_XCOMP_GUEST_SUPP:
5038 *val = kvm_caps.supported_xcr0;
5039 return 0;
5040 default:
5041 return -ENXIO;
5042 }
5043 }
5044
kvm_x86_dev_get_attr(struct kvm_device_attr * attr)5045 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
5046 {
5047 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5048 int r;
5049 u64 val;
5050
5051 r = __kvm_x86_dev_get_attr(attr, &val);
5052 if (r < 0)
5053 return r;
5054
5055 if (put_user(val, uaddr))
5056 return -EFAULT;
5057
5058 return 0;
5059 }
5060
kvm_x86_dev_has_attr(struct kvm_device_attr * attr)5061 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
5062 {
5063 u64 val;
5064
5065 return __kvm_x86_dev_get_attr(attr, &val);
5066 }
5067
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5068 long kvm_arch_dev_ioctl(struct file *filp,
5069 unsigned int ioctl, unsigned long arg)
5070 {
5071 void __user *argp = (void __user *)arg;
5072 long r;
5073
5074 switch (ioctl) {
5075 case KVM_GET_MSR_INDEX_LIST: {
5076 struct kvm_msr_list __user *user_msr_list = argp;
5077 struct kvm_msr_list msr_list;
5078 unsigned n;
5079
5080 r = -EFAULT;
5081 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
5082 goto out;
5083 n = msr_list.nmsrs;
5084 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
5085 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
5086 goto out;
5087 r = -E2BIG;
5088 if (n < msr_list.nmsrs)
5089 goto out;
5090 r = -EFAULT;
5091 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
5092 num_msrs_to_save * sizeof(u32)))
5093 goto out;
5094 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
5095 &emulated_msrs,
5096 num_emulated_msrs * sizeof(u32)))
5097 goto out;
5098 r = 0;
5099 break;
5100 }
5101 case KVM_GET_SUPPORTED_CPUID:
5102 case KVM_GET_EMULATED_CPUID: {
5103 struct kvm_cpuid2 __user *cpuid_arg = argp;
5104 struct kvm_cpuid2 cpuid;
5105
5106 r = -EFAULT;
5107 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5108 goto out;
5109
5110 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
5111 ioctl);
5112 if (r)
5113 goto out;
5114
5115 r = -EFAULT;
5116 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5117 goto out;
5118 r = 0;
5119 break;
5120 }
5121 case KVM_X86_GET_MCE_CAP_SUPPORTED:
5122 r = -EFAULT;
5123 if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
5124 sizeof(kvm_caps.supported_mce_cap)))
5125 goto out;
5126 r = 0;
5127 break;
5128 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
5129 struct kvm_msr_list __user *user_msr_list = argp;
5130 struct kvm_msr_list msr_list;
5131 unsigned int n;
5132
5133 r = -EFAULT;
5134 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
5135 goto out;
5136 n = msr_list.nmsrs;
5137 msr_list.nmsrs = num_msr_based_features;
5138 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
5139 goto out;
5140 r = -E2BIG;
5141 if (n < msr_list.nmsrs)
5142 goto out;
5143 r = -EFAULT;
5144 if (copy_to_user(user_msr_list->indices, &msr_based_features,
5145 num_msr_based_features * sizeof(u32)))
5146 goto out;
5147 r = 0;
5148 break;
5149 }
5150 case KVM_GET_MSRS:
5151 r = msr_io(NULL, argp, do_get_feature_msr, 1);
5152 break;
5153 #ifdef CONFIG_KVM_HYPERV
5154 case KVM_GET_SUPPORTED_HV_CPUID:
5155 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
5156 break;
5157 #endif
5158 case KVM_GET_DEVICE_ATTR: {
5159 struct kvm_device_attr attr;
5160 r = -EFAULT;
5161 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
5162 break;
5163 r = kvm_x86_dev_get_attr(&attr);
5164 break;
5165 }
5166 case KVM_HAS_DEVICE_ATTR: {
5167 struct kvm_device_attr attr;
5168 r = -EFAULT;
5169 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
5170 break;
5171 r = kvm_x86_dev_has_attr(&attr);
5172 break;
5173 }
5174 default:
5175 r = -EINVAL;
5176 break;
5177 }
5178 out:
5179 return r;
5180 }
5181
need_emulate_wbinvd(struct kvm_vcpu * vcpu)5182 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
5183 {
5184 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
5185 }
5186
5187 static DEFINE_PER_CPU(struct kvm_vcpu *, last_vcpu);
5188
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)5189 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
5190 {
5191 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
5192
5193 vcpu->arch.l1tf_flush_l1d = true;
5194
5195 if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
5196 pmu->need_cleanup = true;
5197 kvm_make_request(KVM_REQ_PMU, vcpu);
5198 }
5199
5200 /* Address WBINVD may be executed by guest */
5201 if (need_emulate_wbinvd(vcpu)) {
5202 if (kvm_x86_call(has_wbinvd_exit)())
5203 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5204 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
5205 wbinvd_on_cpu(vcpu->cpu);
5206 }
5207
5208 kvm_x86_call(vcpu_load)(vcpu, cpu);
5209
5210 if (vcpu != per_cpu(last_vcpu, cpu)) {
5211 /*
5212 * Flush the branch predictor when switching vCPUs on the same
5213 * physical CPU, as each vCPU needs its own branch prediction
5214 * domain. No IBPB is needed when switching between L1 and L2
5215 * on the same vCPU unless IBRS is advertised to the vCPU; that
5216 * is handled on the nested VM-Exit path.
5217 */
5218 if (static_branch_likely(&switch_vcpu_ibpb))
5219 indirect_branch_prediction_barrier();
5220 per_cpu(last_vcpu, cpu) = vcpu;
5221 }
5222
5223 /* Save host pkru register if supported */
5224 vcpu->arch.host_pkru = read_pkru();
5225
5226 /* Apply any externally detected TSC adjustments (due to suspend) */
5227 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5228 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5229 vcpu->arch.tsc_offset_adjustment = 0;
5230 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5231 }
5232
5233 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
5234 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
5235 rdtsc() - vcpu->arch.last_host_tsc;
5236 if (tsc_delta < 0)
5237 mark_tsc_unstable("KVM discovered backwards TSC");
5238
5239 if (kvm_check_tsc_unstable()) {
5240 u64 offset = kvm_compute_l1_tsc_offset(vcpu,
5241 vcpu->arch.last_guest_tsc);
5242 kvm_vcpu_write_tsc_offset(vcpu, offset);
5243 if (!vcpu->arch.guest_tsc_protected)
5244 vcpu->arch.tsc_catchup = 1;
5245 }
5246
5247 if (kvm_lapic_hv_timer_in_use(vcpu))
5248 kvm_lapic_restart_hv_timer(vcpu);
5249
5250 /*
5251 * On a host with synchronized TSC, there is no need to update
5252 * kvmclock on vcpu->cpu migration
5253 */
5254 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
5255 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
5256 if (vcpu->cpu != cpu)
5257 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
5258 vcpu->cpu = cpu;
5259 }
5260
5261 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
5262 }
5263
kvm_steal_time_set_preempted(struct kvm_vcpu * vcpu)5264 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
5265 {
5266 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
5267 struct kvm_steal_time __user *st;
5268 struct kvm_memslots *slots;
5269 static const u8 preempted = KVM_VCPU_PREEMPTED;
5270 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
5271
5272 /*
5273 * The vCPU can be marked preempted if and only if the VM-Exit was on
5274 * an instruction boundary and will not trigger guest emulation of any
5275 * kind (see vcpu_run). Vendor specific code controls (conservatively)
5276 * when this is true, for example allowing the vCPU to be marked
5277 * preempted if and only if the VM-Exit was due to a host interrupt.
5278 */
5279 if (!vcpu->arch.at_instruction_boundary) {
5280 vcpu->stat.preemption_other++;
5281 return;
5282 }
5283
5284 vcpu->stat.preemption_reported++;
5285 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
5286 return;
5287
5288 if (vcpu->arch.st.preempted)
5289 return;
5290
5291 /* This happens on process exit */
5292 if (unlikely(current->mm != vcpu->kvm->mm))
5293 return;
5294
5295 slots = kvm_memslots(vcpu->kvm);
5296
5297 if (unlikely(slots->generation != ghc->generation ||
5298 gpa != ghc->gpa ||
5299 kvm_is_error_hva(ghc->hva) || !ghc->memslot))
5300 return;
5301
5302 st = (struct kvm_steal_time __user *)ghc->hva;
5303 BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
5304
5305 if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
5306 vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
5307
5308 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
5309 }
5310
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)5311 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
5312 {
5313 int idx;
5314
5315 if (vcpu->preempted) {
5316 /*
5317 * Assume protected guests are in-kernel. Inefficient yielding
5318 * due to false positives is preferable to never yielding due
5319 * to false negatives.
5320 */
5321 vcpu->arch.preempted_in_kernel = vcpu->arch.guest_state_protected ||
5322 !kvm_x86_call(get_cpl_no_cache)(vcpu);
5323
5324 /*
5325 * Take the srcu lock as memslots will be accessed to check the gfn
5326 * cache generation against the memslots generation.
5327 */
5328 idx = srcu_read_lock(&vcpu->kvm->srcu);
5329 if (kvm_xen_msr_enabled(vcpu->kvm))
5330 kvm_xen_runstate_set_preempted(vcpu);
5331 else
5332 kvm_steal_time_set_preempted(vcpu);
5333 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5334 }
5335
5336 kvm_x86_call(vcpu_put)(vcpu);
5337 vcpu->arch.last_host_tsc = rdtsc();
5338 }
5339
kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5340 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5341 struct kvm_lapic_state *s)
5342 {
5343 if (vcpu->arch.apic->guest_apic_protected)
5344 return -EINVAL;
5345
5346 kvm_x86_call(sync_pir_to_irr)(vcpu);
5347
5348 return kvm_apic_get_state(vcpu, s);
5349 }
5350
kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5351 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5352 struct kvm_lapic_state *s)
5353 {
5354 int r;
5355
5356 if (vcpu->arch.apic->guest_apic_protected)
5357 return -EINVAL;
5358
5359 r = kvm_apic_set_state(vcpu, s);
5360 if (r)
5361 return r;
5362 update_cr8_intercept(vcpu);
5363
5364 return 0;
5365 }
5366
kvm_cpu_accept_dm_intr(struct kvm_vcpu * vcpu)5367 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5368 {
5369 /*
5370 * We can accept userspace's request for interrupt injection
5371 * as long as we have a place to store the interrupt number.
5372 * The actual injection will happen when the CPU is able to
5373 * deliver the interrupt.
5374 */
5375 if (kvm_cpu_has_extint(vcpu))
5376 return false;
5377
5378 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
5379 return (!lapic_in_kernel(vcpu) ||
5380 kvm_apic_accept_pic_intr(vcpu));
5381 }
5382
kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu * vcpu)5383 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5384 {
5385 /*
5386 * Do not cause an interrupt window exit if an exception
5387 * is pending or an event needs reinjection; userspace
5388 * might want to inject the interrupt manually using KVM_SET_REGS
5389 * or KVM_SET_SREGS. For that to work, we must be at an
5390 * instruction boundary and with no events half-injected.
5391 */
5392 return (kvm_arch_interrupt_allowed(vcpu) &&
5393 kvm_cpu_accept_dm_intr(vcpu) &&
5394 !kvm_event_needs_reinjection(vcpu) &&
5395 !kvm_is_exception_pending(vcpu));
5396 }
5397
kvm_vcpu_ioctl_interrupt(struct kvm_vcpu * vcpu,struct kvm_interrupt * irq)5398 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5399 struct kvm_interrupt *irq)
5400 {
5401 if (irq->irq >= KVM_NR_INTERRUPTS)
5402 return -EINVAL;
5403
5404 if (!irqchip_in_kernel(vcpu->kvm)) {
5405 kvm_queue_interrupt(vcpu, irq->irq, false);
5406 kvm_make_request(KVM_REQ_EVENT, vcpu);
5407 return 0;
5408 }
5409
5410 /*
5411 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5412 * fail for in-kernel 8259.
5413 */
5414 if (pic_in_kernel(vcpu->kvm))
5415 return -ENXIO;
5416
5417 if (vcpu->arch.pending_external_vector != -1)
5418 return -EEXIST;
5419
5420 vcpu->arch.pending_external_vector = irq->irq;
5421 kvm_make_request(KVM_REQ_EVENT, vcpu);
5422 return 0;
5423 }
5424
kvm_vcpu_ioctl_nmi(struct kvm_vcpu * vcpu)5425 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5426 {
5427 kvm_inject_nmi(vcpu);
5428
5429 return 0;
5430 }
5431
vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu * vcpu,struct kvm_tpr_access_ctl * tac)5432 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5433 struct kvm_tpr_access_ctl *tac)
5434 {
5435 if (tac->flags)
5436 return -EINVAL;
5437 vcpu->arch.tpr_access_reporting = !!tac->enabled;
5438 return 0;
5439 }
5440
kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu * vcpu,u64 mcg_cap)5441 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5442 u64 mcg_cap)
5443 {
5444 int r;
5445 unsigned bank_num = mcg_cap & 0xff, bank;
5446
5447 r = -EINVAL;
5448 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
5449 goto out;
5450 if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
5451 goto out;
5452 r = 0;
5453 vcpu->arch.mcg_cap = mcg_cap;
5454 /* Init IA32_MCG_CTL to all 1s */
5455 if (mcg_cap & MCG_CTL_P)
5456 vcpu->arch.mcg_ctl = ~(u64)0;
5457 /* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5458 for (bank = 0; bank < bank_num; bank++) {
5459 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
5460 if (mcg_cap & MCG_CMCI_P)
5461 vcpu->arch.mci_ctl2_banks[bank] = 0;
5462 }
5463
5464 kvm_apic_after_set_mcg_cap(vcpu);
5465
5466 kvm_x86_call(setup_mce)(vcpu);
5467 out:
5468 return r;
5469 }
5470
5471 /*
5472 * Validate this is an UCNA (uncorrectable no action) error by checking the
5473 * MCG_STATUS and MCi_STATUS registers:
5474 * - none of the bits for Machine Check Exceptions are set
5475 * - both the VAL (valid) and UC (uncorrectable) bits are set
5476 * MCI_STATUS_PCC - Processor Context Corrupted
5477 * MCI_STATUS_S - Signaled as a Machine Check Exception
5478 * MCI_STATUS_AR - Software recoverable Action Required
5479 */
is_ucna(struct kvm_x86_mce * mce)5480 static bool is_ucna(struct kvm_x86_mce *mce)
5481 {
5482 return !mce->mcg_status &&
5483 !(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5484 (mce->status & MCI_STATUS_VAL) &&
5485 (mce->status & MCI_STATUS_UC);
5486 }
5487
kvm_vcpu_x86_set_ucna(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce,u64 * banks)5488 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5489 {
5490 u64 mcg_cap = vcpu->arch.mcg_cap;
5491
5492 banks[1] = mce->status;
5493 banks[2] = mce->addr;
5494 banks[3] = mce->misc;
5495 vcpu->arch.mcg_status = mce->mcg_status;
5496
5497 if (!(mcg_cap & MCG_CMCI_P) ||
5498 !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5499 return 0;
5500
5501 if (lapic_in_kernel(vcpu))
5502 kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5503
5504 return 0;
5505 }
5506
kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce)5507 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5508 struct kvm_x86_mce *mce)
5509 {
5510 u64 mcg_cap = vcpu->arch.mcg_cap;
5511 unsigned bank_num = mcg_cap & 0xff;
5512 u64 *banks = vcpu->arch.mce_banks;
5513
5514 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5515 return -EINVAL;
5516
5517 banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5518
5519 if (is_ucna(mce))
5520 return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5521
5522 /*
5523 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5524 * reporting is disabled
5525 */
5526 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5527 vcpu->arch.mcg_ctl != ~(u64)0)
5528 return 0;
5529 /*
5530 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5531 * reporting is disabled for the bank
5532 */
5533 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5534 return 0;
5535 if (mce->status & MCI_STATUS_UC) {
5536 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5537 !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
5538 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5539 return 0;
5540 }
5541 if (banks[1] & MCI_STATUS_VAL)
5542 mce->status |= MCI_STATUS_OVER;
5543 banks[2] = mce->addr;
5544 banks[3] = mce->misc;
5545 vcpu->arch.mcg_status = mce->mcg_status;
5546 banks[1] = mce->status;
5547 kvm_queue_exception(vcpu, MC_VECTOR);
5548 } else if (!(banks[1] & MCI_STATUS_VAL)
5549 || !(banks[1] & MCI_STATUS_UC)) {
5550 if (banks[1] & MCI_STATUS_VAL)
5551 mce->status |= MCI_STATUS_OVER;
5552 banks[2] = mce->addr;
5553 banks[3] = mce->misc;
5554 banks[1] = mce->status;
5555 } else
5556 banks[1] |= MCI_STATUS_OVER;
5557 return 0;
5558 }
5559
kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5560 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5561 struct kvm_vcpu_events *events)
5562 {
5563 struct kvm_queued_exception *ex;
5564
5565 process_nmi(vcpu);
5566
5567 #ifdef CONFIG_KVM_SMM
5568 if (kvm_check_request(KVM_REQ_SMI, vcpu))
5569 process_smi(vcpu);
5570 #endif
5571
5572 /*
5573 * KVM's ABI only allows for one exception to be migrated. Luckily,
5574 * the only time there can be two queued exceptions is if there's a
5575 * non-exiting _injected_ exception, and a pending exiting exception.
5576 * In that case, ignore the VM-Exiting exception as it's an extension
5577 * of the injected exception.
5578 */
5579 if (vcpu->arch.exception_vmexit.pending &&
5580 !vcpu->arch.exception.pending &&
5581 !vcpu->arch.exception.injected)
5582 ex = &vcpu->arch.exception_vmexit;
5583 else
5584 ex = &vcpu->arch.exception;
5585
5586 /*
5587 * In guest mode, payload delivery should be deferred if the exception
5588 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5589 * intercepts #PF, ditto for DR6 and #DBs. If the per-VM capability,
5590 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5591 * propagate the payload and so it cannot be safely deferred. Deliver
5592 * the payload if the capability hasn't been requested.
5593 */
5594 if (!vcpu->kvm->arch.exception_payload_enabled &&
5595 ex->pending && ex->has_payload)
5596 kvm_deliver_exception_payload(vcpu, ex);
5597
5598 memset(events, 0, sizeof(*events));
5599
5600 /*
5601 * The API doesn't provide the instruction length for software
5602 * exceptions, so don't report them. As long as the guest RIP
5603 * isn't advanced, we should expect to encounter the exception
5604 * again.
5605 */
5606 if (!kvm_exception_is_soft(ex->vector)) {
5607 events->exception.injected = ex->injected;
5608 events->exception.pending = ex->pending;
5609 /*
5610 * For ABI compatibility, deliberately conflate
5611 * pending and injected exceptions when
5612 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5613 */
5614 if (!vcpu->kvm->arch.exception_payload_enabled)
5615 events->exception.injected |= ex->pending;
5616 }
5617 events->exception.nr = ex->vector;
5618 events->exception.has_error_code = ex->has_error_code;
5619 events->exception.error_code = ex->error_code;
5620 events->exception_has_payload = ex->has_payload;
5621 events->exception_payload = ex->payload;
5622
5623 events->interrupt.injected =
5624 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5625 events->interrupt.nr = vcpu->arch.interrupt.nr;
5626 events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
5627
5628 events->nmi.injected = vcpu->arch.nmi_injected;
5629 events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
5630 events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
5631
5632 /* events->sipi_vector is never valid when reporting to user space */
5633
5634 #ifdef CONFIG_KVM_SMM
5635 events->smi.smm = is_smm(vcpu);
5636 events->smi.pending = vcpu->arch.smi_pending;
5637 events->smi.smm_inside_nmi =
5638 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5639 #endif
5640 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5641
5642 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5643 | KVM_VCPUEVENT_VALID_SHADOW
5644 | KVM_VCPUEVENT_VALID_SMM);
5645 if (vcpu->kvm->arch.exception_payload_enabled)
5646 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5647 if (vcpu->kvm->arch.triple_fault_event) {
5648 events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5649 events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5650 }
5651 }
5652
kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5653 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5654 struct kvm_vcpu_events *events)
5655 {
5656 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5657 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5658 | KVM_VCPUEVENT_VALID_SHADOW
5659 | KVM_VCPUEVENT_VALID_SMM
5660 | KVM_VCPUEVENT_VALID_PAYLOAD
5661 | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5662 return -EINVAL;
5663
5664 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5665 if (!vcpu->kvm->arch.exception_payload_enabled)
5666 return -EINVAL;
5667 if (events->exception.pending)
5668 events->exception.injected = 0;
5669 else
5670 events->exception_has_payload = 0;
5671 } else {
5672 events->exception.pending = 0;
5673 events->exception_has_payload = 0;
5674 }
5675
5676 if ((events->exception.injected || events->exception.pending) &&
5677 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5678 return -EINVAL;
5679
5680 process_nmi(vcpu);
5681
5682 /*
5683 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5684 * morph the exception to a VM-Exit if appropriate. Do this only for
5685 * pending exceptions, already-injected exceptions are not subject to
5686 * intercpetion. Note, userspace that conflates pending and injected
5687 * is hosed, and will incorrectly convert an injected exception into a
5688 * pending exception, which in turn may cause a spurious VM-Exit.
5689 */
5690 vcpu->arch.exception_from_userspace = events->exception.pending;
5691
5692 vcpu->arch.exception_vmexit.pending = false;
5693
5694 vcpu->arch.exception.injected = events->exception.injected;
5695 vcpu->arch.exception.pending = events->exception.pending;
5696 vcpu->arch.exception.vector = events->exception.nr;
5697 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5698 vcpu->arch.exception.error_code = events->exception.error_code;
5699 vcpu->arch.exception.has_payload = events->exception_has_payload;
5700 vcpu->arch.exception.payload = events->exception_payload;
5701
5702 vcpu->arch.interrupt.injected = events->interrupt.injected;
5703 vcpu->arch.interrupt.nr = events->interrupt.nr;
5704 vcpu->arch.interrupt.soft = events->interrupt.soft;
5705 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5706 kvm_x86_call(set_interrupt_shadow)(vcpu,
5707 events->interrupt.shadow);
5708
5709 vcpu->arch.nmi_injected = events->nmi.injected;
5710 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
5711 vcpu->arch.nmi_pending = 0;
5712 atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
5713 if (events->nmi.pending)
5714 kvm_make_request(KVM_REQ_NMI, vcpu);
5715 }
5716 kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
5717
5718 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5719 lapic_in_kernel(vcpu))
5720 vcpu->arch.apic->sipi_vector = events->sipi_vector;
5721
5722 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5723 #ifdef CONFIG_KVM_SMM
5724 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5725 kvm_leave_nested(vcpu);
5726 kvm_smm_changed(vcpu, events->smi.smm);
5727 }
5728
5729 vcpu->arch.smi_pending = events->smi.pending;
5730
5731 if (events->smi.smm) {
5732 if (events->smi.smm_inside_nmi)
5733 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5734 else
5735 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5736 }
5737
5738 #else
5739 if (events->smi.smm || events->smi.pending ||
5740 events->smi.smm_inside_nmi)
5741 return -EINVAL;
5742 #endif
5743
5744 if (lapic_in_kernel(vcpu)) {
5745 if (events->smi.latched_init)
5746 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5747 else
5748 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5749 }
5750 }
5751
5752 if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5753 if (!vcpu->kvm->arch.triple_fault_event)
5754 return -EINVAL;
5755 if (events->triple_fault.pending)
5756 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5757 else
5758 kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5759 }
5760
5761 kvm_make_request(KVM_REQ_EVENT, vcpu);
5762
5763 return 0;
5764 }
5765
kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5766 static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5767 struct kvm_debugregs *dbgregs)
5768 {
5769 unsigned int i;
5770
5771 if (vcpu->kvm->arch.has_protected_state &&
5772 vcpu->arch.guest_state_protected)
5773 return -EINVAL;
5774
5775 memset(dbgregs, 0, sizeof(*dbgregs));
5776
5777 BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5778 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5779 dbgregs->db[i] = vcpu->arch.db[i];
5780
5781 dbgregs->dr6 = vcpu->arch.dr6;
5782 dbgregs->dr7 = vcpu->arch.dr7;
5783 return 0;
5784 }
5785
kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5786 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5787 struct kvm_debugregs *dbgregs)
5788 {
5789 unsigned int i;
5790
5791 if (vcpu->kvm->arch.has_protected_state &&
5792 vcpu->arch.guest_state_protected)
5793 return -EINVAL;
5794
5795 if (dbgregs->flags)
5796 return -EINVAL;
5797
5798 if (!kvm_dr6_valid(dbgregs->dr6))
5799 return -EINVAL;
5800 if (!kvm_dr7_valid(dbgregs->dr7))
5801 return -EINVAL;
5802
5803 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5804 vcpu->arch.db[i] = dbgregs->db[i];
5805
5806 kvm_update_dr0123(vcpu);
5807 vcpu->arch.dr6 = dbgregs->dr6;
5808 vcpu->arch.dr7 = dbgregs->dr7;
5809 kvm_update_dr7(vcpu);
5810
5811 return 0;
5812 }
5813
5814
kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu * vcpu,u8 * state,unsigned int size)5815 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5816 u8 *state, unsigned int size)
5817 {
5818 /*
5819 * Only copy state for features that are enabled for the guest. The
5820 * state itself isn't problematic, but setting bits in the header for
5821 * features that are supported in *this* host but not exposed to the
5822 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5823 * compatible host without the features that are NOT exposed to the
5824 * guest.
5825 *
5826 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5827 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5828 * supported by the host.
5829 */
5830 u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5831 XFEATURE_MASK_FPSSE;
5832
5833 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5834 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5835
5836 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5837 supported_xcr0, vcpu->arch.pkru);
5838 return 0;
5839 }
5840
kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5841 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5842 struct kvm_xsave *guest_xsave)
5843 {
5844 return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5845 sizeof(guest_xsave->region));
5846 }
5847
kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5848 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5849 struct kvm_xsave *guest_xsave)
5850 {
5851 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5852 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5853
5854 return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5855 guest_xsave->region,
5856 kvm_caps.supported_xcr0,
5857 &vcpu->arch.pkru);
5858 }
5859
kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5860 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5861 struct kvm_xcrs *guest_xcrs)
5862 {
5863 if (vcpu->kvm->arch.has_protected_state &&
5864 vcpu->arch.guest_state_protected)
5865 return -EINVAL;
5866
5867 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5868 guest_xcrs->nr_xcrs = 0;
5869 return 0;
5870 }
5871
5872 guest_xcrs->nr_xcrs = 1;
5873 guest_xcrs->flags = 0;
5874 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5875 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5876 return 0;
5877 }
5878
kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5879 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5880 struct kvm_xcrs *guest_xcrs)
5881 {
5882 int i, r = 0;
5883
5884 if (vcpu->kvm->arch.has_protected_state &&
5885 vcpu->arch.guest_state_protected)
5886 return -EINVAL;
5887
5888 if (!boot_cpu_has(X86_FEATURE_XSAVE))
5889 return -EINVAL;
5890
5891 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5892 return -EINVAL;
5893
5894 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5895 /* Only support XCR0 currently */
5896 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5897 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5898 guest_xcrs->xcrs[i].value);
5899 break;
5900 }
5901 if (r)
5902 r = -EINVAL;
5903 return r;
5904 }
5905
5906 /*
5907 * kvm_set_guest_paused() indicates to the guest kernel that it has been
5908 * stopped by the hypervisor. This function will be called from the host only.
5909 * EINVAL is returned when the host attempts to set the flag for a guest that
5910 * does not support pv clocks.
5911 */
kvm_set_guest_paused(struct kvm_vcpu * vcpu)5912 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5913 {
5914 if (!vcpu->arch.pv_time.active)
5915 return -EINVAL;
5916 vcpu->arch.pvclock_set_guest_stopped_request = true;
5917 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5918 return 0;
5919 }
5920
kvm_arch_tsc_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5921 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5922 struct kvm_device_attr *attr)
5923 {
5924 int r;
5925
5926 switch (attr->attr) {
5927 case KVM_VCPU_TSC_OFFSET:
5928 r = 0;
5929 break;
5930 default:
5931 r = -ENXIO;
5932 }
5933
5934 return r;
5935 }
5936
kvm_arch_tsc_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5937 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5938 struct kvm_device_attr *attr)
5939 {
5940 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5941 int r;
5942
5943 switch (attr->attr) {
5944 case KVM_VCPU_TSC_OFFSET:
5945 r = -EFAULT;
5946 if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5947 break;
5948 r = 0;
5949 break;
5950 default:
5951 r = -ENXIO;
5952 }
5953
5954 return r;
5955 }
5956
kvm_arch_tsc_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5957 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5958 struct kvm_device_attr *attr)
5959 {
5960 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5961 struct kvm *kvm = vcpu->kvm;
5962 int r;
5963
5964 switch (attr->attr) {
5965 case KVM_VCPU_TSC_OFFSET: {
5966 u64 offset, tsc, ns;
5967 unsigned long flags;
5968 bool matched;
5969
5970 r = -EFAULT;
5971 if (get_user(offset, uaddr))
5972 break;
5973
5974 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5975
5976 matched = (vcpu->arch.virtual_tsc_khz &&
5977 kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5978 kvm->arch.last_tsc_offset == offset);
5979
5980 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5981 ns = get_kvmclock_base_ns();
5982
5983 __kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched, true);
5984 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5985
5986 r = 0;
5987 break;
5988 }
5989 default:
5990 r = -ENXIO;
5991 }
5992
5993 return r;
5994 }
5995
kvm_vcpu_ioctl_device_attr(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)5996 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5997 unsigned int ioctl,
5998 void __user *argp)
5999 {
6000 struct kvm_device_attr attr;
6001 int r;
6002
6003 if (copy_from_user(&attr, argp, sizeof(attr)))
6004 return -EFAULT;
6005
6006 if (attr.group != KVM_VCPU_TSC_CTRL)
6007 return -ENXIO;
6008
6009 switch (ioctl) {
6010 case KVM_HAS_DEVICE_ATTR:
6011 r = kvm_arch_tsc_has_attr(vcpu, &attr);
6012 break;
6013 case KVM_GET_DEVICE_ATTR:
6014 r = kvm_arch_tsc_get_attr(vcpu, &attr);
6015 break;
6016 case KVM_SET_DEVICE_ATTR:
6017 r = kvm_arch_tsc_set_attr(vcpu, &attr);
6018 break;
6019 }
6020
6021 return r;
6022 }
6023
kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu * vcpu,struct kvm_enable_cap * cap)6024 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
6025 struct kvm_enable_cap *cap)
6026 {
6027 if (cap->flags)
6028 return -EINVAL;
6029
6030 switch (cap->cap) {
6031 #ifdef CONFIG_KVM_HYPERV
6032 case KVM_CAP_HYPERV_SYNIC2:
6033 if (cap->args[0])
6034 return -EINVAL;
6035 fallthrough;
6036
6037 case KVM_CAP_HYPERV_SYNIC:
6038 if (!irqchip_in_kernel(vcpu->kvm))
6039 return -EINVAL;
6040 return kvm_hv_activate_synic(vcpu, cap->cap ==
6041 KVM_CAP_HYPERV_SYNIC2);
6042 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
6043 {
6044 int r;
6045 uint16_t vmcs_version;
6046 void __user *user_ptr;
6047
6048 if (!kvm_x86_ops.nested_ops->enable_evmcs)
6049 return -ENOTTY;
6050 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
6051 if (!r) {
6052 user_ptr = (void __user *)(uintptr_t)cap->args[0];
6053 if (copy_to_user(user_ptr, &vmcs_version,
6054 sizeof(vmcs_version)))
6055 r = -EFAULT;
6056 }
6057 return r;
6058 }
6059 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
6060 if (!kvm_x86_ops.enable_l2_tlb_flush)
6061 return -ENOTTY;
6062
6063 return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
6064
6065 case KVM_CAP_HYPERV_ENFORCE_CPUID:
6066 return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
6067 #endif
6068
6069 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
6070 vcpu->arch.pv_cpuid.enforce = cap->args[0];
6071 return 0;
6072 default:
6073 return -EINVAL;
6074 }
6075 }
6076
6077 struct kvm_x86_reg_id {
6078 __u32 index;
6079 __u8 type;
6080 __u8 rsvd1;
6081 __u8 rsvd2:4;
6082 __u8 size:4;
6083 __u8 x86;
6084 };
6085
kvm_translate_kvm_reg(struct kvm_vcpu * vcpu,struct kvm_x86_reg_id * reg)6086 static int kvm_translate_kvm_reg(struct kvm_vcpu *vcpu,
6087 struct kvm_x86_reg_id *reg)
6088 {
6089 switch (reg->index) {
6090 case KVM_REG_GUEST_SSP:
6091 /*
6092 * FIXME: If host-initiated accesses are ever exempted from
6093 * ignore_msrs (in kvm_do_msr_access()), drop this manual check
6094 * and rely on KVM's standard checks to reject accesses to regs
6095 * that don't exist.
6096 */
6097 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
6098 return -EINVAL;
6099
6100 reg->type = KVM_X86_REG_TYPE_MSR;
6101 reg->index = MSR_KVM_INTERNAL_GUEST_SSP;
6102 break;
6103 default:
6104 return -EINVAL;
6105 }
6106 return 0;
6107 }
6108
kvm_get_one_msr(struct kvm_vcpu * vcpu,u32 msr,u64 __user * user_val)6109 static int kvm_get_one_msr(struct kvm_vcpu *vcpu, u32 msr, u64 __user *user_val)
6110 {
6111 u64 val;
6112
6113 if (do_get_msr(vcpu, msr, &val))
6114 return -EINVAL;
6115
6116 if (put_user(val, user_val))
6117 return -EFAULT;
6118
6119 return 0;
6120 }
6121
kvm_set_one_msr(struct kvm_vcpu * vcpu,u32 msr,u64 __user * user_val)6122 static int kvm_set_one_msr(struct kvm_vcpu *vcpu, u32 msr, u64 __user *user_val)
6123 {
6124 u64 val;
6125
6126 if (get_user(val, user_val))
6127 return -EFAULT;
6128
6129 if (do_set_msr(vcpu, msr, &val))
6130 return -EINVAL;
6131
6132 return 0;
6133 }
6134
kvm_get_set_one_reg(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)6135 static int kvm_get_set_one_reg(struct kvm_vcpu *vcpu, unsigned int ioctl,
6136 void __user *argp)
6137 {
6138 struct kvm_one_reg one_reg;
6139 struct kvm_x86_reg_id *reg;
6140 u64 __user *user_val;
6141 bool load_fpu;
6142 int r;
6143
6144 if (copy_from_user(&one_reg, argp, sizeof(one_reg)))
6145 return -EFAULT;
6146
6147 if ((one_reg.id & KVM_REG_ARCH_MASK) != KVM_REG_X86)
6148 return -EINVAL;
6149
6150 reg = (struct kvm_x86_reg_id *)&one_reg.id;
6151 if (reg->rsvd1 || reg->rsvd2)
6152 return -EINVAL;
6153
6154 if (reg->type == KVM_X86_REG_TYPE_KVM) {
6155 r = kvm_translate_kvm_reg(vcpu, reg);
6156 if (r)
6157 return r;
6158 }
6159
6160 if (reg->type != KVM_X86_REG_TYPE_MSR)
6161 return -EINVAL;
6162
6163 if ((one_reg.id & KVM_REG_SIZE_MASK) != KVM_REG_SIZE_U64)
6164 return -EINVAL;
6165
6166 guard(srcu)(&vcpu->kvm->srcu);
6167
6168 load_fpu = is_xstate_managed_msr(vcpu, reg->index);
6169 if (load_fpu)
6170 kvm_load_guest_fpu(vcpu);
6171
6172 user_val = u64_to_user_ptr(one_reg.addr);
6173 if (ioctl == KVM_GET_ONE_REG)
6174 r = kvm_get_one_msr(vcpu, reg->index, user_val);
6175 else
6176 r = kvm_set_one_msr(vcpu, reg->index, user_val);
6177
6178 if (load_fpu)
6179 kvm_put_guest_fpu(vcpu);
6180 return r;
6181 }
6182
kvm_get_reg_list(struct kvm_vcpu * vcpu,struct kvm_reg_list __user * user_list)6183 static int kvm_get_reg_list(struct kvm_vcpu *vcpu,
6184 struct kvm_reg_list __user *user_list)
6185 {
6186 u64 nr_regs = guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) ? 1 : 0;
6187 u64 user_nr_regs;
6188
6189 if (get_user(user_nr_regs, &user_list->n))
6190 return -EFAULT;
6191
6192 if (put_user(nr_regs, &user_list->n))
6193 return -EFAULT;
6194
6195 if (user_nr_regs < nr_regs)
6196 return -E2BIG;
6197
6198 if (nr_regs &&
6199 put_user(KVM_X86_REG_KVM(KVM_REG_GUEST_SSP), &user_list->reg[0]))
6200 return -EFAULT;
6201
6202 return 0;
6203 }
6204
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)6205 long kvm_arch_vcpu_ioctl(struct file *filp,
6206 unsigned int ioctl, unsigned long arg)
6207 {
6208 struct kvm_vcpu *vcpu = filp->private_data;
6209 void __user *argp = (void __user *)arg;
6210 int r;
6211 union {
6212 struct kvm_sregs2 *sregs2;
6213 struct kvm_lapic_state *lapic;
6214 struct kvm_xsave *xsave;
6215 struct kvm_xcrs *xcrs;
6216 void *buffer;
6217 } u;
6218
6219 vcpu_load(vcpu);
6220
6221 u.buffer = NULL;
6222 switch (ioctl) {
6223 case KVM_GET_LAPIC: {
6224 r = -EINVAL;
6225 if (!lapic_in_kernel(vcpu))
6226 goto out;
6227 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
6228
6229 r = -ENOMEM;
6230 if (!u.lapic)
6231 goto out;
6232 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
6233 if (r)
6234 goto out;
6235 r = -EFAULT;
6236 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
6237 goto out;
6238 r = 0;
6239 break;
6240 }
6241 case KVM_SET_LAPIC: {
6242 r = -EINVAL;
6243 if (!lapic_in_kernel(vcpu))
6244 goto out;
6245 u.lapic = memdup_user(argp, sizeof(*u.lapic));
6246 if (IS_ERR(u.lapic)) {
6247 r = PTR_ERR(u.lapic);
6248 goto out_nofree;
6249 }
6250
6251 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
6252 break;
6253 }
6254 case KVM_INTERRUPT: {
6255 struct kvm_interrupt irq;
6256
6257 r = -EFAULT;
6258 if (copy_from_user(&irq, argp, sizeof(irq)))
6259 goto out;
6260 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
6261 break;
6262 }
6263 case KVM_NMI: {
6264 r = kvm_vcpu_ioctl_nmi(vcpu);
6265 break;
6266 }
6267 case KVM_SMI: {
6268 r = kvm_inject_smi(vcpu);
6269 break;
6270 }
6271 case KVM_SET_CPUID: {
6272 struct kvm_cpuid __user *cpuid_arg = argp;
6273 struct kvm_cpuid cpuid;
6274
6275 r = -EFAULT;
6276 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6277 goto out;
6278 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
6279 break;
6280 }
6281 case KVM_SET_CPUID2: {
6282 struct kvm_cpuid2 __user *cpuid_arg = argp;
6283 struct kvm_cpuid2 cpuid;
6284
6285 r = -EFAULT;
6286 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6287 goto out;
6288 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
6289 cpuid_arg->entries);
6290 break;
6291 }
6292 case KVM_GET_CPUID2: {
6293 struct kvm_cpuid2 __user *cpuid_arg = argp;
6294 struct kvm_cpuid2 cpuid;
6295
6296 r = -EFAULT;
6297 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6298 goto out;
6299 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
6300 cpuid_arg->entries);
6301 if (r)
6302 goto out;
6303 r = -EFAULT;
6304 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
6305 goto out;
6306 r = 0;
6307 break;
6308 }
6309 case KVM_GET_MSRS: {
6310 int idx = srcu_read_lock(&vcpu->kvm->srcu);
6311 r = msr_io(vcpu, argp, do_get_msr, 1);
6312 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6313 break;
6314 }
6315 case KVM_SET_MSRS: {
6316 int idx = srcu_read_lock(&vcpu->kvm->srcu);
6317 r = msr_io(vcpu, argp, do_set_msr, 0);
6318 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6319 break;
6320 }
6321 case KVM_GET_ONE_REG:
6322 case KVM_SET_ONE_REG:
6323 r = kvm_get_set_one_reg(vcpu, ioctl, argp);
6324 break;
6325 case KVM_GET_REG_LIST:
6326 r = kvm_get_reg_list(vcpu, argp);
6327 break;
6328 case KVM_TPR_ACCESS_REPORTING: {
6329 struct kvm_tpr_access_ctl tac;
6330
6331 r = -EFAULT;
6332 if (copy_from_user(&tac, argp, sizeof(tac)))
6333 goto out;
6334 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
6335 if (r)
6336 goto out;
6337 r = -EFAULT;
6338 if (copy_to_user(argp, &tac, sizeof(tac)))
6339 goto out;
6340 r = 0;
6341 break;
6342 };
6343 case KVM_SET_VAPIC_ADDR: {
6344 struct kvm_vapic_addr va;
6345 int idx;
6346
6347 r = -EINVAL;
6348 if (!lapic_in_kernel(vcpu))
6349 goto out;
6350 r = -EFAULT;
6351 if (copy_from_user(&va, argp, sizeof(va)))
6352 goto out;
6353 idx = srcu_read_lock(&vcpu->kvm->srcu);
6354 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
6355 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6356 break;
6357 }
6358 case KVM_X86_SETUP_MCE: {
6359 u64 mcg_cap;
6360
6361 r = -EFAULT;
6362 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
6363 goto out;
6364 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6365 break;
6366 }
6367 case KVM_X86_SET_MCE: {
6368 struct kvm_x86_mce mce;
6369
6370 r = -EFAULT;
6371 if (copy_from_user(&mce, argp, sizeof(mce)))
6372 goto out;
6373 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6374 break;
6375 }
6376 case KVM_GET_VCPU_EVENTS: {
6377 struct kvm_vcpu_events events;
6378
6379 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6380
6381 r = -EFAULT;
6382 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6383 break;
6384 r = 0;
6385 break;
6386 }
6387 case KVM_SET_VCPU_EVENTS: {
6388 struct kvm_vcpu_events events;
6389
6390 r = -EFAULT;
6391 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6392 break;
6393
6394 kvm_vcpu_srcu_read_lock(vcpu);
6395 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
6396 kvm_vcpu_srcu_read_unlock(vcpu);
6397 break;
6398 }
6399 case KVM_GET_DEBUGREGS: {
6400 struct kvm_debugregs dbgregs;
6401
6402 r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6403 if (r < 0)
6404 break;
6405
6406 r = -EFAULT;
6407 if (copy_to_user(argp, &dbgregs,
6408 sizeof(struct kvm_debugregs)))
6409 break;
6410 r = 0;
6411 break;
6412 }
6413 case KVM_SET_DEBUGREGS: {
6414 struct kvm_debugregs dbgregs;
6415
6416 r = -EFAULT;
6417 if (copy_from_user(&dbgregs, argp,
6418 sizeof(struct kvm_debugregs)))
6419 break;
6420
6421 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6422 break;
6423 }
6424 case KVM_GET_XSAVE: {
6425 r = -EINVAL;
6426 if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6427 break;
6428
6429 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
6430 r = -ENOMEM;
6431 if (!u.xsave)
6432 break;
6433
6434 r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6435 if (r < 0)
6436 break;
6437
6438 r = -EFAULT;
6439 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
6440 break;
6441 r = 0;
6442 break;
6443 }
6444 case KVM_SET_XSAVE: {
6445 int size = vcpu->arch.guest_fpu.uabi_size;
6446
6447 u.xsave = memdup_user(argp, size);
6448 if (IS_ERR(u.xsave)) {
6449 r = PTR_ERR(u.xsave);
6450 goto out_nofree;
6451 }
6452
6453 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
6454 break;
6455 }
6456
6457 case KVM_GET_XSAVE2: {
6458 int size = vcpu->arch.guest_fpu.uabi_size;
6459
6460 u.xsave = kzalloc(size, GFP_KERNEL);
6461 r = -ENOMEM;
6462 if (!u.xsave)
6463 break;
6464
6465 r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6466 if (r < 0)
6467 break;
6468
6469 r = -EFAULT;
6470 if (copy_to_user(argp, u.xsave, size))
6471 break;
6472
6473 r = 0;
6474 break;
6475 }
6476
6477 case KVM_GET_XCRS: {
6478 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
6479 r = -ENOMEM;
6480 if (!u.xcrs)
6481 break;
6482
6483 r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6484 if (r < 0)
6485 break;
6486
6487 r = -EFAULT;
6488 if (copy_to_user(argp, u.xcrs,
6489 sizeof(struct kvm_xcrs)))
6490 break;
6491 r = 0;
6492 break;
6493 }
6494 case KVM_SET_XCRS: {
6495 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
6496 if (IS_ERR(u.xcrs)) {
6497 r = PTR_ERR(u.xcrs);
6498 goto out_nofree;
6499 }
6500
6501 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
6502 break;
6503 }
6504 case KVM_SET_TSC_KHZ: {
6505 u32 user_tsc_khz;
6506
6507 r = -EINVAL;
6508
6509 if (vcpu->arch.guest_tsc_protected)
6510 goto out;
6511
6512 user_tsc_khz = (u32)arg;
6513
6514 if (kvm_caps.has_tsc_control &&
6515 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6516 goto out;
6517
6518 if (user_tsc_khz == 0)
6519 user_tsc_khz = tsc_khz;
6520
6521 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6522 r = 0;
6523
6524 goto out;
6525 }
6526 case KVM_GET_TSC_KHZ: {
6527 r = vcpu->arch.virtual_tsc_khz;
6528 goto out;
6529 }
6530 case KVM_KVMCLOCK_CTRL: {
6531 r = kvm_set_guest_paused(vcpu);
6532 goto out;
6533 }
6534 case KVM_ENABLE_CAP: {
6535 struct kvm_enable_cap cap;
6536
6537 r = -EFAULT;
6538 if (copy_from_user(&cap, argp, sizeof(cap)))
6539 goto out;
6540 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6541 break;
6542 }
6543 case KVM_GET_NESTED_STATE: {
6544 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6545 u32 user_data_size;
6546
6547 r = -EINVAL;
6548 if (!kvm_x86_ops.nested_ops->get_state)
6549 break;
6550
6551 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
6552 r = -EFAULT;
6553 if (get_user(user_data_size, &user_kvm_nested_state->size))
6554 break;
6555
6556 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6557 user_data_size);
6558 if (r < 0)
6559 break;
6560
6561 if (r > user_data_size) {
6562 if (put_user(r, &user_kvm_nested_state->size))
6563 r = -EFAULT;
6564 else
6565 r = -E2BIG;
6566 break;
6567 }
6568
6569 r = 0;
6570 break;
6571 }
6572 case KVM_SET_NESTED_STATE: {
6573 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6574 struct kvm_nested_state kvm_state;
6575 int idx;
6576
6577 r = -EINVAL;
6578 if (!kvm_x86_ops.nested_ops->set_state)
6579 break;
6580
6581 r = -EFAULT;
6582 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
6583 break;
6584
6585 r = -EINVAL;
6586 if (kvm_state.size < sizeof(kvm_state))
6587 break;
6588
6589 if (kvm_state.flags &
6590 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
6591 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6592 | KVM_STATE_NESTED_GIF_SET))
6593 break;
6594
6595 /* nested_run_pending implies guest_mode. */
6596 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6597 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
6598 break;
6599
6600 idx = srcu_read_lock(&vcpu->kvm->srcu);
6601 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
6602 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6603 break;
6604 }
6605 #ifdef CONFIG_KVM_HYPERV
6606 case KVM_GET_SUPPORTED_HV_CPUID:
6607 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
6608 break;
6609 #endif
6610 #ifdef CONFIG_KVM_XEN
6611 case KVM_XEN_VCPU_GET_ATTR: {
6612 struct kvm_xen_vcpu_attr xva;
6613
6614 r = -EFAULT;
6615 if (copy_from_user(&xva, argp, sizeof(xva)))
6616 goto out;
6617 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6618 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6619 r = -EFAULT;
6620 break;
6621 }
6622 case KVM_XEN_VCPU_SET_ATTR: {
6623 struct kvm_xen_vcpu_attr xva;
6624
6625 r = -EFAULT;
6626 if (copy_from_user(&xva, argp, sizeof(xva)))
6627 goto out;
6628 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6629 break;
6630 }
6631 #endif
6632 case KVM_GET_SREGS2: {
6633 r = -EINVAL;
6634 if (vcpu->kvm->arch.has_protected_state &&
6635 vcpu->arch.guest_state_protected)
6636 goto out;
6637
6638 u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
6639 r = -ENOMEM;
6640 if (!u.sregs2)
6641 goto out;
6642 __get_sregs2(vcpu, u.sregs2);
6643 r = -EFAULT;
6644 if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6645 goto out;
6646 r = 0;
6647 break;
6648 }
6649 case KVM_SET_SREGS2: {
6650 r = -EINVAL;
6651 if (vcpu->kvm->arch.has_protected_state &&
6652 vcpu->arch.guest_state_protected)
6653 goto out;
6654
6655 u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6656 if (IS_ERR(u.sregs2)) {
6657 r = PTR_ERR(u.sregs2);
6658 u.sregs2 = NULL;
6659 goto out;
6660 }
6661 r = __set_sregs2(vcpu, u.sregs2);
6662 break;
6663 }
6664 case KVM_HAS_DEVICE_ATTR:
6665 case KVM_GET_DEVICE_ATTR:
6666 case KVM_SET_DEVICE_ATTR:
6667 r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6668 break;
6669 case KVM_MEMORY_ENCRYPT_OP:
6670 r = -ENOTTY;
6671 if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
6672 goto out;
6673 r = kvm_x86_ops.vcpu_mem_enc_ioctl(vcpu, argp);
6674 break;
6675 default:
6676 r = -EINVAL;
6677 }
6678 out:
6679 kfree(u.buffer);
6680 out_nofree:
6681 vcpu_put(vcpu);
6682 return r;
6683 }
6684
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)6685 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6686 {
6687 return VM_FAULT_SIGBUS;
6688 }
6689
kvm_vm_ioctl_set_tss_addr(struct kvm * kvm,unsigned long addr)6690 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6691 {
6692 int ret;
6693
6694 if (addr > (unsigned int)(-3 * PAGE_SIZE))
6695 return -EINVAL;
6696 ret = kvm_x86_call(set_tss_addr)(kvm, addr);
6697 return ret;
6698 }
6699
kvm_vm_ioctl_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)6700 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6701 u64 ident_addr)
6702 {
6703 return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
6704 }
6705
kvm_vm_ioctl_set_nr_mmu_pages(struct kvm * kvm,unsigned long kvm_nr_mmu_pages)6706 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6707 unsigned long kvm_nr_mmu_pages)
6708 {
6709 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6710 return -EINVAL;
6711
6712 mutex_lock(&kvm->slots_lock);
6713
6714 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6715 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6716
6717 mutex_unlock(&kvm->slots_lock);
6718 return 0;
6719 }
6720
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)6721 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6722 {
6723
6724 /*
6725 * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
6726 * before reporting dirty_bitmap to userspace. KVM flushes the buffers
6727 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6728 * VM-Exit.
6729 */
6730 struct kvm_vcpu *vcpu;
6731 unsigned long i;
6732
6733 if (!kvm->arch.cpu_dirty_log_size)
6734 return;
6735
6736 kvm_for_each_vcpu(i, vcpu, kvm)
6737 kvm_vcpu_kick(vcpu);
6738 }
6739
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)6740 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6741 struct kvm_enable_cap *cap)
6742 {
6743 int r;
6744
6745 if (cap->flags)
6746 return -EINVAL;
6747
6748 switch (cap->cap) {
6749 case KVM_CAP_DISABLE_QUIRKS2:
6750 r = -EINVAL;
6751 if (cap->args[0] & ~kvm_caps.supported_quirks)
6752 break;
6753 fallthrough;
6754 case KVM_CAP_DISABLE_QUIRKS:
6755 kvm->arch.disabled_quirks |= cap->args[0] & kvm_caps.supported_quirks;
6756 r = 0;
6757 break;
6758 case KVM_CAP_SPLIT_IRQCHIP: {
6759 mutex_lock(&kvm->lock);
6760 r = -EINVAL;
6761 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6762 goto split_irqchip_unlock;
6763 r = -EEXIST;
6764 if (irqchip_in_kernel(kvm))
6765 goto split_irqchip_unlock;
6766 if (kvm->created_vcpus)
6767 goto split_irqchip_unlock;
6768 /* Pairs with irqchip_in_kernel. */
6769 smp_wmb();
6770 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6771 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6772 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6773 r = 0;
6774 split_irqchip_unlock:
6775 mutex_unlock(&kvm->lock);
6776 break;
6777 }
6778 case KVM_CAP_X2APIC_API:
6779 r = -EINVAL;
6780 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6781 break;
6782
6783 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6784 kvm->arch.x2apic_format = true;
6785 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6786 kvm->arch.x2apic_broadcast_quirk_disabled = true;
6787
6788 r = 0;
6789 break;
6790 case KVM_CAP_X86_DISABLE_EXITS:
6791 r = -EINVAL;
6792 if (cap->args[0] & ~kvm_get_allowed_disable_exits())
6793 break;
6794
6795 mutex_lock(&kvm->lock);
6796 if (kvm->created_vcpus)
6797 goto disable_exits_unlock;
6798
6799 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6800 "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6801
6802 if (!mitigate_smt_rsb && boot_cpu_has_bug(X86_BUG_SMT_RSB) &&
6803 cpu_smt_possible() &&
6804 (cap->args[0] & ~(KVM_X86_DISABLE_EXITS_PAUSE |
6805 KVM_X86_DISABLE_EXITS_APERFMPERF)))
6806 pr_warn_once(SMT_RSB_MSG);
6807
6808 kvm_disable_exits(kvm, cap->args[0]);
6809 r = 0;
6810 disable_exits_unlock:
6811 mutex_unlock(&kvm->lock);
6812 break;
6813 case KVM_CAP_MSR_PLATFORM_INFO:
6814 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6815 r = 0;
6816 break;
6817 case KVM_CAP_EXCEPTION_PAYLOAD:
6818 kvm->arch.exception_payload_enabled = cap->args[0];
6819 r = 0;
6820 break;
6821 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6822 kvm->arch.triple_fault_event = cap->args[0];
6823 r = 0;
6824 break;
6825 case KVM_CAP_X86_USER_SPACE_MSR:
6826 r = -EINVAL;
6827 if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
6828 break;
6829 kvm->arch.user_space_msr_mask = cap->args[0];
6830 r = 0;
6831 break;
6832 case KVM_CAP_X86_BUS_LOCK_EXIT:
6833 r = -EINVAL;
6834 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6835 break;
6836
6837 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6838 (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6839 break;
6840
6841 if (kvm_caps.has_bus_lock_exit &&
6842 cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6843 kvm->arch.bus_lock_detection_enabled = true;
6844 r = 0;
6845 break;
6846 #ifdef CONFIG_X86_SGX_KVM
6847 case KVM_CAP_SGX_ATTRIBUTE: {
6848 unsigned long allowed_attributes = 0;
6849
6850 r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6851 if (r)
6852 break;
6853
6854 /* KVM only supports the PROVISIONKEY privileged attribute. */
6855 if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6856 !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6857 kvm->arch.sgx_provisioning_allowed = true;
6858 else
6859 r = -EINVAL;
6860 break;
6861 }
6862 #endif
6863 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6864 r = -EINVAL;
6865 if (!kvm_x86_ops.vm_copy_enc_context_from)
6866 break;
6867
6868 r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
6869 break;
6870 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6871 r = -EINVAL;
6872 if (!kvm_x86_ops.vm_move_enc_context_from)
6873 break;
6874
6875 r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
6876 break;
6877 case KVM_CAP_EXIT_HYPERCALL:
6878 if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6879 r = -EINVAL;
6880 break;
6881 }
6882 kvm->arch.hypercall_exit_enabled = cap->args[0];
6883 r = 0;
6884 break;
6885 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6886 r = -EINVAL;
6887 if (cap->args[0] & ~1)
6888 break;
6889 kvm->arch.exit_on_emulation_error = cap->args[0];
6890 r = 0;
6891 break;
6892 case KVM_CAP_PMU_CAPABILITY:
6893 r = -EINVAL;
6894 if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6895 break;
6896
6897 mutex_lock(&kvm->lock);
6898 if (!kvm->created_vcpus) {
6899 kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6900 r = 0;
6901 }
6902 mutex_unlock(&kvm->lock);
6903 break;
6904 case KVM_CAP_MAX_VCPU_ID:
6905 r = -EINVAL;
6906 if (cap->args[0] > KVM_MAX_VCPU_IDS)
6907 break;
6908
6909 mutex_lock(&kvm->lock);
6910 if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
6911 ;
6912 } else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6913 r = 0;
6914 } else if (!kvm->arch.max_vcpu_ids) {
6915 kvm->arch.max_vcpu_ids = cap->args[0];
6916 r = 0;
6917 }
6918 mutex_unlock(&kvm->lock);
6919 break;
6920 case KVM_CAP_X86_NOTIFY_VMEXIT:
6921 r = -EINVAL;
6922 if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6923 break;
6924 if (!kvm_caps.has_notify_vmexit)
6925 break;
6926 if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6927 break;
6928 mutex_lock(&kvm->lock);
6929 if (!kvm->created_vcpus) {
6930 kvm->arch.notify_window = cap->args[0] >> 32;
6931 kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6932 r = 0;
6933 }
6934 mutex_unlock(&kvm->lock);
6935 break;
6936 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6937 r = -EINVAL;
6938
6939 /*
6940 * Since the risk of disabling NX hugepages is a guest crashing
6941 * the system, ensure the userspace process has permission to
6942 * reboot the system.
6943 *
6944 * Note that unlike the reboot() syscall, the process must have
6945 * this capability in the root namespace because exposing
6946 * /dev/kvm into a container does not limit the scope of the
6947 * iTLB multihit bug to that container. In other words,
6948 * this must use capable(), not ns_capable().
6949 */
6950 if (!capable(CAP_SYS_BOOT)) {
6951 r = -EPERM;
6952 break;
6953 }
6954
6955 if (cap->args[0])
6956 break;
6957
6958 mutex_lock(&kvm->lock);
6959 if (!kvm->created_vcpus) {
6960 kvm->arch.disable_nx_huge_pages = true;
6961 r = 0;
6962 }
6963 mutex_unlock(&kvm->lock);
6964 break;
6965 case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
6966 u64 bus_cycle_ns = cap->args[0];
6967 u64 unused;
6968
6969 /*
6970 * Guard against overflow in tmict_to_ns(). 128 is the highest
6971 * divide value that can be programmed in APIC_TDCR.
6972 */
6973 r = -EINVAL;
6974 if (!bus_cycle_ns ||
6975 check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
6976 break;
6977
6978 r = 0;
6979 mutex_lock(&kvm->lock);
6980 if (!irqchip_in_kernel(kvm))
6981 r = -ENXIO;
6982 else if (kvm->created_vcpus)
6983 r = -EINVAL;
6984 else
6985 kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
6986 mutex_unlock(&kvm->lock);
6987 break;
6988 }
6989 default:
6990 r = -EINVAL;
6991 break;
6992 }
6993 return r;
6994 }
6995
kvm_alloc_msr_filter(bool default_allow)6996 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6997 {
6998 struct kvm_x86_msr_filter *msr_filter;
6999
7000 msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
7001 if (!msr_filter)
7002 return NULL;
7003
7004 msr_filter->default_allow = default_allow;
7005 return msr_filter;
7006 }
7007
kvm_free_msr_filter(struct kvm_x86_msr_filter * msr_filter)7008 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
7009 {
7010 u32 i;
7011
7012 if (!msr_filter)
7013 return;
7014
7015 for (i = 0; i < msr_filter->count; i++)
7016 kfree(msr_filter->ranges[i].bitmap);
7017
7018 kfree(msr_filter);
7019 }
7020
kvm_add_msr_filter(struct kvm_x86_msr_filter * msr_filter,struct kvm_msr_filter_range * user_range)7021 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
7022 struct kvm_msr_filter_range *user_range)
7023 {
7024 unsigned long *bitmap;
7025 size_t bitmap_size;
7026
7027 if (!user_range->nmsrs)
7028 return 0;
7029
7030 if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
7031 return -EINVAL;
7032
7033 if (!user_range->flags)
7034 return -EINVAL;
7035
7036 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
7037 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
7038 return -EINVAL;
7039
7040 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
7041 if (IS_ERR(bitmap))
7042 return PTR_ERR(bitmap);
7043
7044 msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
7045 .flags = user_range->flags,
7046 .base = user_range->base,
7047 .nmsrs = user_range->nmsrs,
7048 .bitmap = bitmap,
7049 };
7050
7051 msr_filter->count++;
7052 return 0;
7053 }
7054
kvm_vm_ioctl_set_msr_filter(struct kvm * kvm,struct kvm_msr_filter * filter)7055 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
7056 struct kvm_msr_filter *filter)
7057 {
7058 struct kvm_x86_msr_filter *new_filter, *old_filter;
7059 bool default_allow;
7060 bool empty = true;
7061 int r;
7062 u32 i;
7063
7064 if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
7065 return -EINVAL;
7066
7067 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
7068 empty &= !filter->ranges[i].nmsrs;
7069
7070 default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
7071 if (empty && !default_allow)
7072 return -EINVAL;
7073
7074 new_filter = kvm_alloc_msr_filter(default_allow);
7075 if (!new_filter)
7076 return -ENOMEM;
7077
7078 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
7079 r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
7080 if (r) {
7081 kvm_free_msr_filter(new_filter);
7082 return r;
7083 }
7084 }
7085
7086 mutex_lock(&kvm->lock);
7087 old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
7088 mutex_is_locked(&kvm->lock));
7089 mutex_unlock(&kvm->lock);
7090 synchronize_srcu(&kvm->srcu);
7091
7092 kvm_free_msr_filter(old_filter);
7093
7094 /*
7095 * Recalc MSR intercepts as userspace may want to intercept accesses to
7096 * MSRs that KVM would otherwise pass through to the guest.
7097 */
7098 kvm_make_all_cpus_request(kvm, KVM_REQ_RECALC_INTERCEPTS);
7099
7100 return 0;
7101 }
7102
7103 #ifdef CONFIG_KVM_COMPAT
7104 /* for KVM_X86_SET_MSR_FILTER */
7105 struct kvm_msr_filter_range_compat {
7106 __u32 flags;
7107 __u32 nmsrs;
7108 __u32 base;
7109 __u32 bitmap;
7110 };
7111
7112 struct kvm_msr_filter_compat {
7113 __u32 flags;
7114 struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
7115 };
7116
7117 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
7118
kvm_arch_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7119 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
7120 unsigned long arg)
7121 {
7122 void __user *argp = (void __user *)arg;
7123 struct kvm *kvm = filp->private_data;
7124 long r = -ENOTTY;
7125
7126 switch (ioctl) {
7127 case KVM_X86_SET_MSR_FILTER_COMPAT: {
7128 struct kvm_msr_filter __user *user_msr_filter = argp;
7129 struct kvm_msr_filter_compat filter_compat;
7130 struct kvm_msr_filter filter;
7131 int i;
7132
7133 if (copy_from_user(&filter_compat, user_msr_filter,
7134 sizeof(filter_compat)))
7135 return -EFAULT;
7136
7137 filter.flags = filter_compat.flags;
7138 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
7139 struct kvm_msr_filter_range_compat *cr;
7140
7141 cr = &filter_compat.ranges[i];
7142 filter.ranges[i] = (struct kvm_msr_filter_range) {
7143 .flags = cr->flags,
7144 .nmsrs = cr->nmsrs,
7145 .base = cr->base,
7146 .bitmap = (__u8 *)(ulong)cr->bitmap,
7147 };
7148 }
7149
7150 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7151 break;
7152 }
7153 }
7154
7155 return r;
7156 }
7157 #endif
7158
7159 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_arch_suspend_notifier(struct kvm * kvm)7160 static int kvm_arch_suspend_notifier(struct kvm *kvm)
7161 {
7162 struct kvm_vcpu *vcpu;
7163 unsigned long i;
7164
7165 /*
7166 * Ignore the return, marking the guest paused only "fails" if the vCPU
7167 * isn't using kvmclock; continuing on is correct and desirable.
7168 */
7169 kvm_for_each_vcpu(i, vcpu, kvm)
7170 (void)kvm_set_guest_paused(vcpu);
7171
7172 return NOTIFY_DONE;
7173 }
7174
kvm_arch_pm_notifier(struct kvm * kvm,unsigned long state)7175 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
7176 {
7177 switch (state) {
7178 case PM_HIBERNATION_PREPARE:
7179 case PM_SUSPEND_PREPARE:
7180 return kvm_arch_suspend_notifier(kvm);
7181 }
7182
7183 return NOTIFY_DONE;
7184 }
7185 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
7186
kvm_vm_ioctl_get_clock(struct kvm * kvm,void __user * argp)7187 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
7188 {
7189 struct kvm_clock_data data = { 0 };
7190
7191 get_kvmclock(kvm, &data);
7192 if (copy_to_user(argp, &data, sizeof(data)))
7193 return -EFAULT;
7194
7195 return 0;
7196 }
7197
kvm_vm_ioctl_set_clock(struct kvm * kvm,void __user * argp)7198 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
7199 {
7200 struct kvm_arch *ka = &kvm->arch;
7201 struct kvm_clock_data data;
7202 u64 now_raw_ns;
7203
7204 if (copy_from_user(&data, argp, sizeof(data)))
7205 return -EFAULT;
7206
7207 /*
7208 * Only KVM_CLOCK_REALTIME is used, but allow passing the
7209 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
7210 */
7211 if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
7212 return -EINVAL;
7213
7214 kvm_hv_request_tsc_page_update(kvm);
7215 kvm_start_pvclock_update(kvm);
7216 pvclock_update_vm_gtod_copy(kvm);
7217
7218 /*
7219 * This pairs with kvm_guest_time_update(): when masterclock is
7220 * in use, we use master_kernel_ns + kvmclock_offset to set
7221 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
7222 * is slightly ahead) here we risk going negative on unsigned
7223 * 'system_time' when 'data.clock' is very small.
7224 */
7225 if (data.flags & KVM_CLOCK_REALTIME) {
7226 u64 now_real_ns = ktime_get_real_ns();
7227
7228 /*
7229 * Avoid stepping the kvmclock backwards.
7230 */
7231 if (now_real_ns > data.realtime)
7232 data.clock += now_real_ns - data.realtime;
7233 }
7234
7235 if (ka->use_master_clock)
7236 now_raw_ns = ka->master_kernel_ns;
7237 else
7238 now_raw_ns = get_kvmclock_base_ns();
7239 ka->kvmclock_offset = data.clock - now_raw_ns;
7240 kvm_end_pvclock_update(kvm);
7241 return 0;
7242 }
7243
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7244 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
7245 {
7246 struct kvm *kvm = filp->private_data;
7247 void __user *argp = (void __user *)arg;
7248 int r = -ENOTTY;
7249
7250 #ifdef CONFIG_KVM_IOAPIC
7251 /*
7252 * This union makes it completely explicit to gcc-3.x
7253 * that these three variables' stack usage should be
7254 * combined, not added together.
7255 */
7256 union {
7257 struct kvm_pit_state ps;
7258 struct kvm_pit_state2 ps2;
7259 struct kvm_pit_config pit_config;
7260 } u;
7261 #endif
7262
7263 switch (ioctl) {
7264 case KVM_SET_TSS_ADDR:
7265 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
7266 break;
7267 case KVM_SET_IDENTITY_MAP_ADDR: {
7268 u64 ident_addr;
7269
7270 mutex_lock(&kvm->lock);
7271 r = -EINVAL;
7272 if (kvm->created_vcpus)
7273 goto set_identity_unlock;
7274 r = -EFAULT;
7275 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
7276 goto set_identity_unlock;
7277 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
7278 set_identity_unlock:
7279 mutex_unlock(&kvm->lock);
7280 break;
7281 }
7282 case KVM_SET_NR_MMU_PAGES:
7283 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
7284 break;
7285 #ifdef CONFIG_KVM_IOAPIC
7286 case KVM_CREATE_IRQCHIP: {
7287 mutex_lock(&kvm->lock);
7288
7289 r = -EEXIST;
7290 if (irqchip_in_kernel(kvm))
7291 goto create_irqchip_unlock;
7292
7293 /*
7294 * Disallow an in-kernel I/O APIC if the VM has protected EOIs,
7295 * i.e. if KVM can't intercept EOIs and thus can't properly
7296 * emulate level-triggered interrupts.
7297 */
7298 r = -ENOTTY;
7299 if (kvm->arch.has_protected_eoi)
7300 goto create_irqchip_unlock;
7301
7302 r = -EINVAL;
7303 if (kvm->created_vcpus)
7304 goto create_irqchip_unlock;
7305
7306 r = kvm_pic_init(kvm);
7307 if (r)
7308 goto create_irqchip_unlock;
7309
7310 r = kvm_ioapic_init(kvm);
7311 if (r) {
7312 kvm_pic_destroy(kvm);
7313 goto create_irqchip_unlock;
7314 }
7315
7316 r = kvm_setup_default_ioapic_and_pic_routing(kvm);
7317 if (r) {
7318 kvm_ioapic_destroy(kvm);
7319 kvm_pic_destroy(kvm);
7320 goto create_irqchip_unlock;
7321 }
7322 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
7323 smp_wmb();
7324 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
7325 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
7326 create_irqchip_unlock:
7327 mutex_unlock(&kvm->lock);
7328 break;
7329 }
7330 case KVM_CREATE_PIT:
7331 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7332 goto create_pit;
7333 case KVM_CREATE_PIT2:
7334 r = -EFAULT;
7335 if (copy_from_user(&u.pit_config, argp,
7336 sizeof(struct kvm_pit_config)))
7337 goto out;
7338 create_pit:
7339 mutex_lock(&kvm->lock);
7340 r = -EEXIST;
7341 if (kvm->arch.vpit)
7342 goto create_pit_unlock;
7343 r = -ENOENT;
7344 if (!pic_in_kernel(kvm))
7345 goto create_pit_unlock;
7346 r = -ENOMEM;
7347 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7348 if (kvm->arch.vpit)
7349 r = 0;
7350 create_pit_unlock:
7351 mutex_unlock(&kvm->lock);
7352 break;
7353 case KVM_GET_IRQCHIP: {
7354 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7355 struct kvm_irqchip *chip;
7356
7357 chip = memdup_user(argp, sizeof(*chip));
7358 if (IS_ERR(chip)) {
7359 r = PTR_ERR(chip);
7360 goto out;
7361 }
7362
7363 r = -ENXIO;
7364 if (!irqchip_full(kvm))
7365 goto get_irqchip_out;
7366 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
7367 if (r)
7368 goto get_irqchip_out;
7369 r = -EFAULT;
7370 if (copy_to_user(argp, chip, sizeof(*chip)))
7371 goto get_irqchip_out;
7372 r = 0;
7373 get_irqchip_out:
7374 kfree(chip);
7375 break;
7376 }
7377 case KVM_SET_IRQCHIP: {
7378 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7379 struct kvm_irqchip *chip;
7380
7381 chip = memdup_user(argp, sizeof(*chip));
7382 if (IS_ERR(chip)) {
7383 r = PTR_ERR(chip);
7384 goto out;
7385 }
7386
7387 r = -ENXIO;
7388 if (!irqchip_full(kvm))
7389 goto set_irqchip_out;
7390 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
7391 set_irqchip_out:
7392 kfree(chip);
7393 break;
7394 }
7395 case KVM_GET_PIT: {
7396 r = -EFAULT;
7397 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
7398 goto out;
7399 r = -ENXIO;
7400 if (!kvm->arch.vpit)
7401 goto out;
7402 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
7403 if (r)
7404 goto out;
7405 r = -EFAULT;
7406 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
7407 goto out;
7408 r = 0;
7409 break;
7410 }
7411 case KVM_SET_PIT: {
7412 r = -EFAULT;
7413 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
7414 goto out;
7415 mutex_lock(&kvm->lock);
7416 r = -ENXIO;
7417 if (!kvm->arch.vpit)
7418 goto set_pit_out;
7419 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7420 set_pit_out:
7421 mutex_unlock(&kvm->lock);
7422 break;
7423 }
7424 case KVM_GET_PIT2: {
7425 r = -ENXIO;
7426 if (!kvm->arch.vpit)
7427 goto out;
7428 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7429 if (r)
7430 goto out;
7431 r = -EFAULT;
7432 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7433 goto out;
7434 r = 0;
7435 break;
7436 }
7437 case KVM_SET_PIT2: {
7438 r = -EFAULT;
7439 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7440 goto out;
7441 mutex_lock(&kvm->lock);
7442 r = -ENXIO;
7443 if (!kvm->arch.vpit)
7444 goto set_pit2_out;
7445 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7446 set_pit2_out:
7447 mutex_unlock(&kvm->lock);
7448 break;
7449 }
7450 case KVM_REINJECT_CONTROL: {
7451 struct kvm_reinject_control control;
7452 r = -EFAULT;
7453 if (copy_from_user(&control, argp, sizeof(control)))
7454 goto out;
7455 r = -ENXIO;
7456 if (!kvm->arch.vpit)
7457 goto out;
7458 r = kvm_vm_ioctl_reinject(kvm, &control);
7459 break;
7460 }
7461 #endif
7462 case KVM_SET_BOOT_CPU_ID:
7463 r = 0;
7464 mutex_lock(&kvm->lock);
7465 if (kvm->created_vcpus)
7466 r = -EBUSY;
7467 else if (arg > KVM_MAX_VCPU_IDS ||
7468 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
7469 r = -EINVAL;
7470 else
7471 kvm->arch.bsp_vcpu_id = arg;
7472 mutex_unlock(&kvm->lock);
7473 break;
7474 #ifdef CONFIG_KVM_XEN
7475 case KVM_XEN_HVM_CONFIG: {
7476 struct kvm_xen_hvm_config xhc;
7477 r = -EFAULT;
7478 if (copy_from_user(&xhc, argp, sizeof(xhc)))
7479 goto out;
7480 r = kvm_xen_hvm_config(kvm, &xhc);
7481 break;
7482 }
7483 case KVM_XEN_HVM_GET_ATTR: {
7484 struct kvm_xen_hvm_attr xha;
7485
7486 r = -EFAULT;
7487 if (copy_from_user(&xha, argp, sizeof(xha)))
7488 goto out;
7489 r = kvm_xen_hvm_get_attr(kvm, &xha);
7490 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7491 r = -EFAULT;
7492 break;
7493 }
7494 case KVM_XEN_HVM_SET_ATTR: {
7495 struct kvm_xen_hvm_attr xha;
7496
7497 r = -EFAULT;
7498 if (copy_from_user(&xha, argp, sizeof(xha)))
7499 goto out;
7500 r = kvm_xen_hvm_set_attr(kvm, &xha);
7501 break;
7502 }
7503 case KVM_XEN_HVM_EVTCHN_SEND: {
7504 struct kvm_irq_routing_xen_evtchn uxe;
7505
7506 r = -EFAULT;
7507 if (copy_from_user(&uxe, argp, sizeof(uxe)))
7508 goto out;
7509 r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7510 break;
7511 }
7512 #endif
7513 case KVM_SET_CLOCK:
7514 r = kvm_vm_ioctl_set_clock(kvm, argp);
7515 break;
7516 case KVM_GET_CLOCK:
7517 r = kvm_vm_ioctl_get_clock(kvm, argp);
7518 break;
7519 case KVM_SET_TSC_KHZ: {
7520 u32 user_tsc_khz;
7521
7522 r = -EINVAL;
7523 user_tsc_khz = (u32)arg;
7524
7525 if (kvm_caps.has_tsc_control &&
7526 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
7527 goto out;
7528
7529 if (user_tsc_khz == 0)
7530 user_tsc_khz = tsc_khz;
7531
7532 mutex_lock(&kvm->lock);
7533 if (!kvm->created_vcpus) {
7534 WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7535 r = 0;
7536 }
7537 mutex_unlock(&kvm->lock);
7538 goto out;
7539 }
7540 case KVM_GET_TSC_KHZ: {
7541 r = READ_ONCE(kvm->arch.default_tsc_khz);
7542 goto out;
7543 }
7544 case KVM_MEMORY_ENCRYPT_OP:
7545 r = -ENOTTY;
7546 if (!kvm_x86_ops.mem_enc_ioctl)
7547 goto out;
7548
7549 r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
7550 break;
7551 case KVM_MEMORY_ENCRYPT_REG_REGION: {
7552 struct kvm_enc_region region;
7553
7554 r = -EFAULT;
7555 if (copy_from_user(®ion, argp, sizeof(region)))
7556 goto out;
7557
7558 r = -ENOTTY;
7559 if (!kvm_x86_ops.mem_enc_register_region)
7560 goto out;
7561
7562 r = kvm_x86_call(mem_enc_register_region)(kvm, ®ion);
7563 break;
7564 }
7565 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7566 struct kvm_enc_region region;
7567
7568 r = -EFAULT;
7569 if (copy_from_user(®ion, argp, sizeof(region)))
7570 goto out;
7571
7572 r = -ENOTTY;
7573 if (!kvm_x86_ops.mem_enc_unregister_region)
7574 goto out;
7575
7576 r = kvm_x86_call(mem_enc_unregister_region)(kvm, ®ion);
7577 break;
7578 }
7579 #ifdef CONFIG_KVM_HYPERV
7580 case KVM_HYPERV_EVENTFD: {
7581 struct kvm_hyperv_eventfd hvevfd;
7582
7583 r = -EFAULT;
7584 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7585 goto out;
7586 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7587 break;
7588 }
7589 #endif
7590 case KVM_SET_PMU_EVENT_FILTER:
7591 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7592 break;
7593 case KVM_X86_SET_MSR_FILTER: {
7594 struct kvm_msr_filter __user *user_msr_filter = argp;
7595 struct kvm_msr_filter filter;
7596
7597 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7598 return -EFAULT;
7599
7600 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7601 break;
7602 }
7603 default:
7604 r = -ENOTTY;
7605 }
7606 out:
7607 return r;
7608 }
7609
kvm_probe_feature_msr(u32 msr_index)7610 static void kvm_probe_feature_msr(u32 msr_index)
7611 {
7612 u64 data;
7613
7614 if (kvm_get_feature_msr(NULL, msr_index, &data, true))
7615 return;
7616
7617 msr_based_features[num_msr_based_features++] = msr_index;
7618 }
7619
kvm_probe_msr_to_save(u32 msr_index)7620 static void kvm_probe_msr_to_save(u32 msr_index)
7621 {
7622 u32 dummy[2];
7623
7624 if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7625 return;
7626
7627 /*
7628 * Even MSRs that are valid in the host may not be exposed to guests in
7629 * some cases.
7630 */
7631 switch (msr_index) {
7632 case MSR_IA32_BNDCFGS:
7633 if (!kvm_mpx_supported())
7634 return;
7635 break;
7636 case MSR_TSC_AUX:
7637 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7638 !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7639 return;
7640 break;
7641 case MSR_IA32_UMWAIT_CONTROL:
7642 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7643 return;
7644 break;
7645 case MSR_IA32_RTIT_CTL:
7646 case MSR_IA32_RTIT_STATUS:
7647 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7648 return;
7649 break;
7650 case MSR_IA32_RTIT_CR3_MATCH:
7651 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7652 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7653 return;
7654 break;
7655 case MSR_IA32_RTIT_OUTPUT_BASE:
7656 case MSR_IA32_RTIT_OUTPUT_MASK:
7657 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7658 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7659 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7660 return;
7661 break;
7662 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7663 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7664 (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7665 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7666 return;
7667 break;
7668 case MSR_ARCH_PERFMON_PERFCTR0 ...
7669 MSR_ARCH_PERFMON_PERFCTR0 + KVM_MAX_NR_GP_COUNTERS - 1:
7670 if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7671 kvm_pmu_cap.num_counters_gp)
7672 return;
7673 break;
7674 case MSR_ARCH_PERFMON_EVENTSEL0 ...
7675 MSR_ARCH_PERFMON_EVENTSEL0 + KVM_MAX_NR_GP_COUNTERS - 1:
7676 if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7677 kvm_pmu_cap.num_counters_gp)
7678 return;
7679 break;
7680 case MSR_ARCH_PERFMON_FIXED_CTR0 ...
7681 MSR_ARCH_PERFMON_FIXED_CTR0 + KVM_MAX_NR_FIXED_COUNTERS - 1:
7682 if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7683 kvm_pmu_cap.num_counters_fixed)
7684 return;
7685 break;
7686 case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7687 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7688 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7689 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET:
7690 if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7691 return;
7692 break;
7693 case MSR_IA32_XFD:
7694 case MSR_IA32_XFD_ERR:
7695 if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7696 return;
7697 break;
7698 case MSR_IA32_TSX_CTRL:
7699 if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7700 return;
7701 break;
7702 case MSR_IA32_XSS:
7703 if (!kvm_caps.supported_xss)
7704 return;
7705 break;
7706 case MSR_IA32_U_CET:
7707 case MSR_IA32_S_CET:
7708 if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
7709 !kvm_cpu_cap_has(X86_FEATURE_IBT))
7710 return;
7711 break;
7712 case MSR_IA32_INT_SSP_TAB:
7713 if (!kvm_cpu_cap_has(X86_FEATURE_LM))
7714 return;
7715 fallthrough;
7716 case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
7717 if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK))
7718 return;
7719 break;
7720 default:
7721 break;
7722 }
7723
7724 msrs_to_save[num_msrs_to_save++] = msr_index;
7725 }
7726
kvm_init_msr_lists(void)7727 static void kvm_init_msr_lists(void)
7728 {
7729 unsigned i;
7730
7731 BUILD_BUG_ON_MSG(KVM_MAX_NR_FIXED_COUNTERS != 3,
7732 "Please update the fixed PMCs in msrs_to_save_pmu[]");
7733
7734 num_msrs_to_save = 0;
7735 num_emulated_msrs = 0;
7736 num_msr_based_features = 0;
7737
7738 for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7739 kvm_probe_msr_to_save(msrs_to_save_base[i]);
7740
7741 if (enable_pmu) {
7742 for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7743 kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
7744 }
7745
7746 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7747 if (!kvm_x86_call(has_emulated_msr)(NULL,
7748 emulated_msrs_all[i]))
7749 continue;
7750
7751 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7752 }
7753
7754 for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7755 kvm_probe_feature_msr(i);
7756
7757 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7758 kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
7759 }
7760
vcpu_mmio_write(struct kvm_vcpu * vcpu,gpa_t addr,int len,const void * v)7761 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7762 const void *v)
7763 {
7764 int handled = 0;
7765 int n;
7766
7767 do {
7768 n = min(len, 8);
7769 if (!(lapic_in_kernel(vcpu) &&
7770 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7771 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7772 break;
7773 handled += n;
7774 addr += n;
7775 len -= n;
7776 v += n;
7777 } while (len);
7778
7779 return handled;
7780 }
7781
vcpu_mmio_read(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * v)7782 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7783 {
7784 int handled = 0;
7785 int n;
7786
7787 do {
7788 n = min(len, 8);
7789 if (!(lapic_in_kernel(vcpu) &&
7790 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7791 addr, n, v))
7792 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7793 break;
7794 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7795 handled += n;
7796 addr += n;
7797 len -= n;
7798 v += n;
7799 } while (len);
7800
7801 return handled;
7802 }
7803
kvm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7804 void kvm_set_segment(struct kvm_vcpu *vcpu,
7805 struct kvm_segment *var, int seg)
7806 {
7807 kvm_x86_call(set_segment)(vcpu, var, seg);
7808 }
7809
kvm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7810 void kvm_get_segment(struct kvm_vcpu *vcpu,
7811 struct kvm_segment *var, int seg)
7812 {
7813 kvm_x86_call(get_segment)(vcpu, var, seg);
7814 }
7815
translate_nested_gpa(struct kvm_vcpu * vcpu,gpa_t gpa,u64 access,struct x86_exception * exception)7816 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7817 struct x86_exception *exception)
7818 {
7819 struct kvm_mmu *mmu = vcpu->arch.mmu;
7820 gpa_t t_gpa;
7821
7822 BUG_ON(!mmu_is_nested(vcpu));
7823
7824 /* NPT walks are always user-walks */
7825 access |= PFERR_USER_MASK;
7826 t_gpa = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7827
7828 return t_gpa;
7829 }
7830
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7831 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7832 struct x86_exception *exception)
7833 {
7834 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7835
7836 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7837 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7838 }
7839 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_read);
7840
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7841 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7842 struct x86_exception *exception)
7843 {
7844 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7845
7846 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7847 access |= PFERR_WRITE_MASK;
7848 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7849 }
7850 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_write);
7851
7852 /* 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)7853 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7854 struct x86_exception *exception)
7855 {
7856 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7857
7858 return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7859 }
7860
kvm_read_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7861 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7862 struct kvm_vcpu *vcpu, u64 access,
7863 struct x86_exception *exception)
7864 {
7865 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7866 void *data = val;
7867 int r = X86EMUL_CONTINUE;
7868
7869 while (bytes) {
7870 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7871 unsigned offset = addr & (PAGE_SIZE-1);
7872 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7873 int ret;
7874
7875 if (gpa == INVALID_GPA)
7876 return X86EMUL_PROPAGATE_FAULT;
7877 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7878 offset, toread);
7879 if (ret < 0) {
7880 r = X86EMUL_IO_NEEDED;
7881 goto out;
7882 }
7883
7884 bytes -= toread;
7885 data += toread;
7886 addr += toread;
7887 }
7888 out:
7889 return r;
7890 }
7891
7892 /* 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)7893 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7894 gva_t addr, void *val, unsigned int bytes,
7895 struct x86_exception *exception)
7896 {
7897 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7898 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7899 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7900 unsigned offset;
7901 int ret;
7902
7903 /* Inline kvm_read_guest_virt_helper for speed. */
7904 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7905 exception);
7906 if (unlikely(gpa == INVALID_GPA))
7907 return X86EMUL_PROPAGATE_FAULT;
7908
7909 offset = addr & (PAGE_SIZE-1);
7910 if (WARN_ON(offset + bytes > PAGE_SIZE))
7911 bytes = (unsigned)PAGE_SIZE - offset;
7912 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7913 offset, bytes);
7914 if (unlikely(ret < 0))
7915 return X86EMUL_IO_NEEDED;
7916
7917 return X86EMUL_CONTINUE;
7918 }
7919
kvm_read_guest_virt(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7920 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7921 gva_t addr, void *val, unsigned int bytes,
7922 struct x86_exception *exception)
7923 {
7924 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7925
7926 /*
7927 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7928 * is returned, but our callers are not ready for that and they blindly
7929 * call kvm_inject_page_fault. Ensure that they at least do not leak
7930 * uninitialized kernel stack memory into cr2 and error code.
7931 */
7932 memset(exception, 0, sizeof(*exception));
7933 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7934 exception);
7935 }
7936 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_virt);
7937
emulator_read_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7938 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7939 gva_t addr, void *val, unsigned int bytes,
7940 struct x86_exception *exception, bool system)
7941 {
7942 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7943 u64 access = 0;
7944
7945 if (system)
7946 access |= PFERR_IMPLICIT_ACCESS;
7947 else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7948 access |= PFERR_USER_MASK;
7949
7950 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7951 }
7952
kvm_write_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7953 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7954 struct kvm_vcpu *vcpu, u64 access,
7955 struct x86_exception *exception)
7956 {
7957 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7958 void *data = val;
7959 int r = X86EMUL_CONTINUE;
7960
7961 while (bytes) {
7962 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7963 unsigned offset = addr & (PAGE_SIZE-1);
7964 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7965 int ret;
7966
7967 if (gpa == INVALID_GPA)
7968 return X86EMUL_PROPAGATE_FAULT;
7969 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7970 if (ret < 0) {
7971 r = X86EMUL_IO_NEEDED;
7972 goto out;
7973 }
7974
7975 bytes -= towrite;
7976 data += towrite;
7977 addr += towrite;
7978 }
7979 out:
7980 return r;
7981 }
7982
emulator_write_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7983 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7984 unsigned int bytes, struct x86_exception *exception,
7985 bool system)
7986 {
7987 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7988 u64 access = PFERR_WRITE_MASK;
7989
7990 if (system)
7991 access |= PFERR_IMPLICIT_ACCESS;
7992 else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7993 access |= PFERR_USER_MASK;
7994
7995 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7996 access, exception);
7997 }
7998
kvm_write_guest_virt_system(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7999 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
8000 unsigned int bytes, struct x86_exception *exception)
8001 {
8002 /* kvm_write_guest_virt_system can pull in tons of pages. */
8003 vcpu->arch.l1tf_flush_l1d = true;
8004
8005 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
8006 PFERR_WRITE_MASK, exception);
8007 }
8008 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_write_guest_virt_system);
8009
kvm_check_emulate_insn(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)8010 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
8011 void *insn, int insn_len)
8012 {
8013 return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
8014 insn, insn_len);
8015 }
8016
handle_ud(struct kvm_vcpu * vcpu)8017 int handle_ud(struct kvm_vcpu *vcpu)
8018 {
8019 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
8020 int fep_flags = READ_ONCE(force_emulation_prefix);
8021 int emul_type = EMULTYPE_TRAP_UD;
8022 char sig[5]; /* ud2; .ascii "kvm" */
8023 struct x86_exception e;
8024 int r;
8025
8026 r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
8027 if (r != X86EMUL_CONTINUE)
8028 return 1;
8029
8030 if (fep_flags &&
8031 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
8032 sig, sizeof(sig), &e) == 0 &&
8033 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
8034 if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
8035 kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
8036 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
8037 emul_type = EMULTYPE_TRAP_UD_FORCED;
8038 }
8039
8040 return kvm_emulate_instruction(vcpu, emul_type);
8041 }
8042 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_ud);
8043
vcpu_is_mmio_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t gpa,bool write)8044 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
8045 gpa_t gpa, bool write)
8046 {
8047 /* For APIC access vmexit */
8048 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8049 return 1;
8050
8051 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
8052 trace_vcpu_match_mmio(gva, gpa, write, true);
8053 return 1;
8054 }
8055
8056 return 0;
8057 }
8058
vcpu_mmio_gva_to_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t * gpa,struct x86_exception * exception,bool write)8059 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
8060 gpa_t *gpa, struct x86_exception *exception,
8061 bool write)
8062 {
8063 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8064 u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
8065 | (write ? PFERR_WRITE_MASK : 0);
8066
8067 /*
8068 * currently PKRU is only applied to ept enabled guest so
8069 * there is no pkey in EPT page table for L1 guest or EPT
8070 * shadow page table for L2 guest.
8071 */
8072 if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
8073 !permission_fault(vcpu, vcpu->arch.walk_mmu,
8074 vcpu->arch.mmio_access, 0, access))) {
8075 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
8076 (gva & (PAGE_SIZE - 1));
8077 trace_vcpu_match_mmio(gva, *gpa, write, false);
8078 return 1;
8079 }
8080
8081 *gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
8082
8083 if (*gpa == INVALID_GPA)
8084 return -1;
8085
8086 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
8087 }
8088
emulator_write_phys(struct kvm_vcpu * vcpu,gpa_t gpa,const void * val,int bytes)8089 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
8090 const void *val, int bytes)
8091 {
8092 int ret;
8093
8094 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
8095 if (ret < 0)
8096 return 0;
8097 kvm_page_track_write(vcpu, gpa, val, bytes);
8098 return 1;
8099 }
8100
8101 struct read_write_emulator_ops {
8102 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
8103 int bytes);
8104 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
8105 void *val, int bytes);
8106 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
8107 int bytes, void *val);
8108 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
8109 void *val, int bytes);
8110 bool write;
8111 };
8112
read_prepare(struct kvm_vcpu * vcpu,void * val,int bytes)8113 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
8114 {
8115 if (vcpu->mmio_read_completed) {
8116 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
8117 vcpu->mmio_fragments[0].gpa, val);
8118 vcpu->mmio_read_completed = 0;
8119 return 1;
8120 }
8121
8122 return 0;
8123 }
8124
read_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8125 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
8126 void *val, int bytes)
8127 {
8128 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
8129 }
8130
write_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8131 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
8132 void *val, int bytes)
8133 {
8134 return emulator_write_phys(vcpu, gpa, val, bytes);
8135 }
8136
write_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,int bytes,void * val)8137 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
8138 {
8139 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
8140 return vcpu_mmio_write(vcpu, gpa, bytes, val);
8141 }
8142
read_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8143 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
8144 void *val, int bytes)
8145 {
8146 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
8147 return X86EMUL_IO_NEEDED;
8148 }
8149
write_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8150 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
8151 void *val, int bytes)
8152 {
8153 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
8154
8155 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
8156 return X86EMUL_CONTINUE;
8157 }
8158
8159 static const struct read_write_emulator_ops read_emultor = {
8160 .read_write_prepare = read_prepare,
8161 .read_write_emulate = read_emulate,
8162 .read_write_mmio = vcpu_mmio_read,
8163 .read_write_exit_mmio = read_exit_mmio,
8164 };
8165
8166 static const struct read_write_emulator_ops write_emultor = {
8167 .read_write_emulate = write_emulate,
8168 .read_write_mmio = write_mmio,
8169 .read_write_exit_mmio = write_exit_mmio,
8170 .write = true,
8171 };
8172
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)8173 static int emulator_read_write_onepage(unsigned long addr, void *val,
8174 unsigned int bytes,
8175 struct x86_exception *exception,
8176 struct kvm_vcpu *vcpu,
8177 const struct read_write_emulator_ops *ops)
8178 {
8179 gpa_t gpa;
8180 int handled, ret;
8181 bool write = ops->write;
8182 struct kvm_mmio_fragment *frag;
8183 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8184
8185 /*
8186 * If the exit was due to a NPF we may already have a GPA.
8187 * If the GPA is present, use it to avoid the GVA to GPA table walk.
8188 * Note, this cannot be used on string operations since string
8189 * operation using rep will only have the initial GPA from the NPF
8190 * occurred.
8191 */
8192 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
8193 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
8194 gpa = ctxt->gpa_val;
8195 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
8196 } else {
8197 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
8198 if (ret < 0)
8199 return X86EMUL_PROPAGATE_FAULT;
8200 }
8201
8202 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
8203 return X86EMUL_CONTINUE;
8204
8205 /*
8206 * Is this MMIO handled locally?
8207 */
8208 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
8209 if (handled == bytes)
8210 return X86EMUL_CONTINUE;
8211
8212 gpa += handled;
8213 bytes -= handled;
8214 val += handled;
8215
8216 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
8217 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
8218 frag->gpa = gpa;
8219 frag->data = val;
8220 frag->len = bytes;
8221 return X86EMUL_CONTINUE;
8222 }
8223
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)8224 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
8225 unsigned long addr,
8226 void *val, unsigned int bytes,
8227 struct x86_exception *exception,
8228 const struct read_write_emulator_ops *ops)
8229 {
8230 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8231 gpa_t gpa;
8232 int rc;
8233
8234 if (ops->read_write_prepare &&
8235 ops->read_write_prepare(vcpu, val, bytes))
8236 return X86EMUL_CONTINUE;
8237
8238 vcpu->mmio_nr_fragments = 0;
8239
8240 /* Crossing a page boundary? */
8241 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
8242 int now;
8243
8244 now = -addr & ~PAGE_MASK;
8245 rc = emulator_read_write_onepage(addr, val, now, exception,
8246 vcpu, ops);
8247
8248 if (rc != X86EMUL_CONTINUE)
8249 return rc;
8250 addr += now;
8251 if (ctxt->mode != X86EMUL_MODE_PROT64)
8252 addr = (u32)addr;
8253 val += now;
8254 bytes -= now;
8255 }
8256
8257 rc = emulator_read_write_onepage(addr, val, bytes, exception,
8258 vcpu, ops);
8259 if (rc != X86EMUL_CONTINUE)
8260 return rc;
8261
8262 if (!vcpu->mmio_nr_fragments)
8263 return X86EMUL_CONTINUE;
8264
8265 gpa = vcpu->mmio_fragments[0].gpa;
8266
8267 vcpu->mmio_needed = 1;
8268 vcpu->mmio_cur_fragment = 0;
8269
8270 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
8271 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
8272 vcpu->run->exit_reason = KVM_EXIT_MMIO;
8273 vcpu->run->mmio.phys_addr = gpa;
8274
8275 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
8276 }
8277
emulator_read_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception)8278 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8279 unsigned long addr,
8280 void *val,
8281 unsigned int bytes,
8282 struct x86_exception *exception)
8283 {
8284 return emulator_read_write(ctxt, addr, val, bytes,
8285 exception, &read_emultor);
8286 }
8287
emulator_write_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * val,unsigned int bytes,struct x86_exception * exception)8288 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
8289 unsigned long addr,
8290 const void *val,
8291 unsigned int bytes,
8292 struct x86_exception *exception)
8293 {
8294 return emulator_read_write(ctxt, addr, (void *)val, bytes,
8295 exception, &write_emultor);
8296 }
8297
8298 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
8299 (__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
8300
emulator_cmpxchg_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * old,const void * new,unsigned int bytes,struct x86_exception * exception)8301 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8302 unsigned long addr,
8303 const void *old,
8304 const void *new,
8305 unsigned int bytes,
8306 struct x86_exception *exception)
8307 {
8308 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8309 u64 page_line_mask;
8310 unsigned long hva;
8311 gpa_t gpa;
8312 int r;
8313
8314 /* guests cmpxchg8b have to be emulated atomically */
8315 if (bytes > 8 || (bytes & (bytes - 1)))
8316 goto emul_write;
8317
8318 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
8319
8320 if (gpa == INVALID_GPA ||
8321 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8322 goto emul_write;
8323
8324 /*
8325 * Emulate the atomic as a straight write to avoid #AC if SLD is
8326 * enabled in the host and the access splits a cache line.
8327 */
8328 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8329 page_line_mask = ~(cache_line_size() - 1);
8330 else
8331 page_line_mask = PAGE_MASK;
8332
8333 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
8334 goto emul_write;
8335
8336 hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
8337 if (kvm_is_error_hva(hva))
8338 goto emul_write;
8339
8340 hva += offset_in_page(gpa);
8341
8342 switch (bytes) {
8343 case 1:
8344 r = emulator_try_cmpxchg_user(u8, hva, old, new);
8345 break;
8346 case 2:
8347 r = emulator_try_cmpxchg_user(u16, hva, old, new);
8348 break;
8349 case 4:
8350 r = emulator_try_cmpxchg_user(u32, hva, old, new);
8351 break;
8352 case 8:
8353 r = emulator_try_cmpxchg_user(u64, hva, old, new);
8354 break;
8355 default:
8356 BUG();
8357 }
8358
8359 if (r < 0)
8360 return X86EMUL_UNHANDLEABLE;
8361
8362 /*
8363 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8364 * successful, as the old value is written back on failure. Note, for
8365 * live migration, this is unnecessarily conservative as CMPXCHG writes
8366 * back the original value and the access is atomic, but KVM's ABI is
8367 * that all writes are dirty logged, regardless of the value written.
8368 */
8369 kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8370
8371 if (r)
8372 return X86EMUL_CMPXCHG_FAILED;
8373
8374 kvm_page_track_write(vcpu, gpa, new, bytes);
8375
8376 return X86EMUL_CONTINUE;
8377
8378 emul_write:
8379 pr_warn_once("emulating exchange as write\n");
8380
8381 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
8382 }
8383
emulator_pio_in_out(struct kvm_vcpu * vcpu,int size,unsigned short port,void * data,unsigned int count,bool in)8384 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
8385 unsigned short port, void *data,
8386 unsigned int count, bool in)
8387 {
8388 unsigned i;
8389 int r;
8390
8391 WARN_ON_ONCE(vcpu->arch.pio.count);
8392 for (i = 0; i < count; i++) {
8393 if (in)
8394 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
8395 else
8396 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
8397
8398 if (r) {
8399 if (i == 0)
8400 goto userspace_io;
8401
8402 /*
8403 * Userspace must have unregistered the device while PIO
8404 * was running. Drop writes / read as 0.
8405 */
8406 if (in)
8407 memset(data, 0, size * (count - i));
8408 break;
8409 }
8410
8411 data += size;
8412 }
8413 return 1;
8414
8415 userspace_io:
8416 vcpu->arch.pio.port = port;
8417 vcpu->arch.pio.in = in;
8418 vcpu->arch.pio.count = count;
8419 vcpu->arch.pio.size = size;
8420
8421 if (in)
8422 memset(vcpu->arch.pio_data, 0, size * count);
8423 else
8424 memcpy(vcpu->arch.pio_data, data, size * count);
8425
8426 vcpu->run->exit_reason = KVM_EXIT_IO;
8427 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
8428 vcpu->run->io.size = size;
8429 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8430 vcpu->run->io.count = count;
8431 vcpu->run->io.port = port;
8432 return 0;
8433 }
8434
emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,void * val,unsigned int count)8435 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8436 unsigned short port, void *val, unsigned int count)
8437 {
8438 int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8439 if (r)
8440 trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8441
8442 return r;
8443 }
8444
complete_emulator_pio_in(struct kvm_vcpu * vcpu,void * val)8445 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
8446 {
8447 int size = vcpu->arch.pio.size;
8448 unsigned int count = vcpu->arch.pio.count;
8449 memcpy(val, vcpu->arch.pio_data, size * count);
8450 trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
8451 vcpu->arch.pio.count = 0;
8452 }
8453
emulator_pio_in_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,void * val,unsigned int count)8454 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8455 int size, unsigned short port, void *val,
8456 unsigned int count)
8457 {
8458 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8459 if (vcpu->arch.pio.count) {
8460 /*
8461 * Complete a previous iteration that required userspace I/O.
8462 * Note, @count isn't guaranteed to match pio.count as userspace
8463 * can modify ECX before rerunning the vCPU. Ignore any such
8464 * shenanigans as KVM doesn't support modifying the rep count,
8465 * and the emulator ensures @count doesn't overflow the buffer.
8466 */
8467 complete_emulator_pio_in(vcpu, val);
8468 return 1;
8469 }
8470
8471 return emulator_pio_in(vcpu, size, port, val, count);
8472 }
8473
emulator_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port,const void * val,unsigned int count)8474 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8475 unsigned short port, const void *val,
8476 unsigned int count)
8477 {
8478 trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
8479 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
8480 }
8481
emulator_pio_out_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,const void * val,unsigned int count)8482 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8483 int size, unsigned short port,
8484 const void *val, unsigned int count)
8485 {
8486 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8487 }
8488
get_segment_base(struct kvm_vcpu * vcpu,int seg)8489 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8490 {
8491 return kvm_x86_call(get_segment_base)(vcpu, seg);
8492 }
8493
emulator_invlpg(struct x86_emulate_ctxt * ctxt,ulong address)8494 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
8495 {
8496 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
8497 }
8498
kvm_emulate_wbinvd_noskip(struct kvm_vcpu * vcpu)8499 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
8500 {
8501 if (!need_emulate_wbinvd(vcpu))
8502 return X86EMUL_CONTINUE;
8503
8504 if (kvm_x86_call(has_wbinvd_exit)()) {
8505 int cpu = get_cpu();
8506
8507 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
8508 wbinvd_on_cpus_mask(vcpu->arch.wbinvd_dirty_mask);
8509 put_cpu();
8510 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
8511 } else
8512 wbinvd();
8513 return X86EMUL_CONTINUE;
8514 }
8515
kvm_emulate_wbinvd(struct kvm_vcpu * vcpu)8516 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8517 {
8518 kvm_emulate_wbinvd_noskip(vcpu);
8519 return kvm_skip_emulated_instruction(vcpu);
8520 }
8521 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wbinvd);
8522
8523
8524
emulator_wbinvd(struct x86_emulate_ctxt * ctxt)8525 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8526 {
8527 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
8528 }
8529
emulator_get_dr(struct x86_emulate_ctxt * ctxt,int dr)8530 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
8531 {
8532 return kvm_get_dr(emul_to_vcpu(ctxt), dr);
8533 }
8534
emulator_set_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long value)8535 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8536 unsigned long value)
8537 {
8538
8539 return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
8540 }
8541
mk_cr_64(u64 curr_cr,u32 new_val)8542 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
8543 {
8544 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
8545 }
8546
emulator_get_cr(struct x86_emulate_ctxt * ctxt,int cr)8547 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
8548 {
8549 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8550 unsigned long value;
8551
8552 switch (cr) {
8553 case 0:
8554 value = kvm_read_cr0(vcpu);
8555 break;
8556 case 2:
8557 value = vcpu->arch.cr2;
8558 break;
8559 case 3:
8560 value = kvm_read_cr3(vcpu);
8561 break;
8562 case 4:
8563 value = kvm_read_cr4(vcpu);
8564 break;
8565 case 8:
8566 value = kvm_get_cr8(vcpu);
8567 break;
8568 default:
8569 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8570 return 0;
8571 }
8572
8573 return value;
8574 }
8575
emulator_set_cr(struct x86_emulate_ctxt * ctxt,int cr,ulong val)8576 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
8577 {
8578 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8579 int res = 0;
8580
8581 switch (cr) {
8582 case 0:
8583 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
8584 break;
8585 case 2:
8586 vcpu->arch.cr2 = val;
8587 break;
8588 case 3:
8589 res = kvm_set_cr3(vcpu, val);
8590 break;
8591 case 4:
8592 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
8593 break;
8594 case 8:
8595 res = kvm_set_cr8(vcpu, val);
8596 break;
8597 default:
8598 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8599 res = -1;
8600 }
8601
8602 return res;
8603 }
8604
emulator_get_cpl(struct x86_emulate_ctxt * ctxt)8605 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8606 {
8607 return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
8608 }
8609
emulator_get_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8610 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8611 {
8612 kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
8613 }
8614
emulator_get_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8615 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8616 {
8617 kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
8618 }
8619
emulator_set_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8620 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8621 {
8622 kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
8623 }
8624
emulator_set_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8625 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8626 {
8627 kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
8628 }
8629
emulator_get_cached_segment_base(struct x86_emulate_ctxt * ctxt,int seg)8630 static unsigned long emulator_get_cached_segment_base(
8631 struct x86_emulate_ctxt *ctxt, int seg)
8632 {
8633 return get_segment_base(emul_to_vcpu(ctxt), seg);
8634 }
8635
emulator_get_segment(struct x86_emulate_ctxt * ctxt,u16 * selector,struct desc_struct * desc,u32 * base3,int seg)8636 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8637 struct desc_struct *desc, u32 *base3,
8638 int seg)
8639 {
8640 struct kvm_segment var;
8641
8642 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8643 *selector = var.selector;
8644
8645 if (var.unusable) {
8646 memset(desc, 0, sizeof(*desc));
8647 if (base3)
8648 *base3 = 0;
8649 return false;
8650 }
8651
8652 if (var.g)
8653 var.limit >>= 12;
8654 set_desc_limit(desc, var.limit);
8655 set_desc_base(desc, (unsigned long)var.base);
8656 #ifdef CONFIG_X86_64
8657 if (base3)
8658 *base3 = var.base >> 32;
8659 #endif
8660 desc->type = var.type;
8661 desc->s = var.s;
8662 desc->dpl = var.dpl;
8663 desc->p = var.present;
8664 desc->avl = var.avl;
8665 desc->l = var.l;
8666 desc->d = var.db;
8667 desc->g = var.g;
8668
8669 return true;
8670 }
8671
emulator_set_segment(struct x86_emulate_ctxt * ctxt,u16 selector,struct desc_struct * desc,u32 base3,int seg)8672 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8673 struct desc_struct *desc, u32 base3,
8674 int seg)
8675 {
8676 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8677 struct kvm_segment var;
8678
8679 var.selector = selector;
8680 var.base = get_desc_base(desc);
8681 #ifdef CONFIG_X86_64
8682 var.base |= ((u64)base3) << 32;
8683 #endif
8684 var.limit = get_desc_limit(desc);
8685 if (desc->g)
8686 var.limit = (var.limit << 12) | 0xfff;
8687 var.type = desc->type;
8688 var.dpl = desc->dpl;
8689 var.db = desc->d;
8690 var.s = desc->s;
8691 var.l = desc->l;
8692 var.g = desc->g;
8693 var.avl = desc->avl;
8694 var.present = desc->p;
8695 var.unusable = !var.present;
8696 var.padding = 0;
8697
8698 kvm_set_segment(vcpu, &var, seg);
8699 return;
8700 }
8701
emulator_get_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8702 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8703 u32 msr_index, u64 *pdata)
8704 {
8705 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8706 int r;
8707
8708 r = kvm_emulate_msr_read(vcpu, msr_index, pdata);
8709 if (r < 0)
8710 return X86EMUL_UNHANDLEABLE;
8711
8712 if (r) {
8713 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8714 complete_emulated_rdmsr, r))
8715 return X86EMUL_IO_NEEDED;
8716
8717 trace_kvm_msr_read_ex(msr_index);
8718 return X86EMUL_PROPAGATE_FAULT;
8719 }
8720
8721 trace_kvm_msr_read(msr_index, *pdata);
8722 return X86EMUL_CONTINUE;
8723 }
8724
emulator_set_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)8725 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8726 u32 msr_index, u64 data)
8727 {
8728 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8729 int r;
8730
8731 r = kvm_emulate_msr_write(vcpu, msr_index, data);
8732 if (r < 0)
8733 return X86EMUL_UNHANDLEABLE;
8734
8735 if (r) {
8736 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8737 complete_emulated_msr_access, r))
8738 return X86EMUL_IO_NEEDED;
8739
8740 trace_kvm_msr_write_ex(msr_index, data);
8741 return X86EMUL_PROPAGATE_FAULT;
8742 }
8743
8744 trace_kvm_msr_write(msr_index, data);
8745 return X86EMUL_CONTINUE;
8746 }
8747
emulator_get_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8748 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8749 u32 msr_index, u64 *pdata)
8750 {
8751 /*
8752 * Treat emulator accesses to the current shadow stack pointer as host-
8753 * initiated, as they aren't true MSR accesses (SSP is a "just a reg"),
8754 * and this API is used only for implicit accesses, i.e. not RDMSR, and
8755 * so the index is fully KVM-controlled.
8756 */
8757 if (unlikely(msr_index == MSR_KVM_INTERNAL_GUEST_SSP))
8758 return kvm_msr_read(emul_to_vcpu(ctxt), msr_index, pdata);
8759
8760 return __kvm_emulate_msr_read(emul_to_vcpu(ctxt), msr_index, pdata);
8761 }
8762
emulator_check_rdpmc_early(struct x86_emulate_ctxt * ctxt,u32 pmc)8763 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
8764 {
8765 return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
8766 }
8767
emulator_read_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc,u64 * pdata)8768 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8769 u32 pmc, u64 *pdata)
8770 {
8771 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8772 }
8773
emulator_halt(struct x86_emulate_ctxt * ctxt)8774 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8775 {
8776 emul_to_vcpu(ctxt)->arch.halt_request = 1;
8777 }
8778
emulator_intercept(struct x86_emulate_ctxt * ctxt,struct x86_instruction_info * info,enum x86_intercept_stage stage)8779 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8780 struct x86_instruction_info *info,
8781 enum x86_intercept_stage stage)
8782 {
8783 return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
8784 &ctxt->exception);
8785 }
8786
emulator_get_cpuid(struct x86_emulate_ctxt * ctxt,u32 * eax,u32 * ebx,u32 * ecx,u32 * edx,bool exact_only)8787 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8788 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8789 bool exact_only)
8790 {
8791 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8792 }
8793
emulator_guest_has_movbe(struct x86_emulate_ctxt * ctxt)8794 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8795 {
8796 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8797 }
8798
emulator_guest_has_fxsr(struct x86_emulate_ctxt * ctxt)8799 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8800 {
8801 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8802 }
8803
emulator_guest_has_rdpid(struct x86_emulate_ctxt * ctxt)8804 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8805 {
8806 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8807 }
8808
emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt * ctxt)8809 static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
8810 {
8811 return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
8812 }
8813
emulator_read_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg)8814 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8815 {
8816 return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8817 }
8818
emulator_write_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg,ulong val)8819 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8820 {
8821 kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8822 }
8823
emulator_set_nmi_mask(struct x86_emulate_ctxt * ctxt,bool masked)8824 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8825 {
8826 kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8827 }
8828
emulator_is_smm(struct x86_emulate_ctxt * ctxt)8829 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
8830 {
8831 return is_smm(emul_to_vcpu(ctxt));
8832 }
8833
8834 #ifndef CONFIG_KVM_SMM
emulator_leave_smm(struct x86_emulate_ctxt * ctxt)8835 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8836 {
8837 WARN_ON_ONCE(1);
8838 return X86EMUL_UNHANDLEABLE;
8839 }
8840 #endif
8841
emulator_triple_fault(struct x86_emulate_ctxt * ctxt)8842 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8843 {
8844 kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8845 }
8846
emulator_set_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 xcr)8847 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8848 {
8849 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8850 }
8851
emulator_vm_bugged(struct x86_emulate_ctxt * ctxt)8852 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8853 {
8854 struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8855
8856 if (!kvm->vm_bugged)
8857 kvm_vm_bugged(kvm);
8858 }
8859
emulator_get_untagged_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8860 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8861 gva_t addr, unsigned int flags)
8862 {
8863 if (!kvm_x86_ops.get_untagged_addr)
8864 return addr;
8865
8866 return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
8867 addr, flags);
8868 }
8869
emulator_is_canonical_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8870 static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
8871 gva_t addr, unsigned int flags)
8872 {
8873 return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
8874 }
8875
8876 static const struct x86_emulate_ops emulate_ops = {
8877 .vm_bugged = emulator_vm_bugged,
8878 .read_gpr = emulator_read_gpr,
8879 .write_gpr = emulator_write_gpr,
8880 .read_std = emulator_read_std,
8881 .write_std = emulator_write_std,
8882 .fetch = kvm_fetch_guest_virt,
8883 .read_emulated = emulator_read_emulated,
8884 .write_emulated = emulator_write_emulated,
8885 .cmpxchg_emulated = emulator_cmpxchg_emulated,
8886 .invlpg = emulator_invlpg,
8887 .pio_in_emulated = emulator_pio_in_emulated,
8888 .pio_out_emulated = emulator_pio_out_emulated,
8889 .get_segment = emulator_get_segment,
8890 .set_segment = emulator_set_segment,
8891 .get_cached_segment_base = emulator_get_cached_segment_base,
8892 .get_gdt = emulator_get_gdt,
8893 .get_idt = emulator_get_idt,
8894 .set_gdt = emulator_set_gdt,
8895 .set_idt = emulator_set_idt,
8896 .get_cr = emulator_get_cr,
8897 .set_cr = emulator_set_cr,
8898 .cpl = emulator_get_cpl,
8899 .get_dr = emulator_get_dr,
8900 .set_dr = emulator_set_dr,
8901 .set_msr_with_filter = emulator_set_msr_with_filter,
8902 .get_msr_with_filter = emulator_get_msr_with_filter,
8903 .get_msr = emulator_get_msr,
8904 .check_rdpmc_early = emulator_check_rdpmc_early,
8905 .read_pmc = emulator_read_pmc,
8906 .halt = emulator_halt,
8907 .wbinvd = emulator_wbinvd,
8908 .fix_hypercall = emulator_fix_hypercall,
8909 .intercept = emulator_intercept,
8910 .get_cpuid = emulator_get_cpuid,
8911 .guest_has_movbe = emulator_guest_has_movbe,
8912 .guest_has_fxsr = emulator_guest_has_fxsr,
8913 .guest_has_rdpid = emulator_guest_has_rdpid,
8914 .guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
8915 .set_nmi_mask = emulator_set_nmi_mask,
8916 .is_smm = emulator_is_smm,
8917 .leave_smm = emulator_leave_smm,
8918 .triple_fault = emulator_triple_fault,
8919 .set_xcr = emulator_set_xcr,
8920 .get_untagged_addr = emulator_get_untagged_addr,
8921 .is_canonical_addr = emulator_is_canonical_addr,
8922 };
8923
toggle_interruptibility(struct kvm_vcpu * vcpu,u32 mask)8924 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8925 {
8926 u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
8927 /*
8928 * an sti; sti; sequence only disable interrupts for the first
8929 * instruction. So, if the last instruction, be it emulated or
8930 * not, left the system with the INT_STI flag enabled, it
8931 * means that the last instruction is an sti. We should not
8932 * leave the flag on in this case. The same goes for mov ss
8933 */
8934 if (int_shadow & mask)
8935 mask = 0;
8936 if (unlikely(int_shadow || mask)) {
8937 kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
8938 if (!mask)
8939 kvm_make_request(KVM_REQ_EVENT, vcpu);
8940 }
8941 }
8942
inject_emulated_exception(struct kvm_vcpu * vcpu)8943 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8944 {
8945 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8946
8947 if (ctxt->exception.vector == PF_VECTOR)
8948 kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8949 else if (ctxt->exception.error_code_valid)
8950 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8951 ctxt->exception.error_code);
8952 else
8953 kvm_queue_exception(vcpu, ctxt->exception.vector);
8954 }
8955
alloc_emulate_ctxt(struct kvm_vcpu * vcpu)8956 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8957 {
8958 struct x86_emulate_ctxt *ctxt;
8959
8960 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8961 if (!ctxt) {
8962 pr_err("failed to allocate vcpu's emulator\n");
8963 return NULL;
8964 }
8965
8966 ctxt->vcpu = vcpu;
8967 ctxt->ops = &emulate_ops;
8968 vcpu->arch.emulate_ctxt = ctxt;
8969
8970 return ctxt;
8971 }
8972
init_emulate_ctxt(struct kvm_vcpu * vcpu)8973 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8974 {
8975 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8976 int cs_db, cs_l;
8977
8978 kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8979
8980 ctxt->gpa_available = false;
8981 ctxt->eflags = kvm_get_rflags(vcpu);
8982 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8983
8984 ctxt->eip = kvm_rip_read(vcpu);
8985 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
8986 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
8987 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
8988 cs_db ? X86EMUL_MODE_PROT32 :
8989 X86EMUL_MODE_PROT16;
8990 ctxt->interruptibility = 0;
8991 ctxt->have_exception = false;
8992 ctxt->exception.vector = -1;
8993 ctxt->perm_ok = false;
8994
8995 init_decode_cache(ctxt);
8996 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8997 }
8998
kvm_inject_realmode_interrupt(struct kvm_vcpu * vcpu,int irq,int inc_eip)8999 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
9000 {
9001 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9002 int ret;
9003
9004 init_emulate_ctxt(vcpu);
9005
9006 ctxt->op_bytes = 2;
9007 ctxt->ad_bytes = 2;
9008 ctxt->_eip = ctxt->eip + inc_eip;
9009 ret = emulate_int_real(ctxt, irq);
9010
9011 if (ret != X86EMUL_CONTINUE) {
9012 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
9013 } else {
9014 ctxt->eip = ctxt->_eip;
9015 kvm_rip_write(vcpu, ctxt->eip);
9016 kvm_set_rflags(vcpu, ctxt->eflags);
9017 }
9018 }
9019 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_realmode_interrupt);
9020
prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata,u8 * insn_bytes,u8 insn_size)9021 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
9022 u8 ndata, u8 *insn_bytes, u8 insn_size)
9023 {
9024 struct kvm_run *run = vcpu->run;
9025 u64 info[5];
9026 u8 info_start;
9027
9028 /*
9029 * Zero the whole array used to retrieve the exit info, as casting to
9030 * u32 for select entries will leave some chunks uninitialized.
9031 */
9032 memset(&info, 0, sizeof(info));
9033
9034 kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
9035 (u32 *)&info[3], (u32 *)&info[4]);
9036
9037 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9038 run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
9039
9040 /*
9041 * There's currently space for 13 entries, but 5 are used for the exit
9042 * reason and info. Restrict to 4 to reduce the maintenance burden
9043 * when expanding kvm_run.emulation_failure in the future.
9044 */
9045 if (WARN_ON_ONCE(ndata > 4))
9046 ndata = 4;
9047
9048 /* Always include the flags as a 'data' entry. */
9049 info_start = 1;
9050 run->emulation_failure.flags = 0;
9051
9052 if (insn_size) {
9053 BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
9054 sizeof(run->emulation_failure.insn_bytes) != 16));
9055 info_start += 2;
9056 run->emulation_failure.flags |=
9057 KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
9058 run->emulation_failure.insn_size = insn_size;
9059 memset(run->emulation_failure.insn_bytes, 0x90,
9060 sizeof(run->emulation_failure.insn_bytes));
9061 memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
9062 }
9063
9064 memcpy(&run->internal.data[info_start], info, sizeof(info));
9065 memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
9066 ndata * sizeof(data[0]));
9067
9068 run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
9069 }
9070
prepare_emulation_ctxt_failure_exit(struct kvm_vcpu * vcpu)9071 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
9072 {
9073 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9074
9075 prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
9076 ctxt->fetch.end - ctxt->fetch.data);
9077 }
9078
__kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata)9079 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
9080 u8 ndata)
9081 {
9082 prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
9083 }
9084 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_prepare_emulation_failure_exit);
9085
kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu)9086 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
9087 {
9088 __kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
9089 }
9090 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_emulation_failure_exit);
9091
kvm_prepare_event_vectoring_exit(struct kvm_vcpu * vcpu,gpa_t gpa)9092 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa)
9093 {
9094 u32 reason, intr_info, error_code;
9095 struct kvm_run *run = vcpu->run;
9096 u64 info1, info2;
9097 int ndata = 0;
9098
9099 kvm_x86_call(get_exit_info)(vcpu, &reason, &info1, &info2,
9100 &intr_info, &error_code);
9101
9102 run->internal.data[ndata++] = info2;
9103 run->internal.data[ndata++] = reason;
9104 run->internal.data[ndata++] = info1;
9105 run->internal.data[ndata++] = gpa;
9106 run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
9107
9108 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9109 run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
9110 run->internal.ndata = ndata;
9111 }
9112 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_event_vectoring_exit);
9113
handle_emulation_failure(struct kvm_vcpu * vcpu,int emulation_type)9114 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
9115 {
9116 struct kvm *kvm = vcpu->kvm;
9117
9118 ++vcpu->stat.insn_emulation_fail;
9119 trace_kvm_emulate_insn_failed(vcpu);
9120
9121 if (emulation_type & EMULTYPE_VMWARE_GP) {
9122 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9123 return 1;
9124 }
9125
9126 if (kvm->arch.exit_on_emulation_error ||
9127 (emulation_type & EMULTYPE_SKIP)) {
9128 prepare_emulation_ctxt_failure_exit(vcpu);
9129 return 0;
9130 }
9131
9132 kvm_queue_exception(vcpu, UD_VECTOR);
9133
9134 if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
9135 prepare_emulation_ctxt_failure_exit(vcpu);
9136 return 0;
9137 }
9138
9139 return 1;
9140 }
9141
kvm_unprotect_and_retry_on_failure(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type)9142 static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
9143 gpa_t cr2_or_gpa,
9144 int emulation_type)
9145 {
9146 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
9147 return false;
9148
9149 /*
9150 * If the failed instruction faulted on an access to page tables that
9151 * are used to translate any part of the instruction, KVM can't resolve
9152 * the issue by unprotecting the gfn, as zapping the shadow page will
9153 * result in the instruction taking a !PRESENT page fault and thus put
9154 * the vCPU into an infinite loop of page faults. E.g. KVM will create
9155 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
9156 * then zap the SPTE to unprotect the gfn, and then do it all over
9157 * again. Report the error to userspace.
9158 */
9159 if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
9160 return false;
9161
9162 /*
9163 * If emulation may have been triggered by a write to a shadowed page
9164 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
9165 * guest to let the CPU re-execute the instruction in the hope that the
9166 * CPU can cleanly execute the instruction that KVM failed to emulate.
9167 */
9168 __kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
9169
9170 /*
9171 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
9172 * all SPTEs were already zapped by a different task. The alternative
9173 * is to report the error to userspace and likely terminate the guest,
9174 * and the last_retry_{eip,addr} checks will prevent retrying the page
9175 * fault indefinitely, i.e. there's nothing to lose by retrying.
9176 */
9177 return true;
9178 }
9179
9180 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
9181 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
9182
kvm_vcpu_check_hw_bp(unsigned long addr,u32 type,u32 dr7,unsigned long * db)9183 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
9184 unsigned long *db)
9185 {
9186 u32 dr6 = 0;
9187 int i;
9188 u32 enable, rwlen;
9189
9190 enable = dr7;
9191 rwlen = dr7 >> 16;
9192 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
9193 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
9194 dr6 |= (1 << i);
9195 return dr6;
9196 }
9197
kvm_vcpu_do_singlestep(struct kvm_vcpu * vcpu)9198 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
9199 {
9200 struct kvm_run *kvm_run = vcpu->run;
9201
9202 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
9203 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
9204 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
9205 kvm_run->debug.arch.exception = DB_VECTOR;
9206 kvm_run->exit_reason = KVM_EXIT_DEBUG;
9207 return 0;
9208 }
9209 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
9210 return 1;
9211 }
9212
kvm_skip_emulated_instruction(struct kvm_vcpu * vcpu)9213 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
9214 {
9215 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9216 int r;
9217
9218 r = kvm_x86_call(skip_emulated_instruction)(vcpu);
9219 if (unlikely(!r))
9220 return 0;
9221
9222 kvm_pmu_instruction_retired(vcpu);
9223
9224 /*
9225 * rflags is the old, "raw" value of the flags. The new value has
9226 * not been saved yet.
9227 *
9228 * This is correct even for TF set by the guest, because "the
9229 * processor will not generate this exception after the instruction
9230 * that sets the TF flag".
9231 */
9232 if (unlikely(rflags & X86_EFLAGS_TF))
9233 r = kvm_vcpu_do_singlestep(vcpu);
9234 return r;
9235 }
9236 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_skip_emulated_instruction);
9237
kvm_is_code_breakpoint_inhibited(struct kvm_vcpu * vcpu)9238 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
9239 {
9240 if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
9241 return true;
9242
9243 /*
9244 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
9245 * active, but AMD compatible CPUs do not.
9246 */
9247 if (!guest_cpuid_is_intel_compatible(vcpu))
9248 return false;
9249
9250 return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
9251 }
9252
kvm_vcpu_check_code_breakpoint(struct kvm_vcpu * vcpu,int emulation_type,int * r)9253 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
9254 int emulation_type, int *r)
9255 {
9256 WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
9257
9258 /*
9259 * Do not check for code breakpoints if hardware has already done the
9260 * checks, as inferred from the emulation type. On NO_DECODE and SKIP,
9261 * the instruction has passed all exception checks, and all intercepted
9262 * exceptions that trigger emulation have lower priority than code
9263 * breakpoints, i.e. the fact that the intercepted exception occurred
9264 * means any code breakpoints have already been serviced.
9265 *
9266 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
9267 * hardware has checked the RIP of the magic prefix, but not the RIP of
9268 * the instruction being emulated. The intent of forced emulation is
9269 * to behave as if KVM intercepted the instruction without an exception
9270 * and without a prefix.
9271 */
9272 if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
9273 EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
9274 return false;
9275
9276 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
9277 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
9278 struct kvm_run *kvm_run = vcpu->run;
9279 unsigned long eip = kvm_get_linear_rip(vcpu);
9280 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9281 vcpu->arch.guest_debug_dr7,
9282 vcpu->arch.eff_db);
9283
9284 if (dr6 != 0) {
9285 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
9286 kvm_run->debug.arch.pc = eip;
9287 kvm_run->debug.arch.exception = DB_VECTOR;
9288 kvm_run->exit_reason = KVM_EXIT_DEBUG;
9289 *r = 0;
9290 return true;
9291 }
9292 }
9293
9294 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
9295 !kvm_is_code_breakpoint_inhibited(vcpu)) {
9296 unsigned long eip = kvm_get_linear_rip(vcpu);
9297 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9298 vcpu->arch.dr7,
9299 vcpu->arch.db);
9300
9301 if (dr6 != 0) {
9302 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
9303 *r = 1;
9304 return true;
9305 }
9306 }
9307
9308 return false;
9309 }
9310
is_vmware_backdoor_opcode(struct x86_emulate_ctxt * ctxt)9311 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9312 {
9313 switch (ctxt->opcode_len) {
9314 case 1:
9315 switch (ctxt->b) {
9316 case 0xe4: /* IN */
9317 case 0xe5:
9318 case 0xec:
9319 case 0xed:
9320 case 0xe6: /* OUT */
9321 case 0xe7:
9322 case 0xee:
9323 case 0xef:
9324 case 0x6c: /* INS */
9325 case 0x6d:
9326 case 0x6e: /* OUTS */
9327 case 0x6f:
9328 return true;
9329 }
9330 break;
9331 case 2:
9332 switch (ctxt->b) {
9333 case 0x33: /* RDPMC */
9334 return true;
9335 }
9336 break;
9337 }
9338
9339 return false;
9340 }
9341
9342 /*
9343 * Decode an instruction for emulation. The caller is responsible for handling
9344 * code breakpoints. Note, manually detecting code breakpoints is unnecessary
9345 * (and wrong) when emulating on an intercepted fault-like exception[*], as
9346 * code breakpoints have higher priority and thus have already been done by
9347 * hardware.
9348 *
9349 * [*] Except #MC, which is higher priority, but KVM should never emulate in
9350 * response to a machine check.
9351 */
x86_decode_emulated_instruction(struct kvm_vcpu * vcpu,int emulation_type,void * insn,int insn_len)9352 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9353 void *insn, int insn_len)
9354 {
9355 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9356 int r;
9357
9358 init_emulate_ctxt(vcpu);
9359
9360 r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
9361
9362 trace_kvm_emulate_insn_start(vcpu);
9363 ++vcpu->stat.insn_emulation;
9364
9365 return r;
9366 }
9367 EXPORT_SYMBOL_FOR_KVM_INTERNAL(x86_decode_emulated_instruction);
9368
x86_emulate_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type,void * insn,int insn_len)9369 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9370 int emulation_type, void *insn, int insn_len)
9371 {
9372 int r;
9373 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9374 bool writeback = true;
9375
9376 if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9377 (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
9378 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
9379 emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
9380
9381 r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
9382 if (r != X86EMUL_CONTINUE) {
9383 if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9384 return 1;
9385
9386 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9387 emulation_type))
9388 return 1;
9389
9390 if (r == X86EMUL_UNHANDLEABLE_VECTORING) {
9391 kvm_prepare_event_vectoring_exit(vcpu, cr2_or_gpa);
9392 return 0;
9393 }
9394
9395 WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9396 return handle_emulation_failure(vcpu, emulation_type);
9397 }
9398
9399 vcpu->arch.l1tf_flush_l1d = true;
9400
9401 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
9402 kvm_clear_exception_queue(vcpu);
9403
9404 /*
9405 * Return immediately if RIP hits a code breakpoint, such #DBs
9406 * are fault-like and are higher priority than any faults on
9407 * the code fetch itself.
9408 */
9409 if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
9410 return r;
9411
9412 r = x86_decode_emulated_instruction(vcpu, emulation_type,
9413 insn, insn_len);
9414 if (r != EMULATION_OK) {
9415 if ((emulation_type & EMULTYPE_TRAP_UD) ||
9416 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9417 kvm_queue_exception(vcpu, UD_VECTOR);
9418 return 1;
9419 }
9420 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9421 emulation_type))
9422 return 1;
9423
9424 if (ctxt->have_exception &&
9425 !(emulation_type & EMULTYPE_SKIP)) {
9426 /*
9427 * #UD should result in just EMULATION_FAILED, and trap-like
9428 * exception should not be encountered during decode.
9429 */
9430 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9431 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
9432 inject_emulated_exception(vcpu);
9433 return 1;
9434 }
9435 return handle_emulation_failure(vcpu, emulation_type);
9436 }
9437 }
9438
9439 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9440 !is_vmware_backdoor_opcode(ctxt)) {
9441 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9442 return 1;
9443 }
9444
9445 /*
9446 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9447 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9448 * The caller is responsible for updating interruptibility state and
9449 * injecting single-step #DBs.
9450 */
9451 if (emulation_type & EMULTYPE_SKIP) {
9452 if (ctxt->mode != X86EMUL_MODE_PROT64)
9453 ctxt->eip = (u32)ctxt->_eip;
9454 else
9455 ctxt->eip = ctxt->_eip;
9456
9457 if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9458 r = 1;
9459 goto writeback;
9460 }
9461
9462 kvm_rip_write(vcpu, ctxt->eip);
9463 if (ctxt->eflags & X86_EFLAGS_RF)
9464 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
9465 return 1;
9466 }
9467
9468 /*
9469 * If emulation was caused by a write-protection #PF on a non-page_table
9470 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
9471 * and retry the instruction, as the vCPU is likely no longer using the
9472 * gfn as a page table.
9473 */
9474 if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9475 !x86_page_table_writing_insn(ctxt) &&
9476 kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
9477 return 1;
9478
9479 /* this is needed for vmware backdoor interface to work since it
9480 changes registers values during IO operation */
9481 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9482 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9483 emulator_invalidate_register_cache(ctxt);
9484 }
9485
9486 restart:
9487 if (emulation_type & EMULTYPE_PF) {
9488 /* Save the faulting GPA (cr2) in the address field */
9489 ctxt->exception.address = cr2_or_gpa;
9490
9491 /* With shadow page tables, cr2 contains a GVA or nGPA. */
9492 if (vcpu->arch.mmu->root_role.direct) {
9493 ctxt->gpa_available = true;
9494 ctxt->gpa_val = cr2_or_gpa;
9495 }
9496 } else {
9497 /* Sanitize the address out of an abundance of paranoia. */
9498 ctxt->exception.address = 0;
9499 }
9500
9501 /*
9502 * Check L1's instruction intercepts when emulating instructions for
9503 * L2, unless KVM is re-emulating a previously decoded instruction,
9504 * e.g. to complete userspace I/O, in which case KVM has already
9505 * checked the intercepts.
9506 */
9507 r = x86_emulate_insn(ctxt, is_guest_mode(vcpu) &&
9508 !(emulation_type & EMULTYPE_NO_DECODE));
9509
9510 if (r == EMULATION_INTERCEPTED)
9511 return 1;
9512
9513 if (r == EMULATION_FAILED) {
9514 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9515 emulation_type))
9516 return 1;
9517
9518 return handle_emulation_failure(vcpu, emulation_type);
9519 }
9520
9521 if (ctxt->have_exception) {
9522 WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9523 vcpu->mmio_needed = false;
9524 r = 1;
9525 inject_emulated_exception(vcpu);
9526 } else if (vcpu->arch.pio.count) {
9527 if (!vcpu->arch.pio.in) {
9528 /* FIXME: return into emulator if single-stepping. */
9529 vcpu->arch.pio.count = 0;
9530 } else {
9531 writeback = false;
9532 vcpu->arch.complete_userspace_io = complete_emulated_pio;
9533 }
9534 r = 0;
9535 } else if (vcpu->mmio_needed) {
9536 ++vcpu->stat.mmio_exits;
9537
9538 if (!vcpu->mmio_is_write)
9539 writeback = false;
9540 r = 0;
9541 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9542 } else if (vcpu->arch.complete_userspace_io) {
9543 writeback = false;
9544 r = 0;
9545 } else if (r == EMULATION_RESTART)
9546 goto restart;
9547 else
9548 r = 1;
9549
9550 writeback:
9551 if (writeback) {
9552 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9553 toggle_interruptibility(vcpu, ctxt->interruptibility);
9554 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9555
9556 /*
9557 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9558 * only supports code breakpoints and general detect #DB, both
9559 * of which are fault-like.
9560 */
9561 if (!ctxt->have_exception ||
9562 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9563 kvm_pmu_instruction_retired(vcpu);
9564 if (ctxt->is_branch)
9565 kvm_pmu_branch_retired(vcpu);
9566 kvm_rip_write(vcpu, ctxt->eip);
9567 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9568 r = kvm_vcpu_do_singlestep(vcpu);
9569 kvm_x86_call(update_emulated_instruction)(vcpu);
9570 __kvm_set_rflags(vcpu, ctxt->eflags);
9571 }
9572
9573 /*
9574 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9575 * do nothing, and it will be requested again as soon as
9576 * the shadow expires. But we still need to check here,
9577 * because POPF has no interrupt shadow.
9578 */
9579 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9580 kvm_make_request(KVM_REQ_EVENT, vcpu);
9581 } else
9582 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9583
9584 return r;
9585 }
9586
kvm_emulate_instruction(struct kvm_vcpu * vcpu,int emulation_type)9587 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9588 {
9589 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9590 }
9591 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction);
9592
kvm_emulate_instruction_from_buffer(struct kvm_vcpu * vcpu,void * insn,int insn_len)9593 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9594 void *insn, int insn_len)
9595 {
9596 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9597 }
9598 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction_from_buffer);
9599
complete_fast_pio_out_port_0x7e(struct kvm_vcpu * vcpu)9600 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9601 {
9602 vcpu->arch.pio.count = 0;
9603 return 1;
9604 }
9605
complete_fast_pio_out(struct kvm_vcpu * vcpu)9606 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9607 {
9608 vcpu->arch.pio.count = 0;
9609
9610 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip)))
9611 return 1;
9612
9613 return kvm_skip_emulated_instruction(vcpu);
9614 }
9615
kvm_fast_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port)9616 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9617 unsigned short port)
9618 {
9619 unsigned long val = kvm_rax_read(vcpu);
9620 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9621
9622 if (ret)
9623 return ret;
9624
9625 /*
9626 * Workaround userspace that relies on old KVM behavior of %rip being
9627 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9628 */
9629 if (port == 0x7e &&
9630 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9631 vcpu->arch.complete_userspace_io =
9632 complete_fast_pio_out_port_0x7e;
9633 kvm_skip_emulated_instruction(vcpu);
9634 } else {
9635 vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9636 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9637 }
9638 return 0;
9639 }
9640
complete_fast_pio_in(struct kvm_vcpu * vcpu)9641 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9642 {
9643 unsigned long val;
9644
9645 /* We should only ever be called with arch.pio.count equal to 1 */
9646 BUG_ON(vcpu->arch.pio.count != 1);
9647
9648 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip))) {
9649 vcpu->arch.pio.count = 0;
9650 return 1;
9651 }
9652
9653 /* For size less than 4 we merge, else we zero extend */
9654 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9655
9656 complete_emulator_pio_in(vcpu, &val);
9657 kvm_rax_write(vcpu, val);
9658
9659 return kvm_skip_emulated_instruction(vcpu);
9660 }
9661
kvm_fast_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port)9662 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9663 unsigned short port)
9664 {
9665 unsigned long val;
9666 int ret;
9667
9668 /* For size less than 4 we merge, else we zero extend */
9669 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9670
9671 ret = emulator_pio_in(vcpu, size, port, &val, 1);
9672 if (ret) {
9673 kvm_rax_write(vcpu, val);
9674 return ret;
9675 }
9676
9677 vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9678 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9679
9680 return 0;
9681 }
9682
kvm_fast_pio(struct kvm_vcpu * vcpu,int size,unsigned short port,int in)9683 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9684 {
9685 int ret;
9686
9687 if (in)
9688 ret = kvm_fast_pio_in(vcpu, size, port);
9689 else
9690 ret = kvm_fast_pio_out(vcpu, size, port);
9691 return ret && kvm_skip_emulated_instruction(vcpu);
9692 }
9693 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fast_pio);
9694
kvmclock_cpu_down_prep(unsigned int cpu)9695 static int kvmclock_cpu_down_prep(unsigned int cpu)
9696 {
9697 __this_cpu_write(cpu_tsc_khz, 0);
9698 return 0;
9699 }
9700
tsc_khz_changed(void * data)9701 static void tsc_khz_changed(void *data)
9702 {
9703 struct cpufreq_freqs *freq = data;
9704 unsigned long khz;
9705
9706 WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9707
9708 if (data)
9709 khz = freq->new;
9710 else
9711 khz = cpufreq_quick_get(raw_smp_processor_id());
9712 if (!khz)
9713 khz = tsc_khz;
9714 __this_cpu_write(cpu_tsc_khz, khz);
9715 }
9716
9717 #ifdef CONFIG_X86_64
kvm_hyperv_tsc_notifier(void)9718 static void kvm_hyperv_tsc_notifier(void)
9719 {
9720 struct kvm *kvm;
9721 int cpu;
9722
9723 mutex_lock(&kvm_lock);
9724 list_for_each_entry(kvm, &vm_list, vm_list)
9725 kvm_make_mclock_inprogress_request(kvm);
9726
9727 /* no guest entries from this point */
9728 hyperv_stop_tsc_emulation();
9729
9730 /* TSC frequency always matches when on Hyper-V */
9731 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9732 for_each_present_cpu(cpu)
9733 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9734 }
9735 kvm_caps.max_guest_tsc_khz = tsc_khz;
9736
9737 list_for_each_entry(kvm, &vm_list, vm_list) {
9738 __kvm_start_pvclock_update(kvm);
9739 pvclock_update_vm_gtod_copy(kvm);
9740 kvm_end_pvclock_update(kvm);
9741 }
9742
9743 mutex_unlock(&kvm_lock);
9744 }
9745 #endif
9746
__kvmclock_cpufreq_notifier(struct cpufreq_freqs * freq,int cpu)9747 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9748 {
9749 struct kvm *kvm;
9750 struct kvm_vcpu *vcpu;
9751 int send_ipi = 0;
9752 unsigned long i;
9753
9754 /*
9755 * We allow guests to temporarily run on slowing clocks,
9756 * provided we notify them after, or to run on accelerating
9757 * clocks, provided we notify them before. Thus time never
9758 * goes backwards.
9759 *
9760 * However, we have a problem. We can't atomically update
9761 * the frequency of a given CPU from this function; it is
9762 * merely a notifier, which can be called from any CPU.
9763 * Changing the TSC frequency at arbitrary points in time
9764 * requires a recomputation of local variables related to
9765 * the TSC for each VCPU. We must flag these local variables
9766 * to be updated and be sure the update takes place with the
9767 * new frequency before any guests proceed.
9768 *
9769 * Unfortunately, the combination of hotplug CPU and frequency
9770 * change creates an intractable locking scenario; the order
9771 * of when these callouts happen is undefined with respect to
9772 * CPU hotplug, and they can race with each other. As such,
9773 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9774 * undefined; you can actually have a CPU frequency change take
9775 * place in between the computation of X and the setting of the
9776 * variable. To protect against this problem, all updates of
9777 * the per_cpu tsc_khz variable are done in an interrupt
9778 * protected IPI, and all callers wishing to update the value
9779 * must wait for a synchronous IPI to complete (which is trivial
9780 * if the caller is on the CPU already). This establishes the
9781 * necessary total order on variable updates.
9782 *
9783 * Note that because a guest time update may take place
9784 * anytime after the setting of the VCPU's request bit, the
9785 * correct TSC value must be set before the request. However,
9786 * to ensure the update actually makes it to any guest which
9787 * starts running in hardware virtualization between the set
9788 * and the acquisition of the spinlock, we must also ping the
9789 * CPU after setting the request bit.
9790 *
9791 */
9792
9793 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9794
9795 mutex_lock(&kvm_lock);
9796 list_for_each_entry(kvm, &vm_list, vm_list) {
9797 kvm_for_each_vcpu(i, vcpu, kvm) {
9798 if (vcpu->cpu != cpu)
9799 continue;
9800 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9801 if (vcpu->cpu != raw_smp_processor_id())
9802 send_ipi = 1;
9803 }
9804 }
9805 mutex_unlock(&kvm_lock);
9806
9807 if (freq->old < freq->new && send_ipi) {
9808 /*
9809 * We upscale the frequency. Must make the guest
9810 * doesn't see old kvmclock values while running with
9811 * the new frequency, otherwise we risk the guest sees
9812 * time go backwards.
9813 *
9814 * In case we update the frequency for another cpu
9815 * (which might be in guest context) send an interrupt
9816 * to kick the cpu out of guest context. Next time
9817 * guest context is entered kvmclock will be updated,
9818 * so the guest will not see stale values.
9819 */
9820 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9821 }
9822 }
9823
kvmclock_cpufreq_notifier(struct notifier_block * nb,unsigned long val,void * data)9824 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9825 void *data)
9826 {
9827 struct cpufreq_freqs *freq = data;
9828 int cpu;
9829
9830 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9831 return 0;
9832 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9833 return 0;
9834
9835 for_each_cpu(cpu, freq->policy->cpus)
9836 __kvmclock_cpufreq_notifier(freq, cpu);
9837
9838 return 0;
9839 }
9840
9841 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9842 .notifier_call = kvmclock_cpufreq_notifier
9843 };
9844
kvmclock_cpu_online(unsigned int cpu)9845 static int kvmclock_cpu_online(unsigned int cpu)
9846 {
9847 tsc_khz_changed(NULL);
9848 return 0;
9849 }
9850
kvm_timer_init(void)9851 static void kvm_timer_init(void)
9852 {
9853 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9854 max_tsc_khz = tsc_khz;
9855
9856 if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9857 struct cpufreq_policy *policy;
9858 int cpu;
9859
9860 cpu = get_cpu();
9861 policy = cpufreq_cpu_get(cpu);
9862 if (policy) {
9863 if (policy->cpuinfo.max_freq)
9864 max_tsc_khz = policy->cpuinfo.max_freq;
9865 cpufreq_cpu_put(policy);
9866 }
9867 put_cpu();
9868 }
9869 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9870 CPUFREQ_TRANSITION_NOTIFIER);
9871
9872 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9873 kvmclock_cpu_online, kvmclock_cpu_down_prep);
9874 }
9875 }
9876
9877 #ifdef CONFIG_X86_64
pvclock_gtod_update_fn(struct work_struct * work)9878 static void pvclock_gtod_update_fn(struct work_struct *work)
9879 {
9880 struct kvm *kvm;
9881 struct kvm_vcpu *vcpu;
9882 unsigned long i;
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 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9888 atomic_set(&kvm_guest_has_master_clock, 0);
9889 mutex_unlock(&kvm_lock);
9890 }
9891
9892 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9893
9894 /*
9895 * Indirection to move queue_work() out of the tk_core.seq write held
9896 * region to prevent possible deadlocks against time accessors which
9897 * are invoked with work related locks held.
9898 */
pvclock_irq_work_fn(struct irq_work * w)9899 static void pvclock_irq_work_fn(struct irq_work *w)
9900 {
9901 queue_work(system_long_wq, &pvclock_gtod_work);
9902 }
9903
9904 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9905
9906 /*
9907 * Notification about pvclock gtod data update.
9908 */
pvclock_gtod_notify(struct notifier_block * nb,unsigned long unused,void * priv)9909 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9910 void *priv)
9911 {
9912 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9913 struct timekeeper *tk = priv;
9914
9915 update_pvclock_gtod(tk);
9916
9917 /*
9918 * Disable master clock if host does not trust, or does not use,
9919 * TSC based clocksource. Delegate queue_work() to irq_work as
9920 * this is invoked with tk_core.seq write held.
9921 */
9922 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9923 atomic_read(&kvm_guest_has_master_clock) != 0)
9924 irq_work_queue(&pvclock_irq_work);
9925 return 0;
9926 }
9927
9928 static struct notifier_block pvclock_gtod_notifier = {
9929 .notifier_call = pvclock_gtod_notify,
9930 };
9931 #endif
9932
kvm_ops_update(struct kvm_x86_init_ops * ops)9933 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
9934 {
9935 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9936
9937 #define __KVM_X86_OP(func) \
9938 static_call_update(kvm_x86_##func, kvm_x86_ops.func);
9939 #define KVM_X86_OP(func) \
9940 WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
9941 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
9942 #define KVM_X86_OP_OPTIONAL_RET0(func) \
9943 static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
9944 (void *)__static_call_return0);
9945 #include <asm/kvm-x86-ops.h>
9946 #undef __KVM_X86_OP
9947
9948 kvm_pmu_ops_update(ops->pmu_ops);
9949 }
9950
kvm_x86_check_processor_compatibility(void)9951 static int kvm_x86_check_processor_compatibility(void)
9952 {
9953 int cpu = smp_processor_id();
9954 struct cpuinfo_x86 *c = &cpu_data(cpu);
9955
9956 /*
9957 * Compatibility checks are done when loading KVM and when enabling
9958 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
9959 * compatible, i.e. KVM should never perform a compatibility check on
9960 * an offline CPU.
9961 */
9962 WARN_ON(!cpu_online(cpu));
9963
9964 if (__cr4_reserved_bits(cpu_has, c) !=
9965 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9966 return -EIO;
9967
9968 return kvm_x86_call(check_processor_compatibility)();
9969 }
9970
kvm_x86_check_cpu_compat(void * ret)9971 static void kvm_x86_check_cpu_compat(void *ret)
9972 {
9973 *(int *)ret = kvm_x86_check_processor_compatibility();
9974 }
9975
kvm_x86_vendor_init(struct kvm_x86_init_ops * ops)9976 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
9977 {
9978 u64 host_pat;
9979 int r, cpu;
9980
9981 guard(mutex)(&vendor_module_lock);
9982
9983 if (kvm_x86_ops.enable_virtualization_cpu) {
9984 pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
9985 return -EEXIST;
9986 }
9987
9988 /*
9989 * KVM explicitly assumes that the guest has an FPU and
9990 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9991 * vCPU's FPU state as a fxregs_state struct.
9992 */
9993 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9994 pr_err("inadequate fpu\n");
9995 return -EOPNOTSUPP;
9996 }
9997
9998 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9999 pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
10000 return -EOPNOTSUPP;
10001 }
10002
10003 /*
10004 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
10005 * the PAT bits in SPTEs. Bail if PAT[0] is programmed to something
10006 * other than WB. Note, EPT doesn't utilize the PAT, but don't bother
10007 * with an exception. PAT[0] is set to WB on RESET and also by the
10008 * kernel, i.e. failure indicates a kernel bug or broken firmware.
10009 */
10010 if (rdmsrq_safe(MSR_IA32_CR_PAT, &host_pat) ||
10011 (host_pat & GENMASK(2, 0)) != 6) {
10012 pr_err("host PAT[0] is not WB\n");
10013 return -EIO;
10014 }
10015
10016 if (boot_cpu_has(X86_FEATURE_SHSTK) || boot_cpu_has(X86_FEATURE_IBT)) {
10017 rdmsrq(MSR_IA32_S_CET, kvm_host.s_cet);
10018 /*
10019 * Linux doesn't yet support supervisor shadow stacks (SSS), so
10020 * KVM doesn't save/restore the associated MSRs, i.e. KVM may
10021 * clobber the host values. Yell and refuse to load if SSS is
10022 * unexpectedly enabled, e.g. to avoid crashing the host.
10023 */
10024 if (WARN_ON_ONCE(kvm_host.s_cet & CET_SHSTK_EN))
10025 return -EIO;
10026 }
10027
10028 memset(&kvm_caps, 0, sizeof(kvm_caps));
10029
10030 x86_emulator_cache = kvm_alloc_emulator_cache();
10031 if (!x86_emulator_cache) {
10032 pr_err("failed to allocate cache for x86 emulator\n");
10033 return -ENOMEM;
10034 }
10035
10036 user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
10037 if (!user_return_msrs) {
10038 pr_err("failed to allocate percpu kvm_user_return_msrs\n");
10039 r = -ENOMEM;
10040 goto out_free_x86_emulator_cache;
10041 }
10042 kvm_nr_uret_msrs = 0;
10043
10044 r = kvm_mmu_vendor_module_init();
10045 if (r)
10046 goto out_free_percpu;
10047
10048 kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
10049 kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
10050
10051 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
10052 kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
10053 kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
10054 }
10055
10056 if (boot_cpu_has(X86_FEATURE_XSAVES)) {
10057 rdmsrq(MSR_IA32_XSS, kvm_host.xss);
10058 kvm_caps.supported_xss = kvm_host.xss & KVM_SUPPORTED_XSS;
10059 }
10060
10061 kvm_caps.supported_quirks = KVM_X86_VALID_QUIRKS;
10062 kvm_caps.inapplicable_quirks = KVM_X86_CONDITIONAL_QUIRKS;
10063
10064 rdmsrq_safe(MSR_EFER, &kvm_host.efer);
10065
10066 kvm_init_pmu_capability(ops->pmu_ops);
10067
10068 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
10069 rdmsrq(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
10070
10071 r = ops->hardware_setup();
10072 if (r != 0)
10073 goto out_mmu_exit;
10074
10075 enable_device_posted_irqs &= enable_apicv &&
10076 irq_remapping_cap(IRQ_POSTING_CAP);
10077
10078 kvm_ops_update(ops);
10079
10080 for_each_online_cpu(cpu) {
10081 smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
10082 if (r < 0)
10083 goto out_unwind_ops;
10084 }
10085
10086 /*
10087 * Point of no return! DO NOT add error paths below this point unless
10088 * absolutely necessary, as most operations from this point forward
10089 * require unwinding.
10090 */
10091 kvm_timer_init();
10092
10093 if (pi_inject_timer == -1)
10094 pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
10095 #ifdef CONFIG_X86_64
10096 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
10097
10098 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
10099 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
10100 #endif
10101
10102 kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
10103
10104 if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
10105 kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
10106
10107 /* KVM always ignores guest PAT for shadow paging. */
10108 if (!tdp_enabled)
10109 kvm_caps.supported_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT;
10110
10111 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
10112 kvm_caps.supported_xss = 0;
10113
10114 if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
10115 !kvm_cpu_cap_has(X86_FEATURE_IBT))
10116 kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
10117
10118 if ((kvm_caps.supported_xss & XFEATURE_MASK_CET_ALL) != XFEATURE_MASK_CET_ALL) {
10119 kvm_cpu_cap_clear(X86_FEATURE_SHSTK);
10120 kvm_cpu_cap_clear(X86_FEATURE_IBT);
10121 kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
10122 }
10123
10124 if (kvm_caps.has_tsc_control) {
10125 /*
10126 * Make sure the user can only configure tsc_khz values that
10127 * fit into a signed integer.
10128 * A min value is not calculated because it will always
10129 * be 1 on all machines.
10130 */
10131 u64 max = min(0x7fffffffULL,
10132 __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
10133 kvm_caps.max_guest_tsc_khz = max;
10134 }
10135 kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
10136 kvm_init_msr_lists();
10137 return 0;
10138
10139 out_unwind_ops:
10140 kvm_x86_ops.enable_virtualization_cpu = NULL;
10141 kvm_x86_call(hardware_unsetup)();
10142 out_mmu_exit:
10143 kvm_mmu_vendor_module_exit();
10144 out_free_percpu:
10145 free_percpu(user_return_msrs);
10146 out_free_x86_emulator_cache:
10147 kmem_cache_destroy(x86_emulator_cache);
10148 return r;
10149 }
10150 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_init);
10151
kvm_x86_vendor_exit(void)10152 void kvm_x86_vendor_exit(void)
10153 {
10154 kvm_unregister_perf_callbacks();
10155
10156 #ifdef CONFIG_X86_64
10157 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
10158 clear_hv_tscchange_cb();
10159 #endif
10160 kvm_lapic_exit();
10161
10162 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
10163 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
10164 CPUFREQ_TRANSITION_NOTIFIER);
10165 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
10166 }
10167 #ifdef CONFIG_X86_64
10168 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
10169 irq_work_sync(&pvclock_irq_work);
10170 cancel_work_sync(&pvclock_gtod_work);
10171 #endif
10172 kvm_x86_call(hardware_unsetup)();
10173 kvm_mmu_vendor_module_exit();
10174 free_percpu(user_return_msrs);
10175 kmem_cache_destroy(x86_emulator_cache);
10176 #ifdef CONFIG_KVM_XEN
10177 static_key_deferred_flush(&kvm_xen_enabled);
10178 WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
10179 #endif
10180 mutex_lock(&vendor_module_lock);
10181 kvm_x86_ops.enable_virtualization_cpu = NULL;
10182 mutex_unlock(&vendor_module_lock);
10183 }
10184 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_exit);
10185
10186 #ifdef CONFIG_X86_64
kvm_pv_clock_pairing(struct kvm_vcpu * vcpu,gpa_t paddr,unsigned long clock_type)10187 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
10188 unsigned long clock_type)
10189 {
10190 struct kvm_clock_pairing clock_pairing;
10191 struct timespec64 ts;
10192 u64 cycle;
10193 int ret;
10194
10195 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
10196 return -KVM_EOPNOTSUPP;
10197
10198 /*
10199 * When tsc is in permanent catchup mode guests won't be able to use
10200 * pvclock_read_retry loop to get consistent view of pvclock
10201 */
10202 if (vcpu->arch.tsc_always_catchup)
10203 return -KVM_EOPNOTSUPP;
10204
10205 if (!kvm_get_walltime_and_clockread(&ts, &cycle))
10206 return -KVM_EOPNOTSUPP;
10207
10208 clock_pairing.sec = ts.tv_sec;
10209 clock_pairing.nsec = ts.tv_nsec;
10210 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
10211 clock_pairing.flags = 0;
10212 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
10213
10214 ret = 0;
10215 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
10216 sizeof(struct kvm_clock_pairing)))
10217 ret = -KVM_EFAULT;
10218
10219 return ret;
10220 }
10221 #endif
10222
10223 /*
10224 * kvm_pv_kick_cpu_op: Kick a vcpu.
10225 *
10226 * @apicid - apicid of vcpu to be kicked.
10227 */
kvm_pv_kick_cpu_op(struct kvm * kvm,int apicid)10228 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
10229 {
10230 /*
10231 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
10232 * common code, e.g. for tracing. Defer initialization to the compiler.
10233 */
10234 struct kvm_lapic_irq lapic_irq = {
10235 .delivery_mode = APIC_DM_REMRD,
10236 .dest_mode = APIC_DEST_PHYSICAL,
10237 .shorthand = APIC_DEST_NOSHORT,
10238 .dest_id = apicid,
10239 };
10240
10241 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
10242 }
10243
kvm_apicv_activated(struct kvm * kvm)10244 bool kvm_apicv_activated(struct kvm *kvm)
10245 {
10246 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
10247 }
10248 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_apicv_activated);
10249
kvm_vcpu_apicv_activated(struct kvm_vcpu * vcpu)10250 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
10251 {
10252 ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
10253 ulong vcpu_reasons =
10254 kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
10255
10256 return (vm_reasons | vcpu_reasons) == 0;
10257 }
10258 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_apicv_activated);
10259
set_or_clear_apicv_inhibit(unsigned long * inhibits,enum kvm_apicv_inhibit reason,bool set)10260 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
10261 enum kvm_apicv_inhibit reason, bool set)
10262 {
10263 const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
10264
10265 BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
10266
10267 if (set)
10268 __set_bit(reason, inhibits);
10269 else
10270 __clear_bit(reason, inhibits);
10271
10272 trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
10273 }
10274
kvm_apicv_init(struct kvm * kvm)10275 static void kvm_apicv_init(struct kvm *kvm)
10276 {
10277 enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
10278 APICV_INHIBIT_REASON_DISABLED;
10279
10280 set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
10281
10282 init_rwsem(&kvm->arch.apicv_update_lock);
10283 }
10284
kvm_sched_yield(struct kvm_vcpu * vcpu,unsigned long dest_id)10285 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
10286 {
10287 struct kvm_vcpu *target = NULL;
10288 struct kvm_apic_map *map;
10289
10290 vcpu->stat.directed_yield_attempted++;
10291
10292 if (single_task_running())
10293 goto no_yield;
10294
10295 rcu_read_lock();
10296 map = rcu_dereference(vcpu->kvm->arch.apic_map);
10297
10298 if (likely(map) && dest_id <= map->max_apic_id) {
10299 dest_id = array_index_nospec(dest_id, map->max_apic_id + 1);
10300 if (map->phys_map[dest_id])
10301 target = map->phys_map[dest_id]->vcpu;
10302 }
10303
10304 rcu_read_unlock();
10305
10306 if (!target || !READ_ONCE(target->ready))
10307 goto no_yield;
10308
10309 /* Ignore requests to yield to self */
10310 if (vcpu == target)
10311 goto no_yield;
10312
10313 if (kvm_vcpu_yield_to(target) <= 0)
10314 goto no_yield;
10315
10316 vcpu->stat.directed_yield_successful++;
10317
10318 no_yield:
10319 return;
10320 }
10321
complete_hypercall_exit(struct kvm_vcpu * vcpu)10322 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
10323 {
10324 u64 ret = vcpu->run->hypercall.ret;
10325
10326 if (!is_64_bit_hypercall(vcpu))
10327 ret = (u32)ret;
10328 kvm_rax_write(vcpu, ret);
10329 return kvm_skip_emulated_instruction(vcpu);
10330 }
10331
____kvm_emulate_hypercall(struct kvm_vcpu * vcpu,int cpl,int (* complete_hypercall)(struct kvm_vcpu *))10332 int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
10333 int (*complete_hypercall)(struct kvm_vcpu *))
10334 {
10335 unsigned long ret;
10336 unsigned long nr = kvm_rax_read(vcpu);
10337 unsigned long a0 = kvm_rbx_read(vcpu);
10338 unsigned long a1 = kvm_rcx_read(vcpu);
10339 unsigned long a2 = kvm_rdx_read(vcpu);
10340 unsigned long a3 = kvm_rsi_read(vcpu);
10341 int op_64_bit = is_64_bit_hypercall(vcpu);
10342
10343 ++vcpu->stat.hypercalls;
10344
10345 trace_kvm_hypercall(nr, a0, a1, a2, a3);
10346
10347 if (!op_64_bit) {
10348 nr &= 0xFFFFFFFF;
10349 a0 &= 0xFFFFFFFF;
10350 a1 &= 0xFFFFFFFF;
10351 a2 &= 0xFFFFFFFF;
10352 a3 &= 0xFFFFFFFF;
10353 }
10354
10355 if (cpl) {
10356 ret = -KVM_EPERM;
10357 goto out;
10358 }
10359
10360 ret = -KVM_ENOSYS;
10361
10362 switch (nr) {
10363 case KVM_HC_VAPIC_POLL_IRQ:
10364 ret = 0;
10365 break;
10366 case KVM_HC_KICK_CPU:
10367 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10368 break;
10369
10370 kvm_pv_kick_cpu_op(vcpu->kvm, a1);
10371 kvm_sched_yield(vcpu, a1);
10372 ret = 0;
10373 break;
10374 #ifdef CONFIG_X86_64
10375 case KVM_HC_CLOCK_PAIRING:
10376 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10377 break;
10378 #endif
10379 case KVM_HC_SEND_IPI:
10380 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10381 break;
10382
10383 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10384 break;
10385 case KVM_HC_SCHED_YIELD:
10386 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10387 break;
10388
10389 kvm_sched_yield(vcpu, a0);
10390 ret = 0;
10391 break;
10392 case KVM_HC_MAP_GPA_RANGE: {
10393 u64 gpa = a0, npages = a1, attrs = a2;
10394
10395 ret = -KVM_ENOSYS;
10396 if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE))
10397 break;
10398
10399 if (!PAGE_ALIGNED(gpa) || !npages ||
10400 gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10401 ret = -KVM_EINVAL;
10402 break;
10403 }
10404
10405 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
10406 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
10407 /*
10408 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
10409 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
10410 * it was always zero on KVM_EXIT_HYPERCALL. Since KVM is now overwriting
10411 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
10412 */
10413 vcpu->run->hypercall.ret = 0;
10414 vcpu->run->hypercall.args[0] = gpa;
10415 vcpu->run->hypercall.args[1] = npages;
10416 vcpu->run->hypercall.args[2] = attrs;
10417 vcpu->run->hypercall.flags = 0;
10418 if (op_64_bit)
10419 vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10420
10421 WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
10422 vcpu->arch.complete_userspace_io = complete_hypercall;
10423 return 0;
10424 }
10425 default:
10426 ret = -KVM_ENOSYS;
10427 break;
10428 }
10429
10430 out:
10431 vcpu->run->hypercall.ret = ret;
10432 return 1;
10433 }
10434 EXPORT_SYMBOL_FOR_KVM_INTERNAL(____kvm_emulate_hypercall);
10435
kvm_emulate_hypercall(struct kvm_vcpu * vcpu)10436 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10437 {
10438 if (kvm_xen_hypercall_enabled(vcpu->kvm))
10439 return kvm_xen_hypercall(vcpu);
10440
10441 if (kvm_hv_hypercall_enabled(vcpu))
10442 return kvm_hv_hypercall(vcpu);
10443
10444 return __kvm_emulate_hypercall(vcpu, kvm_x86_call(get_cpl)(vcpu),
10445 complete_hypercall_exit);
10446 }
10447 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_hypercall);
10448
emulator_fix_hypercall(struct x86_emulate_ctxt * ctxt)10449 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
10450 {
10451 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
10452 char instruction[3];
10453 unsigned long rip = kvm_rip_read(vcpu);
10454
10455 /*
10456 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10457 * the pieces.
10458 */
10459 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10460 ctxt->exception.error_code_valid = false;
10461 ctxt->exception.vector = UD_VECTOR;
10462 ctxt->have_exception = true;
10463 return X86EMUL_PROPAGATE_FAULT;
10464 }
10465
10466 kvm_x86_call(patch_hypercall)(vcpu, instruction);
10467
10468 return emulator_write_emulated(ctxt, rip, instruction, 3,
10469 &ctxt->exception);
10470 }
10471
dm_request_for_irq_injection(struct kvm_vcpu * vcpu)10472 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
10473 {
10474 return vcpu->run->request_interrupt_window &&
10475 likely(!pic_in_kernel(vcpu->kvm));
10476 }
10477
10478 /* Called within kvm->srcu read side. */
post_kvm_run_save(struct kvm_vcpu * vcpu)10479 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
10480 {
10481 struct kvm_run *kvm_run = vcpu->run;
10482
10483 kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
10484 kvm_run->cr8 = kvm_get_cr8(vcpu);
10485 kvm_run->apic_base = vcpu->arch.apic_base;
10486
10487 kvm_run->ready_for_interrupt_injection =
10488 pic_in_kernel(vcpu->kvm) ||
10489 kvm_vcpu_ready_for_interrupt_injection(vcpu);
10490
10491 if (is_smm(vcpu))
10492 kvm_run->flags |= KVM_RUN_X86_SMM;
10493 if (is_guest_mode(vcpu))
10494 kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
10495 }
10496
update_cr8_intercept(struct kvm_vcpu * vcpu)10497 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10498 {
10499 int max_irr, tpr;
10500
10501 if (!kvm_x86_ops.update_cr8_intercept)
10502 return;
10503
10504 if (!lapic_in_kernel(vcpu))
10505 return;
10506
10507 if (vcpu->arch.apic->apicv_active)
10508 return;
10509
10510 if (!vcpu->arch.apic->vapic_addr)
10511 max_irr = kvm_lapic_find_highest_irr(vcpu);
10512 else
10513 max_irr = -1;
10514
10515 if (max_irr != -1)
10516 max_irr >>= 4;
10517
10518 tpr = kvm_lapic_get_cr8(vcpu);
10519
10520 kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
10521 }
10522
10523
kvm_check_nested_events(struct kvm_vcpu * vcpu)10524 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10525 {
10526 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10527 kvm_x86_ops.nested_ops->triple_fault(vcpu);
10528 return 1;
10529 }
10530
10531 return kvm_x86_ops.nested_ops->check_events(vcpu);
10532 }
10533
kvm_inject_exception(struct kvm_vcpu * vcpu)10534 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10535 {
10536 /*
10537 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10538 * exceptions don't report error codes. The presence of an error code
10539 * is carried with the exception and only stripped when the exception
10540 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10541 * report an error code despite the CPU being in Real Mode.
10542 */
10543 vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10544
10545 trace_kvm_inj_exception(vcpu->arch.exception.vector,
10546 vcpu->arch.exception.has_error_code,
10547 vcpu->arch.exception.error_code,
10548 vcpu->arch.exception.injected);
10549
10550 kvm_x86_call(inject_exception)(vcpu);
10551 }
10552
10553 /*
10554 * Check for any event (interrupt or exception) that is ready to be injected,
10555 * and if there is at least one event, inject the event with the highest
10556 * priority. This handles both "pending" events, i.e. events that have never
10557 * been injected into the guest, and "injected" events, i.e. events that were
10558 * injected as part of a previous VM-Enter, but weren't successfully delivered
10559 * and need to be re-injected.
10560 *
10561 * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10562 * i.e. doesn't guarantee that there's an event window in the guest. KVM must
10563 * be able to inject exceptions in the "middle" of an instruction, and so must
10564 * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10565 * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10566 * boundaries is necessary and correct.
10567 *
10568 * For simplicity, KVM uses a single path to inject all events (except events
10569 * that are injected directly from L1 to L2) and doesn't explicitly track
10570 * instruction boundaries for asynchronous events. However, because VM-Exits
10571 * that can occur during instruction execution typically result in KVM skipping
10572 * the instruction or injecting an exception, e.g. instruction and exception
10573 * intercepts, and because pending exceptions have higher priority than pending
10574 * interrupts, KVM still honors instruction boundaries in most scenarios.
10575 *
10576 * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10577 * the instruction or inject an exception, then KVM can incorrecty inject a new
10578 * asynchronous event if the event became pending after the CPU fetched the
10579 * instruction (in the guest). E.g. if a page fault (#PF, #NPF, EPT violation)
10580 * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10581 * injected on the restarted instruction instead of being deferred until the
10582 * instruction completes.
10583 *
10584 * In practice, this virtualization hole is unlikely to be observed by the
10585 * guest, and even less likely to cause functional problems. To detect the
10586 * hole, the guest would have to trigger an event on a side effect of an early
10587 * phase of instruction execution, e.g. on the instruction fetch from memory.
10588 * And for it to be a functional problem, the guest would need to depend on the
10589 * ordering between that side effect, the instruction completing, _and_ the
10590 * delivery of the asynchronous event.
10591 */
kvm_check_and_inject_events(struct kvm_vcpu * vcpu,bool * req_immediate_exit)10592 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10593 bool *req_immediate_exit)
10594 {
10595 bool can_inject;
10596 int r;
10597
10598 /*
10599 * Process nested events first, as nested VM-Exit supersedes event
10600 * re-injection. If there's an event queued for re-injection, it will
10601 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10602 */
10603 if (is_guest_mode(vcpu))
10604 r = kvm_check_nested_events(vcpu);
10605 else
10606 r = 0;
10607
10608 /*
10609 * Re-inject exceptions and events *especially* if immediate entry+exit
10610 * to/from L2 is needed, as any event that has already been injected
10611 * into L2 needs to complete its lifecycle before injecting a new event.
10612 *
10613 * Don't re-inject an NMI or interrupt if there is a pending exception.
10614 * This collision arises if an exception occurred while vectoring the
10615 * injected event, KVM intercepted said exception, and KVM ultimately
10616 * determined the fault belongs to the guest and queues the exception
10617 * for injection back into the guest.
10618 *
10619 * "Injected" interrupts can also collide with pending exceptions if
10620 * userspace ignores the "ready for injection" flag and blindly queues
10621 * an interrupt. In that case, prioritizing the exception is correct,
10622 * as the exception "occurred" before the exit to userspace. Trap-like
10623 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10624 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10625 * priority, they're only generated (pended) during instruction
10626 * execution, and interrupts are recognized at instruction boundaries.
10627 * Thus a pending fault-like exception means the fault occurred on the
10628 * *previous* instruction and must be serviced prior to recognizing any
10629 * new events in order to fully complete the previous instruction.
10630 */
10631 if (vcpu->arch.exception.injected)
10632 kvm_inject_exception(vcpu);
10633 else if (kvm_is_exception_pending(vcpu))
10634 ; /* see above */
10635 else if (vcpu->arch.nmi_injected)
10636 kvm_x86_call(inject_nmi)(vcpu);
10637 else if (vcpu->arch.interrupt.injected)
10638 kvm_x86_call(inject_irq)(vcpu, true);
10639
10640 /*
10641 * Exceptions that morph to VM-Exits are handled above, and pending
10642 * exceptions on top of injected exceptions that do not VM-Exit should
10643 * either morph to #DF or, sadly, override the injected exception.
10644 */
10645 WARN_ON_ONCE(vcpu->arch.exception.injected &&
10646 vcpu->arch.exception.pending);
10647
10648 /*
10649 * Bail if immediate entry+exit to/from the guest is needed to complete
10650 * nested VM-Enter or event re-injection so that a different pending
10651 * event can be serviced (or if KVM needs to exit to userspace).
10652 *
10653 * Otherwise, continue processing events even if VM-Exit occurred. The
10654 * VM-Exit will have cleared exceptions that were meant for L2, but
10655 * there may now be events that can be injected into L1.
10656 */
10657 if (r < 0)
10658 goto out;
10659
10660 /*
10661 * A pending exception VM-Exit should either result in nested VM-Exit
10662 * or force an immediate re-entry and exit to/from L2, and exception
10663 * VM-Exits cannot be injected (flag should _never_ be set).
10664 */
10665 WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10666 vcpu->arch.exception_vmexit.pending);
10667
10668 /*
10669 * New events, other than exceptions, cannot be injected if KVM needs
10670 * to re-inject a previous event. See above comments on re-injecting
10671 * for why pending exceptions get priority.
10672 */
10673 can_inject = !kvm_event_needs_reinjection(vcpu);
10674
10675 if (vcpu->arch.exception.pending) {
10676 /*
10677 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10678 * value pushed on the stack. Trap-like exception and all #DBs
10679 * leave RF as-is (KVM follows Intel's behavior in this regard;
10680 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10681 *
10682 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10683 * describe the behavior of General Detect #DBs, which are
10684 * fault-like. They do _not_ set RF, a la code breakpoints.
10685 */
10686 if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10687 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10688 X86_EFLAGS_RF);
10689
10690 if (vcpu->arch.exception.vector == DB_VECTOR) {
10691 kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
10692 if (vcpu->arch.dr7 & DR7_GD) {
10693 vcpu->arch.dr7 &= ~DR7_GD;
10694 kvm_update_dr7(vcpu);
10695 }
10696 }
10697
10698 kvm_inject_exception(vcpu);
10699
10700 vcpu->arch.exception.pending = false;
10701 vcpu->arch.exception.injected = true;
10702
10703 can_inject = false;
10704 }
10705
10706 /* Don't inject interrupts if the user asked to avoid doing so */
10707 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10708 return 0;
10709
10710 /*
10711 * Finally, inject interrupt events. If an event cannot be injected
10712 * due to architectural conditions (e.g. IF=0) a window-open exit
10713 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
10714 * and can architecturally be injected, but we cannot do it right now:
10715 * an interrupt could have arrived just now and we have to inject it
10716 * as a vmexit, or there could already an event in the queue, which is
10717 * indicated by can_inject. In that case we request an immediate exit
10718 * in order to make progress and get back here for another iteration.
10719 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10720 */
10721 #ifdef CONFIG_KVM_SMM
10722 if (vcpu->arch.smi_pending) {
10723 r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
10724 -EBUSY;
10725 if (r < 0)
10726 goto out;
10727 if (r) {
10728 vcpu->arch.smi_pending = false;
10729 ++vcpu->arch.smi_count;
10730 enter_smm(vcpu);
10731 can_inject = false;
10732 } else
10733 kvm_x86_call(enable_smi_window)(vcpu);
10734 }
10735 #endif
10736
10737 if (vcpu->arch.nmi_pending) {
10738 r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
10739 -EBUSY;
10740 if (r < 0)
10741 goto out;
10742 if (r) {
10743 --vcpu->arch.nmi_pending;
10744 vcpu->arch.nmi_injected = true;
10745 kvm_x86_call(inject_nmi)(vcpu);
10746 can_inject = false;
10747 WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
10748 }
10749 if (vcpu->arch.nmi_pending)
10750 kvm_x86_call(enable_nmi_window)(vcpu);
10751 }
10752
10753 if (kvm_cpu_has_injectable_intr(vcpu)) {
10754 r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
10755 -EBUSY;
10756 if (r < 0)
10757 goto out;
10758 if (r) {
10759 int irq = kvm_cpu_get_interrupt(vcpu);
10760
10761 if (!WARN_ON_ONCE(irq == -1)) {
10762 kvm_queue_interrupt(vcpu, irq, false);
10763 kvm_x86_call(inject_irq)(vcpu, false);
10764 WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
10765 }
10766 }
10767 if (kvm_cpu_has_injectable_intr(vcpu))
10768 kvm_x86_call(enable_irq_window)(vcpu);
10769 }
10770
10771 if (is_guest_mode(vcpu) &&
10772 kvm_x86_ops.nested_ops->has_events &&
10773 kvm_x86_ops.nested_ops->has_events(vcpu, true))
10774 *req_immediate_exit = true;
10775
10776 /*
10777 * KVM must never queue a new exception while injecting an event; KVM
10778 * is done emulating and should only propagate the to-be-injected event
10779 * to the VMCS/VMCB. Queueing a new exception can put the vCPU into an
10780 * infinite loop as KVM will bail from VM-Enter to inject the pending
10781 * exception and start the cycle all over.
10782 *
10783 * Exempt triple faults as they have special handling and won't put the
10784 * vCPU into an infinite loop. Triple fault can be queued when running
10785 * VMX without unrestricted guest, as that requires KVM to emulate Real
10786 * Mode events (see kvm_inject_realmode_interrupt()).
10787 */
10788 WARN_ON_ONCE(vcpu->arch.exception.pending ||
10789 vcpu->arch.exception_vmexit.pending);
10790 return 0;
10791
10792 out:
10793 if (r == -EBUSY) {
10794 *req_immediate_exit = true;
10795 r = 0;
10796 }
10797 return r;
10798 }
10799
process_nmi(struct kvm_vcpu * vcpu)10800 static void process_nmi(struct kvm_vcpu *vcpu)
10801 {
10802 unsigned int limit;
10803
10804 /*
10805 * x86 is limited to one NMI pending, but because KVM can't react to
10806 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10807 * scheduled out, KVM needs to play nice with two queued NMIs showing
10808 * up at the same time. To handle this scenario, allow two NMIs to be
10809 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10810 * waiting for a previous NMI injection to complete (which effectively
10811 * blocks NMIs). KVM will immediately inject one of the two NMIs, and
10812 * will request an NMI window to handle the second NMI.
10813 */
10814 if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10815 limit = 1;
10816 else
10817 limit = 2;
10818
10819 /*
10820 * Adjust the limit to account for pending virtual NMIs, which aren't
10821 * tracked in vcpu->arch.nmi_pending.
10822 */
10823 if (kvm_x86_call(is_vnmi_pending)(vcpu))
10824 limit--;
10825
10826 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10827 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10828
10829 if (vcpu->arch.nmi_pending &&
10830 (kvm_x86_call(set_vnmi_pending)(vcpu)))
10831 vcpu->arch.nmi_pending--;
10832
10833 if (vcpu->arch.nmi_pending)
10834 kvm_make_request(KVM_REQ_EVENT, vcpu);
10835 }
10836
10837 /* Return total number of NMIs pending injection to the VM */
kvm_get_nr_pending_nmis(struct kvm_vcpu * vcpu)10838 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10839 {
10840 return vcpu->arch.nmi_pending +
10841 kvm_x86_call(is_vnmi_pending)(vcpu);
10842 }
10843
kvm_make_scan_ioapic_request_mask(struct kvm * kvm,unsigned long * vcpu_bitmap)10844 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10845 unsigned long *vcpu_bitmap)
10846 {
10847 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10848 }
10849
kvm_make_scan_ioapic_request(struct kvm * kvm)10850 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10851 {
10852 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10853 }
10854
__kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10855 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10856 {
10857 struct kvm_lapic *apic = vcpu->arch.apic;
10858 bool activate;
10859
10860 if (!lapic_in_kernel(vcpu))
10861 return;
10862
10863 down_read(&vcpu->kvm->arch.apicv_update_lock);
10864 preempt_disable();
10865
10866 /* Do not activate APICV when APIC is disabled */
10867 activate = kvm_vcpu_apicv_activated(vcpu) &&
10868 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10869
10870 if (apic->apicv_active == activate)
10871 goto out;
10872
10873 apic->apicv_active = activate;
10874 kvm_apic_update_apicv(vcpu);
10875 kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
10876
10877 /*
10878 * When APICv gets disabled, we may still have injected interrupts
10879 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10880 * still active when the interrupt got accepted. Make sure
10881 * kvm_check_and_inject_events() is called to check for that.
10882 */
10883 if (!apic->apicv_active)
10884 kvm_make_request(KVM_REQ_EVENT, vcpu);
10885
10886 out:
10887 preempt_enable();
10888 up_read(&vcpu->kvm->arch.apicv_update_lock);
10889 }
10890 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_vcpu_update_apicv);
10891
kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10892 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10893 {
10894 if (!lapic_in_kernel(vcpu))
10895 return;
10896
10897 /*
10898 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10899 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10900 * and hardware doesn't support x2APIC virtualization. E.g. some AMD
10901 * CPUs support AVIC but not x2APIC. KVM still allows enabling AVIC in
10902 * this case so that KVM can use the AVIC doorbell to inject interrupts
10903 * to running vCPUs, but KVM must not create SPTEs for the APIC base as
10904 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
10905 * despite being in x2APIC mode. For simplicity, inhibiting the APIC
10906 * access page is sticky.
10907 */
10908 if (apic_x2apic_mode(vcpu->arch.apic) &&
10909 kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
10910 kvm_inhibit_apic_access_page(vcpu);
10911
10912 __kvm_vcpu_update_apicv(vcpu);
10913 }
10914
__kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10915 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10916 enum kvm_apicv_inhibit reason, bool set)
10917 {
10918 unsigned long old, new;
10919
10920 lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10921
10922 if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
10923 return;
10924
10925 old = new = kvm->arch.apicv_inhibit_reasons;
10926
10927 set_or_clear_apicv_inhibit(&new, reason, set);
10928
10929 if (!!old != !!new) {
10930 /*
10931 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10932 * false positives in the sanity check WARN in vcpu_enter_guest().
10933 * This task will wait for all vCPUs to ack the kick IRQ before
10934 * updating apicv_inhibit_reasons, and all other vCPUs will
10935 * block on acquiring apicv_update_lock so that vCPUs can't
10936 * redo vcpu_enter_guest() without seeing the new inhibit state.
10937 *
10938 * Note, holding apicv_update_lock and taking it in the read
10939 * side (handling the request) also prevents other vCPUs from
10940 * servicing the request with a stale apicv_inhibit_reasons.
10941 */
10942 kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10943 kvm->arch.apicv_inhibit_reasons = new;
10944 if (new) {
10945 unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10946 int idx = srcu_read_lock(&kvm->srcu);
10947
10948 kvm_zap_gfn_range(kvm, gfn, gfn+1);
10949 srcu_read_unlock(&kvm->srcu, idx);
10950 }
10951 } else {
10952 kvm->arch.apicv_inhibit_reasons = new;
10953 }
10954 }
10955
kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10956 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10957 enum kvm_apicv_inhibit reason, bool set)
10958 {
10959 if (!enable_apicv)
10960 return;
10961
10962 down_write(&kvm->arch.apicv_update_lock);
10963 __kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10964 up_write(&kvm->arch.apicv_update_lock);
10965 }
10966 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_or_clear_apicv_inhibit);
10967
vcpu_scan_ioapic(struct kvm_vcpu * vcpu)10968 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10969 {
10970 if (!kvm_apic_present(vcpu))
10971 return;
10972
10973 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10974 vcpu->arch.highest_stale_pending_ioapic_eoi = -1;
10975
10976 kvm_x86_call(sync_pir_to_irr)(vcpu);
10977
10978 if (irqchip_split(vcpu->kvm))
10979 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
10980 #ifdef CONFIG_KVM_IOAPIC
10981 else if (ioapic_in_kernel(vcpu->kvm))
10982 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
10983 #endif
10984
10985 if (is_guest_mode(vcpu))
10986 vcpu->arch.load_eoi_exitmap_pending = true;
10987 else
10988 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10989 }
10990
vcpu_load_eoi_exitmap(struct kvm_vcpu * vcpu)10991 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10992 {
10993 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10994 return;
10995
10996 #ifdef CONFIG_KVM_HYPERV
10997 if (to_hv_vcpu(vcpu)) {
10998 u64 eoi_exit_bitmap[4];
10999
11000 bitmap_or((ulong *)eoi_exit_bitmap,
11001 vcpu->arch.ioapic_handled_vectors,
11002 to_hv_synic(vcpu)->vec_bitmap, 256);
11003 kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
11004 return;
11005 }
11006 #endif
11007 kvm_x86_call(load_eoi_exitmap)(
11008 vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
11009 }
11010
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)11011 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
11012 {
11013 kvm_x86_call(guest_memory_reclaimed)(kvm);
11014 }
11015
kvm_vcpu_reload_apic_access_page(struct kvm_vcpu * vcpu)11016 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
11017 {
11018 if (!lapic_in_kernel(vcpu))
11019 return;
11020
11021 kvm_x86_call(set_apic_access_page_addr)(vcpu);
11022 }
11023
11024 /*
11025 * Called within kvm->srcu read side.
11026 * Returns 1 to let vcpu_run() continue the guest execution loop without
11027 * exiting to the userspace. Otherwise, the value will be returned to the
11028 * userspace.
11029 */
vcpu_enter_guest(struct kvm_vcpu * vcpu)11030 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
11031 {
11032 int r;
11033 bool req_int_win =
11034 dm_request_for_irq_injection(vcpu) &&
11035 kvm_cpu_accept_dm_intr(vcpu);
11036 fastpath_t exit_fastpath;
11037 u64 run_flags, debug_ctl;
11038
11039 bool req_immediate_exit = false;
11040
11041 if (kvm_request_pending(vcpu)) {
11042 if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
11043 r = -EIO;
11044 goto out;
11045 }
11046
11047 if (kvm_dirty_ring_check_request(vcpu)) {
11048 r = 0;
11049 goto out;
11050 }
11051
11052 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
11053 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
11054 r = 0;
11055 goto out;
11056 }
11057 }
11058 if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
11059 kvm_mmu_free_obsolete_roots(vcpu);
11060 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
11061 __kvm_migrate_timers(vcpu);
11062 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
11063 kvm_update_masterclock(vcpu->kvm);
11064 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
11065 kvm_gen_kvmclock_update(vcpu);
11066 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
11067 r = kvm_guest_time_update(vcpu);
11068 if (unlikely(r))
11069 goto out;
11070 }
11071 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
11072 kvm_mmu_sync_roots(vcpu);
11073 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
11074 kvm_mmu_load_pgd(vcpu);
11075
11076 /*
11077 * Note, the order matters here, as flushing "all" TLB entries
11078 * also flushes the "current" TLB entries, i.e. servicing the
11079 * flush "all" will clear any request to flush "current".
11080 */
11081 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
11082 kvm_vcpu_flush_tlb_all(vcpu);
11083
11084 kvm_service_local_tlb_flush_requests(vcpu);
11085
11086 /*
11087 * Fall back to a "full" guest flush if Hyper-V's precise
11088 * flushing fails. Note, Hyper-V's flushing is per-vCPU, but
11089 * the flushes are considered "remote" and not "local" because
11090 * the requests can be initiated from other vCPUs.
11091 */
11092 #ifdef CONFIG_KVM_HYPERV
11093 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
11094 kvm_hv_vcpu_flush_tlb(vcpu))
11095 kvm_vcpu_flush_tlb_guest(vcpu);
11096 #endif
11097
11098 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
11099 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
11100 r = 0;
11101 goto out;
11102 }
11103 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
11104 if (is_guest_mode(vcpu))
11105 kvm_x86_ops.nested_ops->triple_fault(vcpu);
11106
11107 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
11108 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
11109 vcpu->mmio_needed = 0;
11110 r = 0;
11111 goto out;
11112 }
11113 }
11114 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
11115 /* Page is swapped out. Do synthetic halt */
11116 vcpu->arch.apf.halted = true;
11117 r = 1;
11118 goto out;
11119 }
11120 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
11121 record_steal_time(vcpu);
11122 if (kvm_check_request(KVM_REQ_PMU, vcpu))
11123 kvm_pmu_handle_event(vcpu);
11124 if (kvm_check_request(KVM_REQ_PMI, vcpu))
11125 kvm_pmu_deliver_pmi(vcpu);
11126 #ifdef CONFIG_KVM_SMM
11127 if (kvm_check_request(KVM_REQ_SMI, vcpu))
11128 process_smi(vcpu);
11129 #endif
11130 if (kvm_check_request(KVM_REQ_NMI, vcpu))
11131 process_nmi(vcpu);
11132 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
11133 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
11134 if (test_bit(vcpu->arch.pending_ioapic_eoi,
11135 vcpu->arch.ioapic_handled_vectors)) {
11136 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
11137 vcpu->run->eoi.vector =
11138 vcpu->arch.pending_ioapic_eoi;
11139 r = 0;
11140 goto out;
11141 }
11142 }
11143 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
11144 vcpu_scan_ioapic(vcpu);
11145 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
11146 vcpu_load_eoi_exitmap(vcpu);
11147 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
11148 kvm_vcpu_reload_apic_access_page(vcpu);
11149 #ifdef CONFIG_KVM_HYPERV
11150 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
11151 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
11152 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
11153 vcpu->run->system_event.ndata = 0;
11154 r = 0;
11155 goto out;
11156 }
11157 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
11158 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
11159 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
11160 vcpu->run->system_event.ndata = 0;
11161 r = 0;
11162 goto out;
11163 }
11164 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
11165 struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
11166
11167 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
11168 vcpu->run->hyperv = hv_vcpu->exit;
11169 r = 0;
11170 goto out;
11171 }
11172
11173 /*
11174 * KVM_REQ_HV_STIMER has to be processed after
11175 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
11176 * depend on the guest clock being up-to-date
11177 */
11178 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
11179 kvm_hv_process_stimers(vcpu);
11180 #endif
11181 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
11182 kvm_vcpu_update_apicv(vcpu);
11183 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
11184 kvm_check_async_pf_completion(vcpu);
11185
11186 if (kvm_check_request(KVM_REQ_RECALC_INTERCEPTS, vcpu))
11187 kvm_x86_call(recalc_intercepts)(vcpu);
11188
11189 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
11190 kvm_x86_call(update_cpu_dirty_logging)(vcpu);
11191
11192 if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
11193 kvm_vcpu_reset(vcpu, true);
11194 if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
11195 r = 1;
11196 goto out;
11197 }
11198 }
11199 }
11200
11201 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
11202 kvm_xen_has_interrupt(vcpu)) {
11203 ++vcpu->stat.req_event;
11204 r = kvm_apic_accept_events(vcpu);
11205 if (r < 0) {
11206 r = 0;
11207 goto out;
11208 }
11209 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
11210 r = 1;
11211 goto out;
11212 }
11213
11214 r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
11215 if (r < 0) {
11216 r = 0;
11217 goto out;
11218 }
11219 if (req_int_win)
11220 kvm_x86_call(enable_irq_window)(vcpu);
11221
11222 if (kvm_lapic_enabled(vcpu)) {
11223 update_cr8_intercept(vcpu);
11224 kvm_lapic_sync_to_vapic(vcpu);
11225 }
11226 }
11227
11228 r = kvm_mmu_reload(vcpu);
11229 if (unlikely(r)) {
11230 goto cancel_injection;
11231 }
11232
11233 preempt_disable();
11234
11235 kvm_x86_call(prepare_switch_to_guest)(vcpu);
11236
11237 /*
11238 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
11239 * IPI are then delayed after guest entry, which ensures that they
11240 * result in virtual interrupt delivery.
11241 */
11242 local_irq_disable();
11243
11244 /* Store vcpu->apicv_active before vcpu->mode. */
11245 smp_store_release(&vcpu->mode, IN_GUEST_MODE);
11246
11247 kvm_vcpu_srcu_read_unlock(vcpu);
11248
11249 /*
11250 * 1) We should set ->mode before checking ->requests. Please see
11251 * the comment in kvm_vcpu_exiting_guest_mode().
11252 *
11253 * 2) For APICv, we should set ->mode before checking PID.ON. This
11254 * pairs with the memory barrier implicit in pi_test_and_set_on
11255 * (see vmx_deliver_posted_interrupt).
11256 *
11257 * 3) This also orders the write to mode from any reads to the page
11258 * tables done while the VCPU is running. Please see the comment
11259 * in kvm_flush_remote_tlbs.
11260 */
11261 smp_mb__after_srcu_read_unlock();
11262
11263 /*
11264 * Process pending posted interrupts to handle the case where the
11265 * notification IRQ arrived in the host, or was never sent (because the
11266 * target vCPU wasn't running). Do this regardless of the vCPU's APICv
11267 * status, KVM doesn't update assigned devices when APICv is inhibited,
11268 * i.e. they can post interrupts even if APICv is temporarily disabled.
11269 */
11270 if (kvm_lapic_enabled(vcpu))
11271 kvm_x86_call(sync_pir_to_irr)(vcpu);
11272
11273 if (kvm_vcpu_exit_request(vcpu)) {
11274 vcpu->mode = OUTSIDE_GUEST_MODE;
11275 smp_wmb();
11276 local_irq_enable();
11277 preempt_enable();
11278 kvm_vcpu_srcu_read_lock(vcpu);
11279 r = 1;
11280 goto cancel_injection;
11281 }
11282
11283 run_flags = 0;
11284 if (req_immediate_exit) {
11285 run_flags |= KVM_RUN_FORCE_IMMEDIATE_EXIT;
11286 kvm_make_request(KVM_REQ_EVENT, vcpu);
11287 }
11288
11289 fpregs_assert_state_consistent();
11290 if (test_thread_flag(TIF_NEED_FPU_LOAD))
11291 switch_fpu_return();
11292
11293 if (vcpu->arch.guest_fpu.xfd_err)
11294 wrmsrq(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
11295
11296 if (unlikely(vcpu->arch.switch_db_regs &&
11297 !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
11298 set_debugreg(DR7_FIXED_1, 7);
11299 set_debugreg(vcpu->arch.eff_db[0], 0);
11300 set_debugreg(vcpu->arch.eff_db[1], 1);
11301 set_debugreg(vcpu->arch.eff_db[2], 2);
11302 set_debugreg(vcpu->arch.eff_db[3], 3);
11303 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
11304 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
11305 run_flags |= KVM_RUN_LOAD_GUEST_DR6;
11306 } else if (unlikely(hw_breakpoint_active())) {
11307 set_debugreg(DR7_FIXED_1, 7);
11308 }
11309
11310 /*
11311 * Refresh the host DEBUGCTL snapshot after disabling IRQs, as DEBUGCTL
11312 * can be modified in IRQ context, e.g. via SMP function calls. Inform
11313 * vendor code if any host-owned bits were changed, e.g. so that the
11314 * value loaded into hardware while running the guest can be updated.
11315 */
11316 debug_ctl = get_debugctlmsr();
11317 if ((debug_ctl ^ vcpu->arch.host_debugctl) & kvm_x86_ops.HOST_OWNED_DEBUGCTL &&
11318 !vcpu->arch.guest_state_protected)
11319 run_flags |= KVM_RUN_LOAD_DEBUGCTL;
11320 vcpu->arch.host_debugctl = debug_ctl;
11321
11322 guest_timing_enter_irqoff();
11323
11324 for (;;) {
11325 /*
11326 * Assert that vCPU vs. VM APICv state is consistent. An APICv
11327 * update must kick and wait for all vCPUs before toggling the
11328 * per-VM state, and responding vCPUs must wait for the update
11329 * to complete before servicing KVM_REQ_APICV_UPDATE.
11330 */
11331 WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11332 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
11333
11334 exit_fastpath = kvm_x86_call(vcpu_run)(vcpu, run_flags);
11335 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11336 break;
11337
11338 if (kvm_lapic_enabled(vcpu))
11339 kvm_x86_call(sync_pir_to_irr)(vcpu);
11340
11341 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
11342 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11343 break;
11344 }
11345
11346 run_flags = 0;
11347
11348 /* Note, VM-Exits that go down the "slow" path are accounted below. */
11349 ++vcpu->stat.exits;
11350 }
11351
11352 /*
11353 * Do this here before restoring debug registers on the host. And
11354 * since we do this before handling the vmexit, a DR access vmexit
11355 * can (a) read the correct value of the debug registers, (b) set
11356 * KVM_DEBUGREG_WONT_EXIT again.
11357 */
11358 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
11359 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
11360 WARN_ON(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH);
11361 kvm_x86_call(sync_dirty_debug_regs)(vcpu);
11362 kvm_update_dr0123(vcpu);
11363 kvm_update_dr7(vcpu);
11364 }
11365
11366 /*
11367 * If the guest has used debug registers, at least dr7
11368 * will be disabled while returning to the host.
11369 * If we don't have active breakpoints in the host, we don't
11370 * care about the messed up debug address registers. But if
11371 * we have some of them active, restore the old state.
11372 */
11373 if (hw_breakpoint_active())
11374 hw_breakpoint_restore();
11375
11376 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
11377 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
11378
11379 vcpu->mode = OUTSIDE_GUEST_MODE;
11380 smp_wmb();
11381
11382 /*
11383 * Sync xfd before calling handle_exit_irqoff() which may
11384 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11385 * in #NM irqoff handler).
11386 */
11387 if (vcpu->arch.xfd_no_write_intercept)
11388 fpu_sync_guest_vmexit_xfd_state();
11389
11390 kvm_x86_call(handle_exit_irqoff)(vcpu);
11391
11392 if (vcpu->arch.guest_fpu.xfd_err)
11393 wrmsrq(MSR_IA32_XFD_ERR, 0);
11394
11395 /*
11396 * Mark this CPU as needing a branch predictor flush before running
11397 * userspace. Must be done before enabling preemption to ensure it gets
11398 * set for the CPU that actually ran the guest, and not the CPU that it
11399 * may migrate to.
11400 */
11401 if (cpu_feature_enabled(X86_FEATURE_IBPB_EXIT_TO_USER))
11402 this_cpu_write(x86_ibpb_exit_to_user, true);
11403
11404 /*
11405 * Consume any pending interrupts, including the possible source of
11406 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11407 * An instruction is required after local_irq_enable() to fully unblock
11408 * interrupts on processors that implement an interrupt shadow, the
11409 * stat.exits increment will do nicely.
11410 */
11411 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
11412 local_irq_enable();
11413 ++vcpu->stat.exits;
11414 local_irq_disable();
11415 kvm_after_interrupt(vcpu);
11416
11417 /*
11418 * Wait until after servicing IRQs to account guest time so that any
11419 * ticks that occurred while running the guest are properly accounted
11420 * to the guest. Waiting until IRQs are enabled degrades the accuracy
11421 * of accounting via context tracking, but the loss of accuracy is
11422 * acceptable for all known use cases.
11423 */
11424 guest_timing_exit_irqoff();
11425
11426 local_irq_enable();
11427 preempt_enable();
11428
11429 kvm_vcpu_srcu_read_lock(vcpu);
11430
11431 /*
11432 * Call this to ensure WC buffers in guest are evicted after each VM
11433 * Exit, so that the evicted WC writes can be snooped across all cpus
11434 */
11435 smp_mb__after_srcu_read_lock();
11436
11437 /*
11438 * Profile KVM exit RIPs:
11439 */
11440 if (unlikely(prof_on == KVM_PROFILING &&
11441 !vcpu->arch.guest_state_protected)) {
11442 unsigned long rip = kvm_rip_read(vcpu);
11443 profile_hit(KVM_PROFILING, (void *)rip);
11444 }
11445
11446 if (unlikely(vcpu->arch.tsc_always_catchup))
11447 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11448
11449 if (vcpu->arch.apic_attention)
11450 kvm_lapic_sync_from_vapic(vcpu);
11451
11452 if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
11453 return 0;
11454
11455 r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
11456 return r;
11457
11458 cancel_injection:
11459 if (req_immediate_exit)
11460 kvm_make_request(KVM_REQ_EVENT, vcpu);
11461 kvm_x86_call(cancel_injection)(vcpu);
11462 if (unlikely(vcpu->arch.apic_attention))
11463 kvm_lapic_sync_from_vapic(vcpu);
11464 out:
11465 return r;
11466 }
11467
kvm_vcpu_running(struct kvm_vcpu * vcpu)11468 static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11469 {
11470 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11471 !vcpu->arch.apf.halted);
11472 }
11473
kvm_vcpu_has_events(struct kvm_vcpu * vcpu)11474 bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
11475 {
11476 if (!list_empty_careful(&vcpu->async_pf.done))
11477 return true;
11478
11479 if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
11480 kvm_apic_init_sipi_allowed(vcpu))
11481 return true;
11482
11483 if (kvm_is_exception_pending(vcpu))
11484 return true;
11485
11486 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11487 (vcpu->arch.nmi_pending &&
11488 kvm_x86_call(nmi_allowed)(vcpu, false)))
11489 return true;
11490
11491 #ifdef CONFIG_KVM_SMM
11492 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11493 (vcpu->arch.smi_pending &&
11494 kvm_x86_call(smi_allowed)(vcpu, false)))
11495 return true;
11496 #endif
11497
11498 if (kvm_test_request(KVM_REQ_PMI, vcpu))
11499 return true;
11500
11501 if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
11502 return true;
11503
11504 if (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
11505 return true;
11506
11507 if (kvm_hv_has_stimer_pending(vcpu))
11508 return true;
11509
11510 if (is_guest_mode(vcpu) &&
11511 kvm_x86_ops.nested_ops->has_events &&
11512 kvm_x86_ops.nested_ops->has_events(vcpu, false))
11513 return true;
11514
11515 if (kvm_xen_has_pending_events(vcpu))
11516 return true;
11517
11518 return false;
11519 }
11520 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_has_events);
11521
kvm_arch_vcpu_runnable(struct kvm_vcpu * vcpu)11522 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11523 {
11524 return kvm_vcpu_running(vcpu) || vcpu->arch.pv.pv_unhalted ||
11525 kvm_vcpu_has_events(vcpu);
11526 }
11527
11528 /* Called within kvm->srcu read side. */
vcpu_block(struct kvm_vcpu * vcpu)11529 static inline int vcpu_block(struct kvm_vcpu *vcpu)
11530 {
11531 bool hv_timer;
11532
11533 if (!kvm_arch_vcpu_runnable(vcpu)) {
11534 /*
11535 * Switch to the software timer before halt-polling/blocking as
11536 * the guest's timer may be a break event for the vCPU, and the
11537 * hypervisor timer runs only when the CPU is in guest mode.
11538 * Switch before halt-polling so that KVM recognizes an expired
11539 * timer before blocking.
11540 */
11541 hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11542 if (hv_timer)
11543 kvm_lapic_switch_to_sw_timer(vcpu);
11544
11545 kvm_vcpu_srcu_read_unlock(vcpu);
11546 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11547 kvm_vcpu_halt(vcpu);
11548 else
11549 kvm_vcpu_block(vcpu);
11550 kvm_vcpu_srcu_read_lock(vcpu);
11551
11552 if (hv_timer)
11553 kvm_lapic_switch_to_hv_timer(vcpu);
11554
11555 /*
11556 * If the vCPU is not runnable, a signal or another host event
11557 * of some kind is pending; service it without changing the
11558 * vCPU's activity state.
11559 */
11560 if (!kvm_arch_vcpu_runnable(vcpu))
11561 return 1;
11562 }
11563
11564 /*
11565 * Evaluate nested events before exiting the halted state. This allows
11566 * the halt state to be recorded properly in the VMCS12's activity
11567 * state field (AMD does not have a similar field and a VM-Exit always
11568 * causes a spurious wakeup from HLT).
11569 */
11570 if (is_guest_mode(vcpu)) {
11571 int r = kvm_check_nested_events(vcpu);
11572
11573 WARN_ON_ONCE(r == -EBUSY);
11574 if (r < 0)
11575 return 0;
11576 }
11577
11578 if (kvm_apic_accept_events(vcpu) < 0)
11579 return 0;
11580 switch(vcpu->arch.mp_state) {
11581 case KVM_MP_STATE_HALTED:
11582 case KVM_MP_STATE_AP_RESET_HOLD:
11583 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
11584 fallthrough;
11585 case KVM_MP_STATE_RUNNABLE:
11586 vcpu->arch.apf.halted = false;
11587 break;
11588 case KVM_MP_STATE_INIT_RECEIVED:
11589 break;
11590 default:
11591 WARN_ON_ONCE(1);
11592 break;
11593 }
11594 return 1;
11595 }
11596
11597 /* Called within kvm->srcu read side. */
vcpu_run(struct kvm_vcpu * vcpu)11598 static int vcpu_run(struct kvm_vcpu *vcpu)
11599 {
11600 int r;
11601
11602 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
11603
11604 for (;;) {
11605 /*
11606 * If another guest vCPU requests a PV TLB flush in the middle
11607 * of instruction emulation, the rest of the emulation could
11608 * use a stale page translation. Assume that any code after
11609 * this point can start executing an instruction.
11610 */
11611 vcpu->arch.at_instruction_boundary = false;
11612 if (kvm_vcpu_running(vcpu)) {
11613 r = vcpu_enter_guest(vcpu);
11614 } else {
11615 r = vcpu_block(vcpu);
11616 }
11617
11618 if (r <= 0)
11619 break;
11620
11621 kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11622 if (kvm_xen_has_pending_events(vcpu))
11623 kvm_xen_inject_pending_events(vcpu);
11624
11625 if (kvm_cpu_has_pending_timer(vcpu))
11626 kvm_inject_pending_timer_irqs(vcpu);
11627
11628 if (dm_request_for_irq_injection(vcpu) &&
11629 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11630 r = 0;
11631 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11632 ++vcpu->stat.request_irq_exits;
11633 break;
11634 }
11635
11636 if (__xfer_to_guest_mode_work_pending()) {
11637 kvm_vcpu_srcu_read_unlock(vcpu);
11638 r = xfer_to_guest_mode_handle_work(vcpu);
11639 kvm_vcpu_srcu_read_lock(vcpu);
11640 if (r)
11641 return r;
11642 }
11643 }
11644
11645 return r;
11646 }
11647
__kvm_emulate_halt(struct kvm_vcpu * vcpu,int state,int reason)11648 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
11649 {
11650 /*
11651 * The vCPU has halted, e.g. executed HLT. Update the run state if the
11652 * local APIC is in-kernel, the run loop will detect the non-runnable
11653 * state and halt the vCPU. Exit to userspace if the local APIC is
11654 * managed by userspace, in which case userspace is responsible for
11655 * handling wake events.
11656 */
11657 ++vcpu->stat.halt_exits;
11658 if (lapic_in_kernel(vcpu)) {
11659 if (kvm_vcpu_has_events(vcpu) || vcpu->arch.pv.pv_unhalted)
11660 state = KVM_MP_STATE_RUNNABLE;
11661 kvm_set_mp_state(vcpu, state);
11662 return 1;
11663 } else {
11664 vcpu->run->exit_reason = reason;
11665 return 0;
11666 }
11667 }
11668
kvm_emulate_halt_noskip(struct kvm_vcpu * vcpu)11669 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
11670 {
11671 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
11672 }
11673 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt_noskip);
11674
kvm_emulate_halt(struct kvm_vcpu * vcpu)11675 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
11676 {
11677 int ret = kvm_skip_emulated_instruction(vcpu);
11678 /*
11679 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
11680 * KVM_EXIT_DEBUG here.
11681 */
11682 return kvm_emulate_halt_noskip(vcpu) && ret;
11683 }
11684 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt);
11685
handle_fastpath_hlt(struct kvm_vcpu * vcpu)11686 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
11687 {
11688 if (!kvm_emulate_halt(vcpu))
11689 return EXIT_FASTPATH_EXIT_USERSPACE;
11690
11691 if (kvm_vcpu_running(vcpu))
11692 return EXIT_FASTPATH_REENTER_GUEST;
11693
11694 return EXIT_FASTPATH_EXIT_HANDLED;
11695 }
11696 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_hlt);
11697
kvm_emulate_ap_reset_hold(struct kvm_vcpu * vcpu)11698 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
11699 {
11700 int ret = kvm_skip_emulated_instruction(vcpu);
11701
11702 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
11703 KVM_EXIT_AP_RESET_HOLD) && ret;
11704 }
11705 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_ap_reset_hold);
11706
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)11707 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
11708 {
11709 return kvm_vcpu_apicv_active(vcpu) &&
11710 kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
11711 }
11712
kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu * vcpu)11713 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
11714 {
11715 return vcpu->arch.preempted_in_kernel;
11716 }
11717
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)11718 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11719 {
11720 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11721 return true;
11722
11723 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11724 #ifdef CONFIG_KVM_SMM
11725 kvm_test_request(KVM_REQ_SMI, vcpu) ||
11726 #endif
11727 kvm_test_request(KVM_REQ_EVENT, vcpu))
11728 return true;
11729
11730 return kvm_arch_dy_has_pending_interrupt(vcpu);
11731 }
11732
complete_emulated_io(struct kvm_vcpu * vcpu)11733 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11734 {
11735 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11736 }
11737
complete_emulated_pio(struct kvm_vcpu * vcpu)11738 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11739 {
11740 BUG_ON(!vcpu->arch.pio.count);
11741
11742 return complete_emulated_io(vcpu);
11743 }
11744
11745 /*
11746 * Implements the following, as a state machine:
11747 *
11748 * read:
11749 * for each fragment
11750 * for each mmio piece in the fragment
11751 * write gpa, len
11752 * exit
11753 * copy data
11754 * execute insn
11755 *
11756 * write:
11757 * for each fragment
11758 * for each mmio piece in the fragment
11759 * write gpa, len
11760 * copy data
11761 * exit
11762 */
complete_emulated_mmio(struct kvm_vcpu * vcpu)11763 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11764 {
11765 struct kvm_run *run = vcpu->run;
11766 struct kvm_mmio_fragment *frag;
11767 unsigned len;
11768
11769 BUG_ON(!vcpu->mmio_needed);
11770
11771 /* Complete previous fragment */
11772 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11773 len = min(8u, frag->len);
11774 if (!vcpu->mmio_is_write)
11775 memcpy(frag->data, run->mmio.data, len);
11776
11777 if (frag->len <= 8) {
11778 /* Switch to the next fragment. */
11779 frag++;
11780 vcpu->mmio_cur_fragment++;
11781 } else {
11782 /* Go forward to the next mmio piece. */
11783 frag->data += len;
11784 frag->gpa += len;
11785 frag->len -= len;
11786 }
11787
11788 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11789 vcpu->mmio_needed = 0;
11790
11791 /* FIXME: return into emulator if single-stepping. */
11792 if (vcpu->mmio_is_write)
11793 return 1;
11794 vcpu->mmio_read_completed = 1;
11795 return complete_emulated_io(vcpu);
11796 }
11797
11798 run->exit_reason = KVM_EXIT_MMIO;
11799 run->mmio.phys_addr = frag->gpa;
11800 if (vcpu->mmio_is_write)
11801 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11802 run->mmio.len = min(8u, frag->len);
11803 run->mmio.is_write = vcpu->mmio_is_write;
11804 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11805 return 0;
11806 }
11807
11808 /* Swap (qemu) user FPU context for the guest FPU context. */
kvm_load_guest_fpu(struct kvm_vcpu * vcpu)11809 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11810 {
11811 /* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11812 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11813 trace_kvm_fpu(1);
11814 }
11815
11816 /* When vcpu_run ends, restore user space FPU context. */
kvm_put_guest_fpu(struct kvm_vcpu * vcpu)11817 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11818 {
11819 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11820 ++vcpu->stat.fpu_reload;
11821 trace_kvm_fpu(0);
11822 }
11823
kvm_x86_vcpu_pre_run(struct kvm_vcpu * vcpu)11824 static int kvm_x86_vcpu_pre_run(struct kvm_vcpu *vcpu)
11825 {
11826 /*
11827 * SIPI_RECEIVED is obsolete; KVM leaves the vCPU in Wait-For-SIPI and
11828 * tracks the pending SIPI separately. SIPI_RECEIVED is still accepted
11829 * by KVM_SET_VCPU_EVENTS for backwards compatibility, but should be
11830 * converted to INIT_RECEIVED.
11831 */
11832 if (WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED))
11833 return -EINVAL;
11834
11835 /*
11836 * Disallow running the vCPU if userspace forced it into an impossible
11837 * MP_STATE, e.g. if the vCPU is in WFS but SIPI is blocked.
11838 */
11839 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED &&
11840 !kvm_apic_init_sipi_allowed(vcpu))
11841 return -EINVAL;
11842
11843 return kvm_x86_call(vcpu_pre_run)(vcpu);
11844 }
11845
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)11846 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
11847 {
11848 struct kvm_queued_exception *ex = &vcpu->arch.exception;
11849 struct kvm_run *kvm_run = vcpu->run;
11850 u64 sync_valid_fields;
11851 int r;
11852
11853 r = kvm_mmu_post_init_vm(vcpu->kvm);
11854 if (r)
11855 return r;
11856
11857 vcpu_load(vcpu);
11858 kvm_sigset_activate(vcpu);
11859 kvm_run->flags = 0;
11860 kvm_load_guest_fpu(vcpu);
11861
11862 kvm_vcpu_srcu_read_lock(vcpu);
11863 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
11864 if (!vcpu->wants_to_run) {
11865 r = -EINTR;
11866 goto out;
11867 }
11868
11869 /*
11870 * Don't bother switching APIC timer emulation from the
11871 * hypervisor timer to the software timer, the only way for the
11872 * APIC timer to be active is if userspace stuffed vCPU state,
11873 * i.e. put the vCPU into a nonsensical state. Only an INIT
11874 * will transition the vCPU out of UNINITIALIZED (without more
11875 * state stuffing from userspace), which will reset the local
11876 * APIC and thus cancel the timer or drop the IRQ (if the timer
11877 * already expired).
11878 */
11879 kvm_vcpu_srcu_read_unlock(vcpu);
11880 kvm_vcpu_block(vcpu);
11881 kvm_vcpu_srcu_read_lock(vcpu);
11882
11883 if (kvm_apic_accept_events(vcpu) < 0) {
11884 r = 0;
11885 goto out;
11886 }
11887 r = -EAGAIN;
11888 if (signal_pending(current)) {
11889 r = -EINTR;
11890 kvm_run->exit_reason = KVM_EXIT_INTR;
11891 ++vcpu->stat.signal_exits;
11892 }
11893 goto out;
11894 }
11895
11896 sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
11897 if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
11898 (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
11899 r = -EINVAL;
11900 goto out;
11901 }
11902
11903 if (kvm_run->kvm_dirty_regs) {
11904 r = sync_regs(vcpu);
11905 if (r != 0)
11906 goto out;
11907 }
11908
11909 /* re-sync apic's tpr */
11910 if (!lapic_in_kernel(vcpu)) {
11911 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11912 r = -EINVAL;
11913 goto out;
11914 }
11915 }
11916
11917 /*
11918 * If userspace set a pending exception and L2 is active, convert it to
11919 * a pending VM-Exit if L1 wants to intercept the exception.
11920 */
11921 if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11922 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11923 ex->error_code)) {
11924 kvm_queue_exception_vmexit(vcpu, ex->vector,
11925 ex->has_error_code, ex->error_code,
11926 ex->has_payload, ex->payload);
11927 ex->injected = false;
11928 ex->pending = false;
11929 }
11930 vcpu->arch.exception_from_userspace = false;
11931
11932 if (unlikely(vcpu->arch.complete_userspace_io)) {
11933 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11934 vcpu->arch.complete_userspace_io = NULL;
11935 r = cui(vcpu);
11936 if (r <= 0)
11937 goto out;
11938 } else {
11939 WARN_ON_ONCE(vcpu->arch.pio.count);
11940 WARN_ON_ONCE(vcpu->mmio_needed);
11941 }
11942
11943 if (!vcpu->wants_to_run) {
11944 r = -EINTR;
11945 goto out;
11946 }
11947
11948 r = kvm_x86_vcpu_pre_run(vcpu);
11949 if (r <= 0)
11950 goto out;
11951
11952 r = vcpu_run(vcpu);
11953
11954 out:
11955 kvm_put_guest_fpu(vcpu);
11956 if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
11957 store_regs(vcpu);
11958 post_kvm_run_save(vcpu);
11959 kvm_vcpu_srcu_read_unlock(vcpu);
11960
11961 kvm_sigset_deactivate(vcpu);
11962 vcpu_put(vcpu);
11963 return r;
11964 }
11965
__get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11966 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11967 {
11968 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
11969 /*
11970 * We are here if userspace calls get_regs() in the middle of
11971 * instruction emulation. Registers state needs to be copied
11972 * back from emulation context to vcpu. Userspace shouldn't do
11973 * that usually, but some bad designed PV devices (vmware
11974 * backdoor interface) need this to work
11975 */
11976 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
11977 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11978 }
11979 regs->rax = kvm_rax_read(vcpu);
11980 regs->rbx = kvm_rbx_read(vcpu);
11981 regs->rcx = kvm_rcx_read(vcpu);
11982 regs->rdx = kvm_rdx_read(vcpu);
11983 regs->rsi = kvm_rsi_read(vcpu);
11984 regs->rdi = kvm_rdi_read(vcpu);
11985 regs->rsp = kvm_rsp_read(vcpu);
11986 regs->rbp = kvm_rbp_read(vcpu);
11987 #ifdef CONFIG_X86_64
11988 regs->r8 = kvm_r8_read(vcpu);
11989 regs->r9 = kvm_r9_read(vcpu);
11990 regs->r10 = kvm_r10_read(vcpu);
11991 regs->r11 = kvm_r11_read(vcpu);
11992 regs->r12 = kvm_r12_read(vcpu);
11993 regs->r13 = kvm_r13_read(vcpu);
11994 regs->r14 = kvm_r14_read(vcpu);
11995 regs->r15 = kvm_r15_read(vcpu);
11996 #endif
11997
11998 regs->rip = kvm_rip_read(vcpu);
11999 regs->rflags = kvm_get_rflags(vcpu);
12000 }
12001
kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12002 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12003 {
12004 if (vcpu->kvm->arch.has_protected_state &&
12005 vcpu->arch.guest_state_protected)
12006 return -EINVAL;
12007
12008 vcpu_load(vcpu);
12009 __get_regs(vcpu, regs);
12010 vcpu_put(vcpu);
12011 return 0;
12012 }
12013
__set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12014 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12015 {
12016 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
12017 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
12018
12019 kvm_rax_write(vcpu, regs->rax);
12020 kvm_rbx_write(vcpu, regs->rbx);
12021 kvm_rcx_write(vcpu, regs->rcx);
12022 kvm_rdx_write(vcpu, regs->rdx);
12023 kvm_rsi_write(vcpu, regs->rsi);
12024 kvm_rdi_write(vcpu, regs->rdi);
12025 kvm_rsp_write(vcpu, regs->rsp);
12026 kvm_rbp_write(vcpu, regs->rbp);
12027 #ifdef CONFIG_X86_64
12028 kvm_r8_write(vcpu, regs->r8);
12029 kvm_r9_write(vcpu, regs->r9);
12030 kvm_r10_write(vcpu, regs->r10);
12031 kvm_r11_write(vcpu, regs->r11);
12032 kvm_r12_write(vcpu, regs->r12);
12033 kvm_r13_write(vcpu, regs->r13);
12034 kvm_r14_write(vcpu, regs->r14);
12035 kvm_r15_write(vcpu, regs->r15);
12036 #endif
12037
12038 kvm_rip_write(vcpu, regs->rip);
12039 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
12040
12041 vcpu->arch.exception.pending = false;
12042 vcpu->arch.exception_vmexit.pending = false;
12043
12044 kvm_make_request(KVM_REQ_EVENT, vcpu);
12045 }
12046
kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12047 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12048 {
12049 if (vcpu->kvm->arch.has_protected_state &&
12050 vcpu->arch.guest_state_protected)
12051 return -EINVAL;
12052
12053 vcpu_load(vcpu);
12054 __set_regs(vcpu, regs);
12055 vcpu_put(vcpu);
12056 return 0;
12057 }
12058
__get_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12059 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12060 {
12061 struct desc_ptr dt;
12062
12063 if (vcpu->arch.guest_state_protected)
12064 goto skip_protected_regs;
12065
12066 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12067 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12068 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12069 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12070 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12071 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12072
12073 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12074 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12075
12076 kvm_x86_call(get_idt)(vcpu, &dt);
12077 sregs->idt.limit = dt.size;
12078 sregs->idt.base = dt.address;
12079 kvm_x86_call(get_gdt)(vcpu, &dt);
12080 sregs->gdt.limit = dt.size;
12081 sregs->gdt.base = dt.address;
12082
12083 sregs->cr2 = vcpu->arch.cr2;
12084 sregs->cr3 = kvm_read_cr3(vcpu);
12085
12086 skip_protected_regs:
12087 sregs->cr0 = kvm_read_cr0(vcpu);
12088 sregs->cr4 = kvm_read_cr4(vcpu);
12089 sregs->cr8 = kvm_get_cr8(vcpu);
12090 sregs->efer = vcpu->arch.efer;
12091 sregs->apic_base = vcpu->arch.apic_base;
12092 }
12093
__get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12094 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12095 {
12096 __get_sregs_common(vcpu, sregs);
12097
12098 if (vcpu->arch.guest_state_protected)
12099 return;
12100
12101 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
12102 set_bit(vcpu->arch.interrupt.nr,
12103 (unsigned long *)sregs->interrupt_bitmap);
12104 }
12105
__get_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12106 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12107 {
12108 int i;
12109
12110 __get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
12111
12112 if (vcpu->arch.guest_state_protected)
12113 return;
12114
12115 if (is_pae_paging(vcpu)) {
12116 for (i = 0 ; i < 4 ; i++)
12117 sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
12118 sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
12119 }
12120 }
12121
kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12122 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
12123 struct kvm_sregs *sregs)
12124 {
12125 if (vcpu->kvm->arch.has_protected_state &&
12126 vcpu->arch.guest_state_protected)
12127 return -EINVAL;
12128
12129 vcpu_load(vcpu);
12130 __get_sregs(vcpu, sregs);
12131 vcpu_put(vcpu);
12132 return 0;
12133 }
12134
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)12135 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
12136 struct kvm_mp_state *mp_state)
12137 {
12138 int r;
12139
12140 vcpu_load(vcpu);
12141 if (kvm_mpx_supported())
12142 kvm_load_guest_fpu(vcpu);
12143
12144 kvm_vcpu_srcu_read_lock(vcpu);
12145
12146 r = kvm_apic_accept_events(vcpu);
12147 if (r < 0)
12148 goto out;
12149 r = 0;
12150
12151 if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
12152 vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
12153 vcpu->arch.pv.pv_unhalted)
12154 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
12155 else
12156 mp_state->mp_state = vcpu->arch.mp_state;
12157
12158 out:
12159 kvm_vcpu_srcu_read_unlock(vcpu);
12160
12161 if (kvm_mpx_supported())
12162 kvm_put_guest_fpu(vcpu);
12163 vcpu_put(vcpu);
12164 return r;
12165 }
12166
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)12167 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
12168 struct kvm_mp_state *mp_state)
12169 {
12170 int ret = -EINVAL;
12171
12172 vcpu_load(vcpu);
12173
12174 switch (mp_state->mp_state) {
12175 case KVM_MP_STATE_UNINITIALIZED:
12176 case KVM_MP_STATE_HALTED:
12177 case KVM_MP_STATE_AP_RESET_HOLD:
12178 case KVM_MP_STATE_INIT_RECEIVED:
12179 case KVM_MP_STATE_SIPI_RECEIVED:
12180 if (!lapic_in_kernel(vcpu))
12181 goto out;
12182 break;
12183
12184 case KVM_MP_STATE_RUNNABLE:
12185 break;
12186
12187 default:
12188 goto out;
12189 }
12190
12191 /*
12192 * SIPI_RECEIVED is obsolete and no longer used internally; KVM instead
12193 * leaves the vCPU in INIT_RECIEVED (Wait-For-SIPI) and pends the SIPI.
12194 * Translate SIPI_RECEIVED as appropriate for backwards compatibility.
12195 */
12196 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
12197 mp_state->mp_state = KVM_MP_STATE_INIT_RECEIVED;
12198 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
12199 }
12200
12201 kvm_set_mp_state(vcpu, mp_state->mp_state);
12202 kvm_make_request(KVM_REQ_EVENT, vcpu);
12203
12204 ret = 0;
12205 out:
12206 vcpu_put(vcpu);
12207 return ret;
12208 }
12209
kvm_task_switch(struct kvm_vcpu * vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code)12210 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
12211 int reason, bool has_error_code, u32 error_code)
12212 {
12213 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
12214 int ret;
12215
12216 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_CET)) {
12217 u64 u_cet, s_cet;
12218
12219 /*
12220 * Check both User and Supervisor on task switches as inter-
12221 * privilege level task switches are impacted by CET at both
12222 * the current privilege level and the new privilege level, and
12223 * that information is not known at this time. The expectation
12224 * is that the guest won't require emulation of task switches
12225 * while using IBT or Shadow Stacks.
12226 */
12227 if (__kvm_emulate_msr_read(vcpu, MSR_IA32_U_CET, &u_cet) ||
12228 __kvm_emulate_msr_read(vcpu, MSR_IA32_S_CET, &s_cet))
12229 goto unhandled_task_switch;
12230
12231 if ((u_cet | s_cet) & (CET_ENDBR_EN | CET_SHSTK_EN))
12232 goto unhandled_task_switch;
12233 }
12234
12235 init_emulate_ctxt(vcpu);
12236
12237 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
12238 has_error_code, error_code);
12239
12240 /*
12241 * Report an error userspace if MMIO is needed, as KVM doesn't support
12242 * MMIO during a task switch (or any other complex operation).
12243 */
12244 if (ret || vcpu->mmio_needed)
12245 goto unhandled_task_switch;
12246
12247 kvm_rip_write(vcpu, ctxt->eip);
12248 kvm_set_rflags(vcpu, ctxt->eflags);
12249 return 1;
12250
12251 unhandled_task_switch:
12252 vcpu->mmio_needed = false;
12253 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
12254 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
12255 vcpu->run->internal.ndata = 0;
12256 return 0;
12257 }
12258 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_task_switch);
12259
kvm_is_valid_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12260 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12261 {
12262 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
12263 /*
12264 * When EFER.LME and CR0.PG are set, the processor is in
12265 * 64-bit mode (though maybe in a 32-bit code segment).
12266 * CR4.PAE and EFER.LMA must be set.
12267 */
12268 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
12269 return false;
12270 if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
12271 return false;
12272 } else {
12273 /*
12274 * Not in 64-bit mode: EFER.LMA is clear and the code
12275 * segment cannot be 64-bit.
12276 */
12277 if (sregs->efer & EFER_LMA || sregs->cs.l)
12278 return false;
12279 }
12280
12281 return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
12282 kvm_is_valid_cr0(vcpu, sregs->cr0);
12283 }
12284
__set_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs,int * mmu_reset_needed,bool update_pdptrs)12285 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
12286 int *mmu_reset_needed, bool update_pdptrs)
12287 {
12288 int idx;
12289 struct desc_ptr dt;
12290
12291 if (!kvm_is_valid_sregs(vcpu, sregs))
12292 return -EINVAL;
12293
12294 if (kvm_apic_set_base(vcpu, sregs->apic_base, true))
12295 return -EINVAL;
12296
12297 if (vcpu->arch.guest_state_protected)
12298 return 0;
12299
12300 dt.size = sregs->idt.limit;
12301 dt.address = sregs->idt.base;
12302 kvm_x86_call(set_idt)(vcpu, &dt);
12303 dt.size = sregs->gdt.limit;
12304 dt.address = sregs->gdt.base;
12305 kvm_x86_call(set_gdt)(vcpu, &dt);
12306
12307 vcpu->arch.cr2 = sregs->cr2;
12308 *mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
12309 vcpu->arch.cr3 = sregs->cr3;
12310 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12311 kvm_x86_call(post_set_cr3)(vcpu, sregs->cr3);
12312
12313 kvm_set_cr8(vcpu, sregs->cr8);
12314
12315 *mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
12316 kvm_x86_call(set_efer)(vcpu, sregs->efer);
12317
12318 *mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
12319 kvm_x86_call(set_cr0)(vcpu, sregs->cr0);
12320
12321 *mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
12322 kvm_x86_call(set_cr4)(vcpu, sregs->cr4);
12323
12324 if (update_pdptrs) {
12325 idx = srcu_read_lock(&vcpu->kvm->srcu);
12326 if (is_pae_paging(vcpu)) {
12327 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
12328 *mmu_reset_needed = 1;
12329 }
12330 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12331 }
12332
12333 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12334 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12335 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12336 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12337 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12338 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12339
12340 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12341 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12342
12343 update_cr8_intercept(vcpu);
12344
12345 /* Older userspace won't unhalt the vcpu on reset. */
12346 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
12347 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
12348 !is_protmode(vcpu))
12349 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12350
12351 return 0;
12352 }
12353
__set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12354 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12355 {
12356 int pending_vec, max_bits;
12357 int mmu_reset_needed = 0;
12358 int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
12359
12360 if (ret)
12361 return ret;
12362
12363 if (mmu_reset_needed) {
12364 kvm_mmu_reset_context(vcpu);
12365 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12366 }
12367
12368 max_bits = KVM_NR_INTERRUPTS;
12369 pending_vec = find_first_bit(
12370 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
12371
12372 if (pending_vec < max_bits) {
12373 kvm_queue_interrupt(vcpu, pending_vec, false);
12374 pr_debug("Set back pending irq %d\n", pending_vec);
12375 kvm_make_request(KVM_REQ_EVENT, vcpu);
12376 }
12377 return 0;
12378 }
12379
__set_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12380 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12381 {
12382 int mmu_reset_needed = 0;
12383 bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
12384 bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
12385 !(sregs2->efer & EFER_LMA);
12386 int i, ret;
12387
12388 if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
12389 return -EINVAL;
12390
12391 if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
12392 return -EINVAL;
12393
12394 ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
12395 &mmu_reset_needed, !valid_pdptrs);
12396 if (ret)
12397 return ret;
12398
12399 if (valid_pdptrs) {
12400 for (i = 0; i < 4 ; i++)
12401 kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
12402
12403 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
12404 mmu_reset_needed = 1;
12405 vcpu->arch.pdptrs_from_userspace = true;
12406 }
12407 if (mmu_reset_needed) {
12408 kvm_mmu_reset_context(vcpu);
12409 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12410 }
12411 return 0;
12412 }
12413
kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12414 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
12415 struct kvm_sregs *sregs)
12416 {
12417 int ret;
12418
12419 if (vcpu->kvm->arch.has_protected_state &&
12420 vcpu->arch.guest_state_protected)
12421 return -EINVAL;
12422
12423 vcpu_load(vcpu);
12424 ret = __set_sregs(vcpu, sregs);
12425 vcpu_put(vcpu);
12426 return ret;
12427 }
12428
kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm * kvm)12429 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
12430 {
12431 bool set = false;
12432 struct kvm_vcpu *vcpu;
12433 unsigned long i;
12434
12435 if (!enable_apicv)
12436 return;
12437
12438 down_write(&kvm->arch.apicv_update_lock);
12439
12440 kvm_for_each_vcpu(i, vcpu, kvm) {
12441 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
12442 set = true;
12443 break;
12444 }
12445 }
12446 __kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
12447 up_write(&kvm->arch.apicv_update_lock);
12448 }
12449
kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu * vcpu,struct kvm_guest_debug * dbg)12450 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
12451 struct kvm_guest_debug *dbg)
12452 {
12453 unsigned long rflags;
12454 int i, r;
12455
12456 if (vcpu->arch.guest_state_protected)
12457 return -EINVAL;
12458
12459 vcpu_load(vcpu);
12460
12461 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
12462 r = -EBUSY;
12463 if (kvm_is_exception_pending(vcpu))
12464 goto out;
12465 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
12466 kvm_queue_exception(vcpu, DB_VECTOR);
12467 else
12468 kvm_queue_exception(vcpu, BP_VECTOR);
12469 }
12470
12471 /*
12472 * Read rflags as long as potentially injected trace flags are still
12473 * filtered out.
12474 */
12475 rflags = kvm_get_rflags(vcpu);
12476
12477 vcpu->guest_debug = dbg->control;
12478 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
12479 vcpu->guest_debug = 0;
12480
12481 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
12482 for (i = 0; i < KVM_NR_DB_REGS; ++i)
12483 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
12484 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
12485 } else {
12486 for (i = 0; i < KVM_NR_DB_REGS; i++)
12487 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
12488 }
12489 kvm_update_dr7(vcpu);
12490
12491 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12492 vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
12493
12494 /*
12495 * Trigger an rflags update that will inject or remove the trace
12496 * flags.
12497 */
12498 kvm_set_rflags(vcpu, rflags);
12499
12500 kvm_x86_call(update_exception_bitmap)(vcpu);
12501
12502 kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12503
12504 r = 0;
12505
12506 out:
12507 vcpu_put(vcpu);
12508 return r;
12509 }
12510
12511 /*
12512 * Translate a guest virtual address to a guest physical address.
12513 */
kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu * vcpu,struct kvm_translation * tr)12514 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12515 struct kvm_translation *tr)
12516 {
12517 unsigned long vaddr = tr->linear_address;
12518 gpa_t gpa;
12519 int idx;
12520
12521 vcpu_load(vcpu);
12522
12523 idx = srcu_read_lock(&vcpu->kvm->srcu);
12524 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
12525 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12526 tr->physical_address = gpa;
12527 tr->valid = gpa != INVALID_GPA;
12528 tr->writeable = 1;
12529 tr->usermode = 0;
12530
12531 vcpu_put(vcpu);
12532 return 0;
12533 }
12534
kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12535 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12536 {
12537 struct fxregs_state *fxsave;
12538
12539 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12540 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12541
12542 vcpu_load(vcpu);
12543
12544 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12545 memcpy(fpu->fpr, fxsave->st_space, 128);
12546 fpu->fcw = fxsave->cwd;
12547 fpu->fsw = fxsave->swd;
12548 fpu->ftwx = fxsave->twd;
12549 fpu->last_opcode = fxsave->fop;
12550 fpu->last_ip = fxsave->rip;
12551 fpu->last_dp = fxsave->rdp;
12552 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
12553
12554 vcpu_put(vcpu);
12555 return 0;
12556 }
12557
kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12558 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12559 {
12560 struct fxregs_state *fxsave;
12561
12562 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12563 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12564
12565 vcpu_load(vcpu);
12566
12567 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12568
12569 memcpy(fxsave->st_space, fpu->fpr, 128);
12570 fxsave->cwd = fpu->fcw;
12571 fxsave->swd = fpu->fsw;
12572 fxsave->twd = fpu->ftwx;
12573 fxsave->fop = fpu->last_opcode;
12574 fxsave->rip = fpu->last_ip;
12575 fxsave->rdp = fpu->last_dp;
12576 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
12577
12578 vcpu_put(vcpu);
12579 return 0;
12580 }
12581
store_regs(struct kvm_vcpu * vcpu)12582 static void store_regs(struct kvm_vcpu *vcpu)
12583 {
12584 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12585
12586 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12587 __get_regs(vcpu, &vcpu->run->s.regs.regs);
12588
12589 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12590 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12591
12592 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12593 kvm_vcpu_ioctl_x86_get_vcpu_events(
12594 vcpu, &vcpu->run->s.regs.events);
12595 }
12596
sync_regs(struct kvm_vcpu * vcpu)12597 static int sync_regs(struct kvm_vcpu *vcpu)
12598 {
12599 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12600 __set_regs(vcpu, &vcpu->run->s.regs.regs);
12601 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12602 }
12603
12604 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
12605 struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12606
12607 if (__set_sregs(vcpu, &sregs))
12608 return -EINVAL;
12609
12610 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12611 }
12612
12613 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
12614 struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12615
12616 if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
12617 return -EINVAL;
12618
12619 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12620 }
12621
12622 return 0;
12623 }
12624
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)12625 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
12626 {
12627 if (kvm_check_tsc_unstable() && kvm->created_vcpus)
12628 pr_warn_once("SMP vm created on host with unstable TSC; "
12629 "guest TSC will not be reliable\n");
12630
12631 if (!kvm->arch.max_vcpu_ids)
12632 kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12633
12634 if (id >= kvm->arch.max_vcpu_ids)
12635 return -EINVAL;
12636
12637 return kvm_x86_call(vcpu_precreate)(kvm);
12638 }
12639
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)12640 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
12641 {
12642 struct page *page;
12643 int r;
12644
12645 vcpu->arch.last_vmentry_cpu = -1;
12646 vcpu->arch.regs_avail = ~0;
12647 vcpu->arch.regs_dirty = ~0;
12648
12649 kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
12650
12651 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
12652 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12653 else
12654 kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);
12655
12656 r = kvm_mmu_create(vcpu);
12657 if (r < 0)
12658 return r;
12659
12660 r = kvm_create_lapic(vcpu);
12661 if (r < 0)
12662 goto fail_mmu_destroy;
12663
12664 r = -ENOMEM;
12665
12666 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
12667 if (!page)
12668 goto fail_free_lapic;
12669 vcpu->arch.pio_data = page_address(page);
12670
12671 vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
12672 GFP_KERNEL_ACCOUNT);
12673 vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12674 GFP_KERNEL_ACCOUNT);
12675 if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
12676 goto fail_free_mce_banks;
12677 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12678
12679 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12680 GFP_KERNEL_ACCOUNT))
12681 goto fail_free_mce_banks;
12682
12683 if (!alloc_emulate_ctxt(vcpu))
12684 goto free_wbinvd_dirty_mask;
12685
12686 if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
12687 pr_err("failed to allocate vcpu's fpu\n");
12688 goto free_emulate_ctxt;
12689 }
12690
12691 kvm_async_pf_hash_reset(vcpu);
12692
12693 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) {
12694 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12695 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12696 vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12697 }
12698 kvm_pmu_init(vcpu);
12699
12700 vcpu->arch.pending_external_vector = -1;
12701 vcpu->arch.preempted_in_kernel = false;
12702
12703 #if IS_ENABLED(CONFIG_HYPERV)
12704 vcpu->arch.hv_root_tdp = INVALID_PAGE;
12705 #endif
12706
12707 r = kvm_x86_call(vcpu_create)(vcpu);
12708 if (r)
12709 goto free_guest_fpu;
12710
12711 kvm_xen_init_vcpu(vcpu);
12712 vcpu_load(vcpu);
12713 kvm_vcpu_after_set_cpuid(vcpu);
12714 kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12715 kvm_vcpu_reset(vcpu, false);
12716 kvm_init_mmu(vcpu);
12717 vcpu_put(vcpu);
12718 return 0;
12719
12720 free_guest_fpu:
12721 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12722 free_emulate_ctxt:
12723 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12724 free_wbinvd_dirty_mask:
12725 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12726 fail_free_mce_banks:
12727 kfree(vcpu->arch.mce_banks);
12728 kfree(vcpu->arch.mci_ctl2_banks);
12729 free_page((unsigned long)vcpu->arch.pio_data);
12730 fail_free_lapic:
12731 kvm_free_lapic(vcpu);
12732 fail_mmu_destroy:
12733 kvm_mmu_destroy(vcpu);
12734 return r;
12735 }
12736
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)12737 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12738 {
12739 struct kvm *kvm = vcpu->kvm;
12740
12741 if (mutex_lock_killable(&vcpu->mutex))
12742 return;
12743 vcpu_load(vcpu);
12744 kvm_synchronize_tsc(vcpu, NULL);
12745 vcpu_put(vcpu);
12746
12747 /* poll control enabled by default */
12748 vcpu->arch.msr_kvm_poll_control = 1;
12749
12750 mutex_unlock(&vcpu->mutex);
12751
12752 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
12753 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
12754 KVMCLOCK_SYNC_PERIOD);
12755 }
12756
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)12757 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12758 {
12759 int idx, cpu;
12760
12761 kvm_clear_async_pf_completion_queue(vcpu);
12762 kvm_mmu_unload(vcpu);
12763
12764 kvmclock_reset(vcpu);
12765
12766 for_each_possible_cpu(cpu)
12767 cmpxchg(per_cpu_ptr(&last_vcpu, cpu), vcpu, NULL);
12768
12769 kvm_x86_call(vcpu_free)(vcpu);
12770
12771 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12772 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12773 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12774
12775 kvm_xen_destroy_vcpu(vcpu);
12776 kvm_hv_vcpu_uninit(vcpu);
12777 kvm_pmu_destroy(vcpu);
12778 kfree(vcpu->arch.mce_banks);
12779 kfree(vcpu->arch.mci_ctl2_banks);
12780 kvm_free_lapic(vcpu);
12781 idx = srcu_read_lock(&vcpu->kvm->srcu);
12782 kvm_mmu_destroy(vcpu);
12783 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12784 free_page((unsigned long)vcpu->arch.pio_data);
12785 kvfree(vcpu->arch.cpuid_entries);
12786 }
12787
kvm_xstate_reset(struct kvm_vcpu * vcpu,bool init_event)12788 static void kvm_xstate_reset(struct kvm_vcpu *vcpu, bool init_event)
12789 {
12790 struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12791 u64 xfeatures_mask;
12792 int i;
12793
12794 /*
12795 * Guest FPU state is zero allocated and so doesn't need to be manually
12796 * cleared on RESET, i.e. during vCPU creation.
12797 */
12798 if (!init_event || !fpstate)
12799 return;
12800
12801 /*
12802 * On INIT, only select XSTATE components are zeroed, most components
12803 * are unchanged. Currently, the only components that are zeroed and
12804 * supported by KVM are MPX and CET related.
12805 */
12806 xfeatures_mask = (kvm_caps.supported_xcr0 | kvm_caps.supported_xss) &
12807 (XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR |
12808 XFEATURE_MASK_CET_ALL);
12809 if (!xfeatures_mask)
12810 return;
12811
12812 BUILD_BUG_ON(sizeof(xfeatures_mask) * BITS_PER_BYTE <= XFEATURE_MAX);
12813
12814 /*
12815 * All paths that lead to INIT are required to load the guest's FPU
12816 * state (because most paths are buried in KVM_RUN).
12817 */
12818 kvm_put_guest_fpu(vcpu);
12819 for_each_set_bit(i, (unsigned long *)&xfeatures_mask, XFEATURE_MAX)
12820 fpstate_clear_xstate_component(fpstate, i);
12821 kvm_load_guest_fpu(vcpu);
12822 }
12823
kvm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)12824 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
12825 {
12826 struct kvm_cpuid_entry2 *cpuid_0x1;
12827 unsigned long old_cr0 = kvm_read_cr0(vcpu);
12828 unsigned long new_cr0;
12829
12830 /*
12831 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12832 * to handle side effects. RESET emulation hits those flows and relies
12833 * on emulated/virtualized registers, including those that are loaded
12834 * into hardware, to be zeroed at vCPU creation. Use CRs as a sentinel
12835 * to detect improper or missing initialization.
12836 */
12837 WARN_ON_ONCE(!init_event &&
12838 (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
12839
12840 /*
12841 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12842 * possible to INIT the vCPU while L2 is active. Force the vCPU back
12843 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12844 * bits), i.e. virtualization is disabled.
12845 */
12846 if (is_guest_mode(vcpu))
12847 kvm_leave_nested(vcpu);
12848
12849 kvm_lapic_reset(vcpu, init_event);
12850
12851 WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
12852 vcpu->arch.hflags = 0;
12853
12854 vcpu->arch.smi_pending = 0;
12855 vcpu->arch.smi_count = 0;
12856 atomic_set(&vcpu->arch.nmi_queued, 0);
12857 vcpu->arch.nmi_pending = 0;
12858 vcpu->arch.nmi_injected = false;
12859 kvm_clear_interrupt_queue(vcpu);
12860 kvm_clear_exception_queue(vcpu);
12861
12862 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
12863 kvm_update_dr0123(vcpu);
12864 vcpu->arch.dr6 = DR6_ACTIVE_LOW;
12865 vcpu->arch.dr7 = DR7_FIXED_1;
12866 kvm_update_dr7(vcpu);
12867
12868 vcpu->arch.cr2 = 0;
12869
12870 kvm_make_request(KVM_REQ_EVENT, vcpu);
12871 vcpu->arch.apf.msr_en_val = 0;
12872 vcpu->arch.apf.msr_int_val = 0;
12873 vcpu->arch.st.msr_val = 0;
12874
12875 kvmclock_reset(vcpu);
12876
12877 kvm_clear_async_pf_completion_queue(vcpu);
12878 kvm_async_pf_hash_reset(vcpu);
12879 vcpu->arch.apf.halted = false;
12880
12881 kvm_xstate_reset(vcpu, init_event);
12882
12883 if (!init_event) {
12884 vcpu->arch.smbase = 0x30000;
12885
12886 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
12887
12888 vcpu->arch.msr_misc_features_enables = 0;
12889 vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12890 MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
12891
12892 __kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12893 kvm_msr_write(vcpu, MSR_IA32_XSS, 0);
12894 }
12895
12896 /* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
12897 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
12898 kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
12899
12900 /*
12901 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12902 * if no CPUID match is found. Note, it's impossible to get a match at
12903 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
12904 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12905 * on RESET. But, go through the motions in case that's ever remedied.
12906 */
12907 cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
12908 kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
12909
12910 kvm_x86_call(vcpu_reset)(vcpu, init_event);
12911
12912 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12913 kvm_rip_write(vcpu, 0xfff0);
12914
12915 vcpu->arch.cr3 = 0;
12916 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12917
12918 /*
12919 * CR0.CD/NW are set on RESET, preserved on INIT. Note, some versions
12920 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12921 * (or qualify) that with a footnote stating that CD/NW are preserved.
12922 */
12923 new_cr0 = X86_CR0_ET;
12924 if (init_event)
12925 new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12926 else
12927 new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12928
12929 kvm_x86_call(set_cr0)(vcpu, new_cr0);
12930 kvm_x86_call(set_cr4)(vcpu, 0);
12931 kvm_x86_call(set_efer)(vcpu, 0);
12932 kvm_x86_call(update_exception_bitmap)(vcpu);
12933
12934 /*
12935 * On the standard CR0/CR4/EFER modification paths, there are several
12936 * complex conditions determining whether the MMU has to be reset and/or
12937 * which PCIDs have to be flushed. However, CR0.WP and the paging-related
12938 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12939 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12940 * CR0 will be '0' prior to RESET). So we only need to check CR0.PG here.
12941 */
12942 if (old_cr0 & X86_CR0_PG) {
12943 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12944 kvm_mmu_reset_context(vcpu);
12945 }
12946
12947 /*
12948 * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
12949 * APM states the TLBs are untouched by INIT, but it also states that
12950 * the TLBs are flushed on "External initialization of the processor."
12951 * Flush the guest TLB regardless of vendor, there is no meaningful
12952 * benefit in relying on the guest to flush the TLB immediately after
12953 * INIT. A spurious TLB flush is benign and likely negligible from a
12954 * performance perspective.
12955 */
12956 if (init_event)
12957 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12958 }
12959 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_reset);
12960
kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)12961 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
12962 {
12963 struct kvm_segment cs;
12964
12965 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
12966 cs.selector = vector << 8;
12967 cs.base = vector << 12;
12968 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
12969 kvm_rip_write(vcpu, 0);
12970 }
12971 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_deliver_sipi_vector);
12972
kvm_arch_enable_virtualization(void)12973 void kvm_arch_enable_virtualization(void)
12974 {
12975 cpu_emergency_register_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12976 }
12977
kvm_arch_disable_virtualization(void)12978 void kvm_arch_disable_virtualization(void)
12979 {
12980 cpu_emergency_unregister_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12981 }
12982
kvm_arch_enable_virtualization_cpu(void)12983 int kvm_arch_enable_virtualization_cpu(void)
12984 {
12985 struct kvm *kvm;
12986 struct kvm_vcpu *vcpu;
12987 unsigned long i;
12988 int ret;
12989 u64 local_tsc;
12990 u64 max_tsc = 0;
12991 bool stable, backwards_tsc = false;
12992
12993 kvm_user_return_msr_cpu_online();
12994
12995 ret = kvm_x86_check_processor_compatibility();
12996 if (ret)
12997 return ret;
12998
12999 ret = kvm_x86_call(enable_virtualization_cpu)();
13000 if (ret != 0)
13001 return ret;
13002
13003 local_tsc = rdtsc();
13004 stable = !kvm_check_tsc_unstable();
13005 list_for_each_entry(kvm, &vm_list, vm_list) {
13006 kvm_for_each_vcpu(i, vcpu, kvm) {
13007 if (!stable && vcpu->cpu == smp_processor_id())
13008 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
13009 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
13010 backwards_tsc = true;
13011 if (vcpu->arch.last_host_tsc > max_tsc)
13012 max_tsc = vcpu->arch.last_host_tsc;
13013 }
13014 }
13015 }
13016
13017 /*
13018 * Sometimes, even reliable TSCs go backwards. This happens on
13019 * platforms that reset TSC during suspend or hibernate actions, but
13020 * maintain synchronization. We must compensate. Fortunately, we can
13021 * detect that condition here, which happens early in CPU bringup,
13022 * before any KVM threads can be running. Unfortunately, we can't
13023 * bring the TSCs fully up to date with real time, as we aren't yet far
13024 * enough into CPU bringup that we know how much real time has actually
13025 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
13026 * variables that haven't been updated yet.
13027 *
13028 * So we simply find the maximum observed TSC above, then record the
13029 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
13030 * the adjustment will be applied. Note that we accumulate
13031 * adjustments, in case multiple suspend cycles happen before some VCPU
13032 * gets a chance to run again. In the event that no KVM threads get a
13033 * chance to run, we will miss the entire elapsed period, as we'll have
13034 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
13035 * loose cycle time. This isn't too big a deal, since the loss will be
13036 * uniform across all VCPUs (not to mention the scenario is extremely
13037 * unlikely). It is possible that a second hibernate recovery happens
13038 * much faster than a first, causing the observed TSC here to be
13039 * smaller; this would require additional padding adjustment, which is
13040 * why we set last_host_tsc to the local tsc observed here.
13041 *
13042 * N.B. - this code below runs only on platforms with reliable TSC,
13043 * as that is the only way backwards_tsc is set above. Also note
13044 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
13045 * have the same delta_cyc adjustment applied if backwards_tsc
13046 * is detected. Note further, this adjustment is only done once,
13047 * as we reset last_host_tsc on all VCPUs to stop this from being
13048 * called multiple times (one for each physical CPU bringup).
13049 *
13050 * Platforms with unreliable TSCs don't have to deal with this, they
13051 * will be compensated by the logic in vcpu_load, which sets the TSC to
13052 * catchup mode. This will catchup all VCPUs to real time, but cannot
13053 * guarantee that they stay in perfect synchronization.
13054 */
13055 if (backwards_tsc) {
13056 u64 delta_cyc = max_tsc - local_tsc;
13057 list_for_each_entry(kvm, &vm_list, vm_list) {
13058 kvm->arch.backwards_tsc_observed = true;
13059 kvm_for_each_vcpu(i, vcpu, kvm) {
13060 vcpu->arch.tsc_offset_adjustment += delta_cyc;
13061 vcpu->arch.last_host_tsc = local_tsc;
13062 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
13063 }
13064
13065 /*
13066 * We have to disable TSC offset matching.. if you were
13067 * booting a VM while issuing an S4 host suspend....
13068 * you may have some problem. Solving this issue is
13069 * left as an exercise to the reader.
13070 */
13071 kvm->arch.last_tsc_nsec = 0;
13072 kvm->arch.last_tsc_write = 0;
13073 }
13074
13075 }
13076 return 0;
13077 }
13078
kvm_arch_disable_virtualization_cpu(void)13079 void kvm_arch_disable_virtualization_cpu(void)
13080 {
13081 kvm_x86_call(disable_virtualization_cpu)();
13082 drop_user_return_notifiers();
13083 }
13084
kvm_vcpu_is_reset_bsp(struct kvm_vcpu * vcpu)13085 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
13086 {
13087 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
13088 }
13089 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_is_reset_bsp);
13090
kvm_vcpu_is_bsp(struct kvm_vcpu * vcpu)13091 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
13092 {
13093 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
13094 }
13095
kvm_arch_free_vm(struct kvm * kvm)13096 void kvm_arch_free_vm(struct kvm *kvm)
13097 {
13098 #if IS_ENABLED(CONFIG_HYPERV)
13099 kfree(kvm->arch.hv_pa_pg);
13100 #endif
13101 __kvm_arch_free_vm(kvm);
13102 }
13103
13104
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)13105 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
13106 {
13107 int ret;
13108 unsigned long flags;
13109
13110 if (!kvm_is_vm_type_supported(type))
13111 return -EINVAL;
13112
13113 kvm->arch.vm_type = type;
13114 kvm->arch.has_private_mem =
13115 (type == KVM_X86_SW_PROTECTED_VM);
13116 /* Decided by the vendor code for other VM types. */
13117 kvm->arch.pre_fault_allowed =
13118 type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
13119 kvm->arch.disabled_quirks = kvm_caps.inapplicable_quirks & kvm_caps.supported_quirks;
13120
13121 ret = kvm_page_track_init(kvm);
13122 if (ret)
13123 goto out;
13124
13125 ret = kvm_mmu_init_vm(kvm);
13126 if (ret)
13127 goto out_cleanup_page_track;
13128
13129 ret = kvm_x86_call(vm_init)(kvm);
13130 if (ret)
13131 goto out_uninit_mmu;
13132
13133 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
13134
13135 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
13136 mutex_init(&kvm->arch.apic_map_lock);
13137 seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
13138 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
13139
13140 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
13141 pvclock_update_vm_gtod_copy(kvm);
13142 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
13143
13144 kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
13145 kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
13146 kvm->arch.guest_can_read_msr_platform_info = true;
13147 kvm->arch.enable_pmu = enable_pmu;
13148
13149 #if IS_ENABLED(CONFIG_HYPERV)
13150 spin_lock_init(&kvm->arch.hv_root_tdp_lock);
13151 kvm->arch.hv_root_tdp = INVALID_PAGE;
13152 #endif
13153
13154 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
13155 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
13156
13157 kvm_apicv_init(kvm);
13158 kvm_hv_init_vm(kvm);
13159 kvm_xen_init_vm(kvm);
13160
13161 if (ignore_msrs && !report_ignored_msrs) {
13162 pr_warn_once("Running KVM with ignore_msrs=1 and report_ignored_msrs=0 is not a\n"
13163 "a supported configuration. Lying to the guest about the existence of MSRs\n"
13164 "may cause the guest operating system to hang or produce errors. If a guest\n"
13165 "does not run without ignore_msrs=1, please report it to kvm@vger.kernel.org.\n");
13166 }
13167
13168 once_init(&kvm->arch.nx_once);
13169 return 0;
13170
13171 out_uninit_mmu:
13172 kvm_mmu_uninit_vm(kvm);
13173 out_cleanup_page_track:
13174 kvm_page_track_cleanup(kvm);
13175 out:
13176 return ret;
13177 }
13178
13179 /**
13180 * __x86_set_memory_region: Setup KVM internal memory slot
13181 *
13182 * @kvm: the kvm pointer to the VM.
13183 * @id: the slot ID to setup.
13184 * @gpa: the GPA to install the slot (unused when @size == 0).
13185 * @size: the size of the slot. Set to zero to uninstall a slot.
13186 *
13187 * This function helps to setup a KVM internal memory slot. Specify
13188 * @size > 0 to install a new slot, while @size == 0 to uninstall a
13189 * slot. The return code can be one of the following:
13190 *
13191 * HVA: on success (uninstall will return a bogus HVA)
13192 * -errno: on error
13193 *
13194 * The caller should always use IS_ERR() to check the return value
13195 * before use. Note, the KVM internal memory slots are guaranteed to
13196 * remain valid and unchanged until the VM is destroyed, i.e., the
13197 * GPA->HVA translation will not change. However, the HVA is a user
13198 * address, i.e. its accessibility is not guaranteed, and must be
13199 * accessed via __copy_{to,from}_user().
13200 */
__x86_set_memory_region(struct kvm * kvm,int id,gpa_t gpa,u32 size)13201 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
13202 u32 size)
13203 {
13204 int i, r;
13205 unsigned long hva, old_npages;
13206 struct kvm_memslots *slots = kvm_memslots(kvm);
13207 struct kvm_memory_slot *slot;
13208
13209 lockdep_assert_held(&kvm->slots_lock);
13210
13211 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
13212 return ERR_PTR_USR(-EINVAL);
13213
13214 slot = id_to_memslot(slots, id);
13215 if (size) {
13216 if (slot && slot->npages)
13217 return ERR_PTR_USR(-EEXIST);
13218
13219 /*
13220 * MAP_SHARED to prevent internal slot pages from being moved
13221 * by fork()/COW.
13222 */
13223 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
13224 MAP_SHARED | MAP_ANONYMOUS, 0);
13225 if (IS_ERR_VALUE(hva))
13226 return (void __user *)hva;
13227 } else {
13228 if (!slot || !slot->npages)
13229 return NULL;
13230
13231 old_npages = slot->npages;
13232 hva = slot->userspace_addr;
13233 }
13234
13235 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
13236 struct kvm_userspace_memory_region2 m;
13237
13238 m.slot = id | (i << 16);
13239 m.flags = 0;
13240 m.guest_phys_addr = gpa;
13241 m.userspace_addr = hva;
13242 m.memory_size = size;
13243 r = kvm_set_internal_memslot(kvm, &m);
13244 if (r < 0)
13245 return ERR_PTR_USR(r);
13246 }
13247
13248 if (!size)
13249 vm_munmap(hva, old_npages * PAGE_SIZE);
13250
13251 return (void __user *)hva;
13252 }
13253 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__x86_set_memory_region);
13254
kvm_arch_pre_destroy_vm(struct kvm * kvm)13255 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
13256 {
13257 /*
13258 * Stop all background workers and kthreads before destroying vCPUs, as
13259 * iterating over vCPUs in a different task while vCPUs are being freed
13260 * is unsafe, i.e. will lead to use-after-free. The PIT also needs to
13261 * be stopped before IRQ routing is freed.
13262 */
13263 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
13264 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
13265
13266 #ifdef CONFIG_KVM_IOAPIC
13267 kvm_free_pit(kvm);
13268 #endif
13269
13270 kvm_mmu_pre_destroy_vm(kvm);
13271 static_call_cond(kvm_x86_vm_pre_destroy)(kvm);
13272 }
13273
kvm_arch_destroy_vm(struct kvm * kvm)13274 void kvm_arch_destroy_vm(struct kvm *kvm)
13275 {
13276 if (current->mm == kvm->mm) {
13277 /*
13278 * Free memory regions allocated on behalf of userspace,
13279 * unless the memory map has changed due to process exit
13280 * or fd copying.
13281 */
13282 mutex_lock(&kvm->slots_lock);
13283 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
13284 0, 0);
13285 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
13286 0, 0);
13287 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
13288 mutex_unlock(&kvm->slots_lock);
13289 }
13290 kvm_destroy_vcpus(kvm);
13291 kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
13292 #ifdef CONFIG_KVM_IOAPIC
13293 kvm_pic_destroy(kvm);
13294 kvm_ioapic_destroy(kvm);
13295 #endif
13296 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
13297 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
13298 kvm_mmu_uninit_vm(kvm);
13299 kvm_page_track_cleanup(kvm);
13300 kvm_xen_destroy_vm(kvm);
13301 kvm_hv_destroy_vm(kvm);
13302 kvm_x86_call(vm_destroy)(kvm);
13303 }
13304
memslot_rmap_free(struct kvm_memory_slot * slot)13305 static void memslot_rmap_free(struct kvm_memory_slot *slot)
13306 {
13307 int i;
13308
13309 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13310 vfree(slot->arch.rmap[i]);
13311 slot->arch.rmap[i] = NULL;
13312 }
13313 }
13314
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)13315 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
13316 {
13317 int i;
13318
13319 memslot_rmap_free(slot);
13320
13321 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13322 vfree(slot->arch.lpage_info[i - 1]);
13323 slot->arch.lpage_info[i - 1] = NULL;
13324 }
13325
13326 kvm_page_track_free_memslot(slot);
13327 }
13328
memslot_rmap_alloc(struct kvm_memory_slot * slot,unsigned long npages)13329 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
13330 {
13331 const int sz = sizeof(*slot->arch.rmap[0]);
13332 int i;
13333
13334 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13335 int level = i + 1;
13336 int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13337
13338 if (slot->arch.rmap[i])
13339 continue;
13340
13341 slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
13342 if (!slot->arch.rmap[i]) {
13343 memslot_rmap_free(slot);
13344 return -ENOMEM;
13345 }
13346 }
13347
13348 return 0;
13349 }
13350
kvm_alloc_memslot_metadata(struct kvm * kvm,struct kvm_memory_slot * slot)13351 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
13352 struct kvm_memory_slot *slot)
13353 {
13354 unsigned long npages = slot->npages;
13355 int i, r;
13356
13357 /*
13358 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
13359 * old arrays will be freed by kvm_set_memory_region() if installing
13360 * the new memslot is successful.
13361 */
13362 memset(&slot->arch, 0, sizeof(slot->arch));
13363
13364 if (kvm_memslots_have_rmaps(kvm)) {
13365 r = memslot_rmap_alloc(slot, npages);
13366 if (r)
13367 return r;
13368 }
13369
13370 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13371 struct kvm_lpage_info *linfo;
13372 unsigned long ugfn;
13373 int lpages;
13374 int level = i + 1;
13375
13376 lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13377
13378 linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
13379 if (!linfo)
13380 goto out_free;
13381
13382 slot->arch.lpage_info[i - 1] = linfo;
13383
13384 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
13385 linfo[0].disallow_lpage = 1;
13386 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
13387 linfo[lpages - 1].disallow_lpage = 1;
13388 ugfn = slot->userspace_addr >> PAGE_SHIFT;
13389 /*
13390 * If the gfn and userspace address are not aligned wrt each
13391 * other, disable large page support for this slot.
13392 */
13393 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
13394 unsigned long j;
13395
13396 for (j = 0; j < lpages; ++j)
13397 linfo[j].disallow_lpage = 1;
13398 }
13399 }
13400
13401 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
13402 kvm_mmu_init_memslot_memory_attributes(kvm, slot);
13403 #endif
13404
13405 if (kvm_page_track_create_memslot(kvm, slot, npages))
13406 goto out_free;
13407
13408 return 0;
13409
13410 out_free:
13411 memslot_rmap_free(slot);
13412
13413 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13414 vfree(slot->arch.lpage_info[i - 1]);
13415 slot->arch.lpage_info[i - 1] = NULL;
13416 }
13417 return -ENOMEM;
13418 }
13419
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)13420 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
13421 {
13422 struct kvm_vcpu *vcpu;
13423 unsigned long i;
13424
13425 /*
13426 * memslots->generation has been incremented.
13427 * mmio generation may have reached its maximum value.
13428 */
13429 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
13430
13431 /* Force re-initialization of steal_time cache */
13432 kvm_for_each_vcpu(i, vcpu, kvm)
13433 kvm_vcpu_kick(vcpu);
13434 }
13435
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)13436 int kvm_arch_prepare_memory_region(struct kvm *kvm,
13437 const struct kvm_memory_slot *old,
13438 struct kvm_memory_slot *new,
13439 enum kvm_mr_change change)
13440 {
13441 /*
13442 * KVM doesn't support moving memslots when there are external page
13443 * trackers attached to the VM, i.e. if KVMGT is in use.
13444 */
13445 if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
13446 return -EINVAL;
13447
13448 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
13449 if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
13450 return -EINVAL;
13451
13452 if (kvm_is_gfn_alias(kvm, new->base_gfn + new->npages - 1))
13453 return -EINVAL;
13454
13455 return kvm_alloc_memslot_metadata(kvm, new);
13456 }
13457
13458 if (change == KVM_MR_FLAGS_ONLY)
13459 memcpy(&new->arch, &old->arch, sizeof(old->arch));
13460 else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
13461 return -EIO;
13462
13463 return 0;
13464 }
13465
13466
kvm_mmu_update_cpu_dirty_logging(struct kvm * kvm,bool enable)13467 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
13468 {
13469 int nr_slots;
13470
13471 if (!kvm->arch.cpu_dirty_log_size)
13472 return;
13473
13474 nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
13475 if ((enable && nr_slots == 1) || !nr_slots)
13476 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
13477 }
13478
kvm_mmu_slot_apply_flags(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13479 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
13480 struct kvm_memory_slot *old,
13481 const struct kvm_memory_slot *new,
13482 enum kvm_mr_change change)
13483 {
13484 u32 old_flags = old ? old->flags : 0;
13485 u32 new_flags = new ? new->flags : 0;
13486 bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
13487
13488 /*
13489 * Update CPU dirty logging if dirty logging is being toggled. This
13490 * applies to all operations.
13491 */
13492 if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
13493 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
13494
13495 /*
13496 * Nothing more to do for RO slots (which can't be dirtied and can't be
13497 * made writable) or CREATE/MOVE/DELETE of a slot.
13498 *
13499 * For a memslot with dirty logging disabled:
13500 * CREATE: No dirty mappings will already exist.
13501 * MOVE/DELETE: The old mappings will already have been cleaned up by
13502 * kvm_arch_flush_shadow_memslot()
13503 *
13504 * For a memslot with dirty logging enabled:
13505 * CREATE: No shadow pages exist, thus nothing to write-protect
13506 * and no dirty bits to clear.
13507 * MOVE/DELETE: The old mappings will already have been cleaned up by
13508 * kvm_arch_flush_shadow_memslot().
13509 */
13510 if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
13511 return;
13512
13513 /*
13514 * READONLY and non-flags changes were filtered out above, and the only
13515 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13516 * logging isn't being toggled on or off.
13517 */
13518 if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
13519 return;
13520
13521 if (!log_dirty_pages) {
13522 /*
13523 * Recover huge page mappings in the slot now that dirty logging
13524 * is disabled, i.e. now that KVM does not have to track guest
13525 * writes at 4KiB granularity.
13526 *
13527 * Dirty logging might be disabled by userspace if an ongoing VM
13528 * live migration is cancelled and the VM must continue running
13529 * on the source.
13530 */
13531 kvm_mmu_recover_huge_pages(kvm, new);
13532 } else {
13533 /*
13534 * Initially-all-set does not require write protecting any page,
13535 * because they're all assumed to be dirty.
13536 */
13537 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13538 return;
13539
13540 if (READ_ONCE(eager_page_split))
13541 kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13542
13543 if (kvm->arch.cpu_dirty_log_size) {
13544 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13545 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13546 } else {
13547 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
13548 }
13549
13550 /*
13551 * Unconditionally flush the TLBs after enabling dirty logging.
13552 * A flush is almost always going to be necessary (see below),
13553 * and unconditionally flushing allows the helpers to omit
13554 * the subtly complex checks when removing write access.
13555 *
13556 * Do the flush outside of mmu_lock to reduce the amount of
13557 * time mmu_lock is held. Flushing after dropping mmu_lock is
13558 * safe as KVM only needs to guarantee the slot is fully
13559 * write-protected before returning to userspace, i.e. before
13560 * userspace can consume the dirty status.
13561 *
13562 * Flushing outside of mmu_lock requires KVM to be careful when
13563 * making decisions based on writable status of an SPTE, e.g. a
13564 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13565 *
13566 * Specifically, KVM also write-protects guest page tables to
13567 * monitor changes when using shadow paging, and must guarantee
13568 * no CPUs can write to those page before mmu_lock is dropped.
13569 * Because CPUs may have stale TLB entries at this point, a
13570 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13571 *
13572 * KVM also allows making SPTES writable outside of mmu_lock,
13573 * e.g. to allow dirty logging without taking mmu_lock.
13574 *
13575 * To handle these scenarios, KVM uses a separate software-only
13576 * bit (MMU-writable) to track if a SPTE is !writable due to
13577 * a guest page table being write-protected (KVM clears the
13578 * MMU-writable flag when write-protecting for shadow paging).
13579 *
13580 * The use of MMU-writable is also the primary motivation for
13581 * the unconditional flush. Because KVM must guarantee that a
13582 * CPU doesn't contain stale, writable TLB entries for a
13583 * !MMU-writable SPTE, KVM must flush if it encounters any
13584 * MMU-writable SPTE regardless of whether the actual hardware
13585 * writable bit was set. I.e. KVM is almost guaranteed to need
13586 * to flush, while unconditionally flushing allows the "remove
13587 * write access" helpers to ignore MMU-writable entirely.
13588 *
13589 * See is_writable_pte() for more details (the case involving
13590 * access-tracked SPTEs is particularly relevant).
13591 */
13592 kvm_flush_remote_tlbs_memslot(kvm, new);
13593 }
13594 }
13595
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13596 void kvm_arch_commit_memory_region(struct kvm *kvm,
13597 struct kvm_memory_slot *old,
13598 const struct kvm_memory_slot *new,
13599 enum kvm_mr_change change)
13600 {
13601 if (change == KVM_MR_DELETE)
13602 kvm_page_track_delete_slot(kvm, old);
13603
13604 if (!kvm->arch.n_requested_mmu_pages &&
13605 (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13606 unsigned long nr_mmu_pages;
13607
13608 nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13609 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13610 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13611 }
13612
13613 kvm_mmu_slot_apply_flags(kvm, old, new, change);
13614
13615 /* Free the arrays associated with the old memslot. */
13616 if (change == KVM_MR_MOVE)
13617 kvm_arch_free_memslot(kvm, old);
13618 }
13619
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)13620 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13621 {
13622 WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13623
13624 if (vcpu->arch.guest_state_protected)
13625 return true;
13626
13627 return kvm_x86_call(get_cpl)(vcpu) == 0;
13628 }
13629
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)13630 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13631 {
13632 WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13633
13634 if (vcpu->arch.guest_state_protected)
13635 return 0;
13636
13637 return kvm_rip_read(vcpu);
13638 }
13639
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)13640 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13641 {
13642 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13643 }
13644
kvm_arch_interrupt_allowed(struct kvm_vcpu * vcpu)13645 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13646 {
13647 return kvm_x86_call(interrupt_allowed)(vcpu, false);
13648 }
13649
kvm_get_linear_rip(struct kvm_vcpu * vcpu)13650 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13651 {
13652 /* Can't read the RIP when guest state is protected, just return 0 */
13653 if (vcpu->arch.guest_state_protected)
13654 return 0;
13655
13656 if (is_64_bit_mode(vcpu))
13657 return kvm_rip_read(vcpu);
13658 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13659 kvm_rip_read(vcpu));
13660 }
13661 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_linear_rip);
13662
kvm_is_linear_rip(struct kvm_vcpu * vcpu,unsigned long linear_rip)13663 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13664 {
13665 return kvm_get_linear_rip(vcpu) == linear_rip;
13666 }
13667 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_is_linear_rip);
13668
kvm_get_rflags(struct kvm_vcpu * vcpu)13669 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13670 {
13671 unsigned long rflags;
13672
13673 rflags = kvm_x86_call(get_rflags)(vcpu);
13674 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13675 rflags &= ~X86_EFLAGS_TF;
13676 return rflags;
13677 }
13678 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_rflags);
13679
__kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13680 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13681 {
13682 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13683 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13684 rflags |= X86_EFLAGS_TF;
13685 kvm_x86_call(set_rflags)(vcpu, rflags);
13686 }
13687
kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13688 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13689 {
13690 __kvm_set_rflags(vcpu, rflags);
13691 kvm_make_request(KVM_REQ_EVENT, vcpu);
13692 }
13693 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_rflags);
13694
kvm_async_pf_hash_fn(gfn_t gfn)13695 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13696 {
13697 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13698
13699 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13700 }
13701
kvm_async_pf_next_probe(u32 key)13702 static inline u32 kvm_async_pf_next_probe(u32 key)
13703 {
13704 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13705 }
13706
kvm_add_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13707 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13708 {
13709 u32 key = kvm_async_pf_hash_fn(gfn);
13710
13711 while (vcpu->arch.apf.gfns[key] != ~0)
13712 key = kvm_async_pf_next_probe(key);
13713
13714 vcpu->arch.apf.gfns[key] = gfn;
13715 }
13716
kvm_async_pf_gfn_slot(struct kvm_vcpu * vcpu,gfn_t gfn)13717 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13718 {
13719 int i;
13720 u32 key = kvm_async_pf_hash_fn(gfn);
13721
13722 for (i = 0; i < ASYNC_PF_PER_VCPU &&
13723 (vcpu->arch.apf.gfns[key] != gfn &&
13724 vcpu->arch.apf.gfns[key] != ~0); i++)
13725 key = kvm_async_pf_next_probe(key);
13726
13727 return key;
13728 }
13729
kvm_find_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13730 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13731 {
13732 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13733 }
13734
kvm_del_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13735 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13736 {
13737 u32 i, j, k;
13738
13739 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13740
13741 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13742 return;
13743
13744 while (true) {
13745 vcpu->arch.apf.gfns[i] = ~0;
13746 do {
13747 j = kvm_async_pf_next_probe(j);
13748 if (vcpu->arch.apf.gfns[j] == ~0)
13749 return;
13750 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13751 /*
13752 * k lies cyclically in ]i,j]
13753 * | i.k.j |
13754 * |....j i.k.| or |.k..j i...|
13755 */
13756 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13757 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13758 i = j;
13759 }
13760 }
13761
apf_put_user_notpresent(struct kvm_vcpu * vcpu)13762 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13763 {
13764 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13765
13766 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13767 sizeof(reason));
13768 }
13769
apf_put_user_ready(struct kvm_vcpu * vcpu,u32 token)13770 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13771 {
13772 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13773
13774 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13775 &token, offset, sizeof(token));
13776 }
13777
apf_pageready_slot_free(struct kvm_vcpu * vcpu)13778 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13779 {
13780 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13781 u32 val;
13782
13783 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13784 &val, offset, sizeof(val)))
13785 return false;
13786
13787 return !val;
13788 }
13789
kvm_can_deliver_async_pf(struct kvm_vcpu * vcpu)13790 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13791 {
13792
13793 if (!kvm_pv_async_pf_enabled(vcpu))
13794 return false;
13795
13796 if (!vcpu->arch.apf.send_always &&
13797 (vcpu->arch.guest_state_protected || !kvm_x86_call(get_cpl)(vcpu)))
13798 return false;
13799
13800 if (is_guest_mode(vcpu)) {
13801 /*
13802 * L1 needs to opt into the special #PF vmexits that are
13803 * used to deliver async page faults.
13804 */
13805 return vcpu->arch.apf.delivery_as_pf_vmexit;
13806 } else {
13807 /*
13808 * Play it safe in case the guest temporarily disables paging.
13809 * The real mode IDT in particular is unlikely to have a #PF
13810 * exception setup.
13811 */
13812 return is_paging(vcpu);
13813 }
13814 }
13815
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)13816 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13817 {
13818 if (unlikely(!lapic_in_kernel(vcpu) ||
13819 kvm_event_needs_reinjection(vcpu) ||
13820 kvm_is_exception_pending(vcpu)))
13821 return false;
13822
13823 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13824 return false;
13825
13826 /*
13827 * If interrupts are off we cannot even use an artificial
13828 * halt state.
13829 */
13830 return kvm_arch_interrupt_allowed(vcpu);
13831 }
13832
kvm_arch_async_page_not_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13833 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
13834 struct kvm_async_pf *work)
13835 {
13836 struct x86_exception fault;
13837
13838 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
13839 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
13840
13841 if (kvm_can_deliver_async_pf(vcpu) &&
13842 !apf_put_user_notpresent(vcpu)) {
13843 fault.vector = PF_VECTOR;
13844 fault.error_code_valid = true;
13845 fault.error_code = 0;
13846 fault.nested_page_fault = false;
13847 fault.address = work->arch.token;
13848 fault.async_page_fault = true;
13849 kvm_inject_page_fault(vcpu, &fault);
13850 return true;
13851 } else {
13852 /*
13853 * It is not possible to deliver a paravirtualized asynchronous
13854 * page fault, but putting the guest in an artificial halt state
13855 * can be beneficial nevertheless: if an interrupt arrives, we
13856 * can deliver it timely and perhaps the guest will schedule
13857 * another process. When the instruction that triggered a page
13858 * fault is retried, hopefully the page will be ready in the host.
13859 */
13860 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
13861 return false;
13862 }
13863 }
13864
kvm_arch_async_page_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13865 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13866 struct kvm_async_pf *work)
13867 {
13868 struct kvm_lapic_irq irq = {
13869 .delivery_mode = APIC_DM_FIXED,
13870 .vector = vcpu->arch.apf.vec
13871 };
13872
13873 if (work->wakeup_all)
13874 work->arch.token = ~0; /* broadcast wakeup */
13875 else
13876 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
13877 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
13878
13879 if ((work->wakeup_all || work->notpresent_injected) &&
13880 kvm_pv_async_pf_enabled(vcpu) &&
13881 !apf_put_user_ready(vcpu, work->arch.token)) {
13882 vcpu->arch.apf.pageready_pending = true;
13883 kvm_apic_set_irq(vcpu, &irq, NULL);
13884 }
13885
13886 vcpu->arch.apf.halted = false;
13887 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
13888 }
13889
kvm_arch_async_page_present_queued(struct kvm_vcpu * vcpu)13890 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13891 {
13892 kvm_make_request(KVM_REQ_APF_READY, vcpu);
13893 if (!vcpu->arch.apf.pageready_pending)
13894 kvm_vcpu_kick(vcpu);
13895 }
13896
kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu * vcpu)13897 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
13898 {
13899 if (!kvm_pv_async_pf_enabled(vcpu))
13900 return true;
13901 else
13902 return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
13903 }
13904
kvm_noncoherent_dma_assignment_start_or_stop(struct kvm * kvm)13905 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
13906 {
13907 /*
13908 * Non-coherent DMA assignment and de-assignment may affect whether or
13909 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
13910 * due to toggling the "ignore PAT" bit. Zap all SPTEs when the first
13911 * (or last) non-coherent device is (un)registered to so that new SPTEs
13912 * with the correct "ignore guest PAT" setting are created.
13913 *
13914 * If KVM always honors guest PAT, however, there is nothing to do.
13915 */
13916 if (kvm_check_has_quirk(kvm, KVM_X86_QUIRK_IGNORE_GUEST_PAT))
13917 kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
13918 }
13919
kvm_arch_register_noncoherent_dma(struct kvm * kvm)13920 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13921 {
13922 if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
13923 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13924 }
13925
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)13926 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13927 {
13928 if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
13929 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13930 }
13931
kvm_arch_has_noncoherent_dma(struct kvm * kvm)13932 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13933 {
13934 return atomic_read(&kvm->arch.noncoherent_dma_count);
13935 }
13936 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_arch_has_noncoherent_dma);
13937
kvm_arch_no_poll(struct kvm_vcpu * vcpu)13938 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13939 {
13940 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13941 }
13942
13943 #ifdef CONFIG_KVM_GUEST_MEMFD
13944 /*
13945 * KVM doesn't yet support mmap() on guest_memfd for VMs with private memory
13946 * (the private vs. shared tracking needs to be moved into guest_memfd).
13947 */
kvm_arch_supports_gmem_mmap(struct kvm * kvm)13948 bool kvm_arch_supports_gmem_mmap(struct kvm *kvm)
13949 {
13950 return !kvm_arch_has_private_mem(kvm);
13951 }
13952
13953 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
kvm_arch_gmem_prepare(struct kvm * kvm,gfn_t gfn,kvm_pfn_t pfn,int max_order)13954 int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
13955 {
13956 return kvm_x86_call(gmem_prepare)(kvm, pfn, gfn, max_order);
13957 }
13958 #endif
13959
13960 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
kvm_arch_gmem_invalidate(kvm_pfn_t start,kvm_pfn_t end)13961 void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
13962 {
13963 kvm_x86_call(gmem_invalidate)(start, end);
13964 }
13965 #endif
13966 #endif
13967
kvm_spec_ctrl_test_value(u64 value)13968 int kvm_spec_ctrl_test_value(u64 value)
13969 {
13970 /*
13971 * test that setting IA32_SPEC_CTRL to given value
13972 * is allowed by the host processor
13973 */
13974
13975 u64 saved_value;
13976 unsigned long flags;
13977 int ret = 0;
13978
13979 local_irq_save(flags);
13980
13981 if (rdmsrq_safe(MSR_IA32_SPEC_CTRL, &saved_value))
13982 ret = 1;
13983 else if (wrmsrq_safe(MSR_IA32_SPEC_CTRL, value))
13984 ret = 1;
13985 else
13986 wrmsrq(MSR_IA32_SPEC_CTRL, saved_value);
13987
13988 local_irq_restore(flags);
13989
13990 return ret;
13991 }
13992 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_spec_ctrl_test_value);
13993
kvm_fixup_and_inject_pf_error(struct kvm_vcpu * vcpu,gva_t gva,u16 error_code)13994 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
13995 {
13996 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
13997 struct x86_exception fault;
13998 u64 access = error_code &
13999 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
14000
14001 if (!(error_code & PFERR_PRESENT_MASK) ||
14002 mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
14003 /*
14004 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
14005 * tables probably do not match the TLB. Just proceed
14006 * with the error code that the processor gave.
14007 */
14008 fault.vector = PF_VECTOR;
14009 fault.error_code_valid = true;
14010 fault.error_code = error_code;
14011 fault.nested_page_fault = false;
14012 fault.address = gva;
14013 fault.async_page_fault = false;
14014 }
14015 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
14016 }
14017 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fixup_and_inject_pf_error);
14018
14019 /*
14020 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
14021 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
14022 * indicates whether exit to userspace is needed.
14023 */
kvm_handle_memory_failure(struct kvm_vcpu * vcpu,int r,struct x86_exception * e)14024 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
14025 struct x86_exception *e)
14026 {
14027 if (r == X86EMUL_PROPAGATE_FAULT) {
14028 if (KVM_BUG_ON(!e, vcpu->kvm))
14029 return -EIO;
14030
14031 kvm_inject_emulated_page_fault(vcpu, e);
14032 return 1;
14033 }
14034
14035 /*
14036 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
14037 * while handling a VMX instruction KVM could've handled the request
14038 * correctly by exiting to userspace and performing I/O but there
14039 * doesn't seem to be a real use-case behind such requests, just return
14040 * KVM_EXIT_INTERNAL_ERROR for now.
14041 */
14042 kvm_prepare_emulation_failure_exit(vcpu);
14043
14044 return 0;
14045 }
14046 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_memory_failure);
14047
kvm_handle_invpcid(struct kvm_vcpu * vcpu,unsigned long type,gva_t gva)14048 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
14049 {
14050 bool pcid_enabled;
14051 struct x86_exception e;
14052 struct {
14053 u64 pcid;
14054 u64 gla;
14055 } operand;
14056 int r;
14057
14058 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
14059 if (r != X86EMUL_CONTINUE)
14060 return kvm_handle_memory_failure(vcpu, r, &e);
14061
14062 if (operand.pcid >> 12 != 0) {
14063 kvm_inject_gp(vcpu, 0);
14064 return 1;
14065 }
14066
14067 pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
14068
14069 switch (type) {
14070 case INVPCID_TYPE_INDIV_ADDR:
14071 /*
14072 * LAM doesn't apply to addresses that are inputs to TLB
14073 * invalidation.
14074 */
14075 if ((!pcid_enabled && (operand.pcid != 0)) ||
14076 is_noncanonical_invlpg_address(operand.gla, vcpu)) {
14077 kvm_inject_gp(vcpu, 0);
14078 return 1;
14079 }
14080 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
14081 return kvm_skip_emulated_instruction(vcpu);
14082
14083 case INVPCID_TYPE_SINGLE_CTXT:
14084 if (!pcid_enabled && (operand.pcid != 0)) {
14085 kvm_inject_gp(vcpu, 0);
14086 return 1;
14087 }
14088
14089 kvm_invalidate_pcid(vcpu, operand.pcid);
14090 return kvm_skip_emulated_instruction(vcpu);
14091
14092 case INVPCID_TYPE_ALL_NON_GLOBAL:
14093 /*
14094 * Currently, KVM doesn't mark global entries in the shadow
14095 * page tables, so a non-global flush just degenerates to a
14096 * global flush. If needed, we could optimize this later by
14097 * keeping track of global entries in shadow page tables.
14098 */
14099
14100 fallthrough;
14101 case INVPCID_TYPE_ALL_INCL_GLOBAL:
14102 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
14103 return kvm_skip_emulated_instruction(vcpu);
14104
14105 default:
14106 kvm_inject_gp(vcpu, 0);
14107 return 1;
14108 }
14109 }
14110 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invpcid);
14111
complete_sev_es_emulated_mmio(struct kvm_vcpu * vcpu)14112 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
14113 {
14114 struct kvm_run *run = vcpu->run;
14115 struct kvm_mmio_fragment *frag;
14116 unsigned int len;
14117
14118 BUG_ON(!vcpu->mmio_needed);
14119
14120 /* Complete previous fragment */
14121 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
14122 len = min(8u, frag->len);
14123 if (!vcpu->mmio_is_write)
14124 memcpy(frag->data, run->mmio.data, len);
14125
14126 if (frag->len <= 8) {
14127 /* Switch to the next fragment. */
14128 frag++;
14129 vcpu->mmio_cur_fragment++;
14130 } else {
14131 /* Go forward to the next mmio piece. */
14132 frag->data += len;
14133 frag->gpa += len;
14134 frag->len -= len;
14135 }
14136
14137 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
14138 vcpu->mmio_needed = 0;
14139
14140 // VMG change, at this point, we're always done
14141 // RIP has already been advanced
14142 return 1;
14143 }
14144
14145 // More MMIO is needed
14146 run->mmio.phys_addr = frag->gpa;
14147 run->mmio.len = min(8u, frag->len);
14148 run->mmio.is_write = vcpu->mmio_is_write;
14149 if (run->mmio.is_write)
14150 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
14151 run->exit_reason = KVM_EXIT_MMIO;
14152
14153 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14154
14155 return 0;
14156 }
14157
kvm_sev_es_mmio_write(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)14158 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
14159 void *data)
14160 {
14161 int handled;
14162 struct kvm_mmio_fragment *frag;
14163
14164 if (!data)
14165 return -EINVAL;
14166
14167 handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
14168 if (handled == bytes)
14169 return 1;
14170
14171 bytes -= handled;
14172 gpa += handled;
14173 data += handled;
14174
14175 /*TODO: Check if need to increment number of frags */
14176 frag = vcpu->mmio_fragments;
14177 vcpu->mmio_nr_fragments = 1;
14178 frag->len = bytes;
14179 frag->gpa = gpa;
14180 frag->data = data;
14181
14182 vcpu->mmio_needed = 1;
14183 vcpu->mmio_cur_fragment = 0;
14184
14185 vcpu->run->mmio.phys_addr = gpa;
14186 vcpu->run->mmio.len = min(8u, frag->len);
14187 vcpu->run->mmio.is_write = 1;
14188 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
14189 vcpu->run->exit_reason = KVM_EXIT_MMIO;
14190
14191 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14192
14193 return 0;
14194 }
14195 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_mmio_write);
14196
kvm_sev_es_mmio_read(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)14197 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
14198 void *data)
14199 {
14200 int handled;
14201 struct kvm_mmio_fragment *frag;
14202
14203 if (!data)
14204 return -EINVAL;
14205
14206 handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
14207 if (handled == bytes)
14208 return 1;
14209
14210 bytes -= handled;
14211 gpa += handled;
14212 data += handled;
14213
14214 /*TODO: Check if need to increment number of frags */
14215 frag = vcpu->mmio_fragments;
14216 vcpu->mmio_nr_fragments = 1;
14217 frag->len = bytes;
14218 frag->gpa = gpa;
14219 frag->data = data;
14220
14221 vcpu->mmio_needed = 1;
14222 vcpu->mmio_cur_fragment = 0;
14223
14224 vcpu->run->mmio.phys_addr = gpa;
14225 vcpu->run->mmio.len = min(8u, frag->len);
14226 vcpu->run->mmio.is_write = 0;
14227 vcpu->run->exit_reason = KVM_EXIT_MMIO;
14228
14229 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14230
14231 return 0;
14232 }
14233 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_mmio_read);
14234
advance_sev_es_emulated_pio(struct kvm_vcpu * vcpu,unsigned count,int size)14235 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
14236 {
14237 vcpu->arch.sev_pio_count -= count;
14238 vcpu->arch.sev_pio_data += count * size;
14239 }
14240
14241 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14242 unsigned int port);
14243
complete_sev_es_emulated_outs(struct kvm_vcpu * vcpu)14244 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
14245 {
14246 int size = vcpu->arch.pio.size;
14247 int port = vcpu->arch.pio.port;
14248
14249 vcpu->arch.pio.count = 0;
14250 if (vcpu->arch.sev_pio_count)
14251 return kvm_sev_es_outs(vcpu, size, port);
14252 return 1;
14253 }
14254
kvm_sev_es_outs(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14255 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14256 unsigned int port)
14257 {
14258 for (;;) {
14259 unsigned int count =
14260 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14261 int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
14262
14263 /* memcpy done already by emulator_pio_out. */
14264 advance_sev_es_emulated_pio(vcpu, count, size);
14265 if (!ret)
14266 break;
14267
14268 /* Emulation done by the kernel. */
14269 if (!vcpu->arch.sev_pio_count)
14270 return 1;
14271 }
14272
14273 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
14274 return 0;
14275 }
14276
14277 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14278 unsigned int port);
14279
complete_sev_es_emulated_ins(struct kvm_vcpu * vcpu)14280 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
14281 {
14282 unsigned count = vcpu->arch.pio.count;
14283 int size = vcpu->arch.pio.size;
14284 int port = vcpu->arch.pio.port;
14285
14286 complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
14287 advance_sev_es_emulated_pio(vcpu, count, size);
14288 if (vcpu->arch.sev_pio_count)
14289 return kvm_sev_es_ins(vcpu, size, port);
14290 return 1;
14291 }
14292
kvm_sev_es_ins(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14293 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14294 unsigned int port)
14295 {
14296 for (;;) {
14297 unsigned int count =
14298 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14299 if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
14300 break;
14301
14302 /* Emulation done by the kernel. */
14303 advance_sev_es_emulated_pio(vcpu, count, size);
14304 if (!vcpu->arch.sev_pio_count)
14305 return 1;
14306 }
14307
14308 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
14309 return 0;
14310 }
14311
kvm_sev_es_string_io(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port,void * data,unsigned int count,int in)14312 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
14313 unsigned int port, void *data, unsigned int count,
14314 int in)
14315 {
14316 vcpu->arch.sev_pio_data = data;
14317 vcpu->arch.sev_pio_count = count;
14318 return in ? kvm_sev_es_ins(vcpu, size, port)
14319 : kvm_sev_es_outs(vcpu, size, port);
14320 }
14321 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_string_io);
14322
14323 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
14324 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
14325 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_mmio);
14326 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
14327 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
14328 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
14329 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
14330 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
14331 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
14332 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
14333 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
14334 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
14335 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
14336 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
14337 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
14338 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
14339 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
14340 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
14341 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
14342 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
14343 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
14344 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
14345 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
14346 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
14347 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
14348 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
14349 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
14350 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
14351 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
14352 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
14353
kvm_x86_init(void)14354 static int __init kvm_x86_init(void)
14355 {
14356 kvm_init_xstate_sizes();
14357
14358 kvm_mmu_x86_module_init();
14359 mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
14360 return 0;
14361 }
14362 module_init(kvm_x86_init);
14363
kvm_x86_exit(void)14364 static void __exit kvm_x86_exit(void)
14365 {
14366 WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
14367 }
14368 module_exit(kvm_x86_exit);
14369