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_GPL(kvm_caps);
101
102 struct kvm_host_values kvm_host __read_mostly;
103 EXPORT_SYMBOL_GPL(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 struct kvm_x86_ops kvm_x86_ops __read_mostly;
140
141 #define KVM_X86_OP(func) \
142 DEFINE_STATIC_CALL_NULL(kvm_x86_##func, \
143 *(((struct kvm_x86_ops *)0)->func));
144 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
145 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
146 #include <asm/kvm-x86-ops.h>
147 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
148 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
149
150 static bool __read_mostly ignore_msrs = 0;
151 module_param(ignore_msrs, bool, 0644);
152
153 bool __read_mostly report_ignored_msrs = true;
154 module_param(report_ignored_msrs, bool, 0644);
155 EXPORT_SYMBOL_GPL(report_ignored_msrs);
156
157 unsigned int min_timer_period_us = 200;
158 module_param(min_timer_period_us, uint, 0644);
159
160 static bool __read_mostly kvmclock_periodic_sync = true;
161 module_param(kvmclock_periodic_sync, bool, 0444);
162
163 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
164 static u32 __read_mostly tsc_tolerance_ppm = 250;
165 module_param(tsc_tolerance_ppm, uint, 0644);
166
167 static bool __read_mostly vector_hashing = true;
168 module_param(vector_hashing, bool, 0444);
169
170 bool __read_mostly enable_vmware_backdoor = false;
171 module_param(enable_vmware_backdoor, bool, 0444);
172 EXPORT_SYMBOL_GPL(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_GPL(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_GPL(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 bool __read_mostly allow_smaller_maxphyaddr = 0;
224 EXPORT_SYMBOL_GPL(allow_smaller_maxphyaddr);
225
226 bool __read_mostly enable_apicv = true;
227 EXPORT_SYMBOL_GPL(enable_apicv);
228
229 bool __read_mostly enable_device_posted_irqs = true;
230 EXPORT_SYMBOL_GPL(enable_device_posted_irqs);
231
232 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
233 KVM_GENERIC_VM_STATS(),
234 STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
235 STATS_DESC_COUNTER(VM, mmu_pte_write),
236 STATS_DESC_COUNTER(VM, mmu_pde_zapped),
237 STATS_DESC_COUNTER(VM, mmu_flooded),
238 STATS_DESC_COUNTER(VM, mmu_recycled),
239 STATS_DESC_COUNTER(VM, mmu_cache_miss),
240 STATS_DESC_ICOUNTER(VM, mmu_unsync),
241 STATS_DESC_ICOUNTER(VM, pages_4k),
242 STATS_DESC_ICOUNTER(VM, pages_2m),
243 STATS_DESC_ICOUNTER(VM, pages_1g),
244 STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
245 STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
246 STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
247 };
248
249 const struct kvm_stats_header kvm_vm_stats_header = {
250 .name_size = KVM_STATS_NAME_SIZE,
251 .num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
252 .id_offset = sizeof(struct kvm_stats_header),
253 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
254 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
255 sizeof(kvm_vm_stats_desc),
256 };
257
258 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
259 KVM_GENERIC_VCPU_STATS(),
260 STATS_DESC_COUNTER(VCPU, pf_taken),
261 STATS_DESC_COUNTER(VCPU, pf_fixed),
262 STATS_DESC_COUNTER(VCPU, pf_emulate),
263 STATS_DESC_COUNTER(VCPU, pf_spurious),
264 STATS_DESC_COUNTER(VCPU, pf_fast),
265 STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
266 STATS_DESC_COUNTER(VCPU, pf_guest),
267 STATS_DESC_COUNTER(VCPU, tlb_flush),
268 STATS_DESC_COUNTER(VCPU, invlpg),
269 STATS_DESC_COUNTER(VCPU, exits),
270 STATS_DESC_COUNTER(VCPU, io_exits),
271 STATS_DESC_COUNTER(VCPU, mmio_exits),
272 STATS_DESC_COUNTER(VCPU, signal_exits),
273 STATS_DESC_COUNTER(VCPU, irq_window_exits),
274 STATS_DESC_COUNTER(VCPU, nmi_window_exits),
275 STATS_DESC_COUNTER(VCPU, l1d_flush),
276 STATS_DESC_COUNTER(VCPU, halt_exits),
277 STATS_DESC_COUNTER(VCPU, request_irq_exits),
278 STATS_DESC_COUNTER(VCPU, irq_exits),
279 STATS_DESC_COUNTER(VCPU, host_state_reload),
280 STATS_DESC_COUNTER(VCPU, fpu_reload),
281 STATS_DESC_COUNTER(VCPU, insn_emulation),
282 STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
283 STATS_DESC_COUNTER(VCPU, hypercalls),
284 STATS_DESC_COUNTER(VCPU, irq_injections),
285 STATS_DESC_COUNTER(VCPU, nmi_injections),
286 STATS_DESC_COUNTER(VCPU, req_event),
287 STATS_DESC_COUNTER(VCPU, nested_run),
288 STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
289 STATS_DESC_COUNTER(VCPU, directed_yield_successful),
290 STATS_DESC_COUNTER(VCPU, preemption_reported),
291 STATS_DESC_COUNTER(VCPU, preemption_other),
292 STATS_DESC_IBOOLEAN(VCPU, guest_mode),
293 STATS_DESC_COUNTER(VCPU, notify_window_exits),
294 };
295
296 const struct kvm_stats_header kvm_vcpu_stats_header = {
297 .name_size = KVM_STATS_NAME_SIZE,
298 .num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
299 .id_offset = sizeof(struct kvm_stats_header),
300 .desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
301 .data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
302 sizeof(kvm_vcpu_stats_desc),
303 };
304
305 static struct kmem_cache *x86_emulator_cache;
306
307 /*
308 * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features) track
309 * the set of MSRs that KVM exposes to userspace through KVM_GET_MSRS,
310 * KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST. msrs_to_save holds MSRs that
311 * require host support, i.e. should be probed via RDMSR. emulated_msrs holds
312 * MSRs that KVM emulates without strictly requiring host support.
313 * msr_based_features holds MSRs that enumerate features, i.e. are effectively
314 * CPUID leafs. Note, msr_based_features isn't mutually exclusive with
315 * msrs_to_save and emulated_msrs.
316 */
317
318 static const u32 msrs_to_save_base[] = {
319 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
320 MSR_STAR,
321 #ifdef CONFIG_X86_64
322 MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
323 #endif
324 MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
325 MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
326 MSR_IA32_SPEC_CTRL, MSR_IA32_TSX_CTRL,
327 MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
328 MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
329 MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
330 MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
331 MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
332 MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
333 MSR_IA32_UMWAIT_CONTROL,
334
335 MSR_IA32_XFD, MSR_IA32_XFD_ERR,
336 };
337
338 static const u32 msrs_to_save_pmu[] = {
339 MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
340 MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
341 MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
342 MSR_CORE_PERF_GLOBAL_CTRL,
343 MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
344
345 /* This part of MSRs should match KVM_MAX_NR_INTEL_GP_COUNTERS. */
346 MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
347 MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
348 MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
349 MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
350 MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
351 MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
352 MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
353 MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
354
355 MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
356 MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
357
358 /* This part of MSRs should match KVM_MAX_NR_AMD_GP_COUNTERS. */
359 MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
360 MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
361 MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
362 MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
363
364 MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
365 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
366 MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
367 };
368
369 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_base) +
370 ARRAY_SIZE(msrs_to_save_pmu)];
371 static unsigned num_msrs_to_save;
372
373 static const u32 emulated_msrs_all[] = {
374 MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
375 MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
376
377 #ifdef CONFIG_KVM_HYPERV
378 HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
379 HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
380 HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
381 HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
382 HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
383 HV_X64_MSR_RESET,
384 HV_X64_MSR_VP_INDEX,
385 HV_X64_MSR_VP_RUNTIME,
386 HV_X64_MSR_SCONTROL,
387 HV_X64_MSR_STIMER0_CONFIG,
388 HV_X64_MSR_VP_ASSIST_PAGE,
389 HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
390 HV_X64_MSR_TSC_EMULATION_STATUS, HV_X64_MSR_TSC_INVARIANT_CONTROL,
391 HV_X64_MSR_SYNDBG_OPTIONS,
392 HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
393 HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
394 HV_X64_MSR_SYNDBG_PENDING_BUFFER,
395 #endif
396
397 MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
398 MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
399
400 MSR_IA32_TSC_ADJUST,
401 MSR_IA32_TSC_DEADLINE,
402 MSR_IA32_ARCH_CAPABILITIES,
403 MSR_IA32_PERF_CAPABILITIES,
404 MSR_IA32_MISC_ENABLE,
405 MSR_IA32_MCG_STATUS,
406 MSR_IA32_MCG_CTL,
407 MSR_IA32_MCG_EXT_CTL,
408 MSR_IA32_SMBASE,
409 MSR_SMI_COUNT,
410 MSR_PLATFORM_INFO,
411 MSR_MISC_FEATURES_ENABLES,
412 MSR_AMD64_VIRT_SPEC_CTRL,
413 MSR_AMD64_TSC_RATIO,
414 MSR_IA32_POWER_CTL,
415 MSR_IA32_UCODE_REV,
416
417 /*
418 * KVM always supports the "true" VMX control MSRs, even if the host
419 * does not. The VMX MSRs as a whole are considered "emulated" as KVM
420 * doesn't strictly require them to exist in the host (ignoring that
421 * KVM would refuse to load in the first place if the core set of MSRs
422 * aren't supported).
423 */
424 MSR_IA32_VMX_BASIC,
425 MSR_IA32_VMX_TRUE_PINBASED_CTLS,
426 MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
427 MSR_IA32_VMX_TRUE_EXIT_CTLS,
428 MSR_IA32_VMX_TRUE_ENTRY_CTLS,
429 MSR_IA32_VMX_MISC,
430 MSR_IA32_VMX_CR0_FIXED0,
431 MSR_IA32_VMX_CR4_FIXED0,
432 MSR_IA32_VMX_VMCS_ENUM,
433 MSR_IA32_VMX_PROCBASED_CTLS2,
434 MSR_IA32_VMX_EPT_VPID_CAP,
435 MSR_IA32_VMX_VMFUNC,
436
437 MSR_K7_HWCR,
438 MSR_KVM_POLL_CONTROL,
439 };
440
441 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
442 static unsigned num_emulated_msrs;
443
444 /*
445 * List of MSRs that control the existence of MSR-based features, i.e. MSRs
446 * that are effectively CPUID leafs. VMX MSRs are also included in the set of
447 * feature MSRs, but are handled separately to allow expedited lookups.
448 */
449 static const u32 msr_based_features_all_except_vmx[] = {
450 MSR_AMD64_DE_CFG,
451 MSR_IA32_UCODE_REV,
452 MSR_IA32_ARCH_CAPABILITIES,
453 MSR_IA32_PERF_CAPABILITIES,
454 MSR_PLATFORM_INFO,
455 };
456
457 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all_except_vmx) +
458 (KVM_LAST_EMULATED_VMX_MSR - KVM_FIRST_EMULATED_VMX_MSR + 1)];
459 static unsigned int num_msr_based_features;
460
461 /*
462 * All feature MSRs except uCode revID, which tracks the currently loaded uCode
463 * patch, are immutable once the vCPU model is defined.
464 */
kvm_is_immutable_feature_msr(u32 msr)465 static bool kvm_is_immutable_feature_msr(u32 msr)
466 {
467 int i;
468
469 if (msr >= KVM_FIRST_EMULATED_VMX_MSR && msr <= KVM_LAST_EMULATED_VMX_MSR)
470 return true;
471
472 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++) {
473 if (msr == msr_based_features_all_except_vmx[i])
474 return msr != MSR_IA32_UCODE_REV;
475 }
476
477 return false;
478 }
479
kvm_is_advertised_msr(u32 msr_index)480 static bool kvm_is_advertised_msr(u32 msr_index)
481 {
482 unsigned int i;
483
484 for (i = 0; i < num_msrs_to_save; i++) {
485 if (msrs_to_save[i] == msr_index)
486 return true;
487 }
488
489 for (i = 0; i < num_emulated_msrs; i++) {
490 if (emulated_msrs[i] == msr_index)
491 return true;
492 }
493
494 return false;
495 }
496
497 typedef int (*msr_access_t)(struct kvm_vcpu *vcpu, u32 index, u64 *data,
498 bool host_initiated);
499
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)500 static __always_inline int kvm_do_msr_access(struct kvm_vcpu *vcpu, u32 msr,
501 u64 *data, bool host_initiated,
502 enum kvm_msr_access rw,
503 msr_access_t msr_access_fn)
504 {
505 const char *op = rw == MSR_TYPE_W ? "wrmsr" : "rdmsr";
506 int ret;
507
508 BUILD_BUG_ON(rw != MSR_TYPE_R && rw != MSR_TYPE_W);
509
510 /*
511 * Zero the data on read failures to avoid leaking stack data to the
512 * guest and/or userspace, e.g. if the failure is ignored below.
513 */
514 ret = msr_access_fn(vcpu, msr, data, host_initiated);
515 if (ret && rw == MSR_TYPE_R)
516 *data = 0;
517
518 if (ret != KVM_MSR_RET_UNSUPPORTED)
519 return ret;
520
521 /*
522 * Userspace is allowed to read MSRs, and write '0' to MSRs, that KVM
523 * advertises to userspace, even if an MSR isn't fully supported.
524 * Simply check that @data is '0', which covers both the write '0' case
525 * and all reads (in which case @data is zeroed on failure; see above).
526 */
527 if (host_initiated && !*data && kvm_is_advertised_msr(msr))
528 return 0;
529
530 if (!ignore_msrs) {
531 kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
532 op, msr, *data);
533 return ret;
534 }
535
536 if (report_ignored_msrs)
537 kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n", op, msr, *data);
538
539 return 0;
540 }
541
kvm_alloc_emulator_cache(void)542 static struct kmem_cache *kvm_alloc_emulator_cache(void)
543 {
544 unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
545 unsigned int size = sizeof(struct x86_emulate_ctxt);
546
547 return kmem_cache_create_usercopy("x86_emulator", size,
548 __alignof__(struct x86_emulate_ctxt),
549 SLAB_ACCOUNT, useroffset,
550 size - useroffset, NULL);
551 }
552
553 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
554
kvm_async_pf_hash_reset(struct kvm_vcpu * vcpu)555 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
556 {
557 int i;
558 for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
559 vcpu->arch.apf.gfns[i] = ~0;
560 }
561
kvm_on_user_return(struct user_return_notifier * urn)562 static void kvm_on_user_return(struct user_return_notifier *urn)
563 {
564 unsigned slot;
565 struct kvm_user_return_msrs *msrs
566 = container_of(urn, struct kvm_user_return_msrs, urn);
567 struct kvm_user_return_msr_values *values;
568 unsigned long flags;
569
570 /*
571 * Disabling irqs at this point since the following code could be
572 * interrupted and executed through kvm_arch_disable_virtualization_cpu()
573 */
574 local_irq_save(flags);
575 if (msrs->registered) {
576 msrs->registered = false;
577 user_return_notifier_unregister(urn);
578 }
579 local_irq_restore(flags);
580 for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
581 values = &msrs->values[slot];
582 if (values->host != values->curr) {
583 wrmsrq(kvm_uret_msrs_list[slot], values->host);
584 values->curr = values->host;
585 }
586 }
587 }
588
kvm_probe_user_return_msr(u32 msr)589 static int kvm_probe_user_return_msr(u32 msr)
590 {
591 u64 val;
592 int ret;
593
594 preempt_disable();
595 ret = rdmsrq_safe(msr, &val);
596 if (ret)
597 goto out;
598 ret = wrmsrq_safe(msr, val);
599 out:
600 preempt_enable();
601 return ret;
602 }
603
kvm_add_user_return_msr(u32 msr)604 int kvm_add_user_return_msr(u32 msr)
605 {
606 BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
607
608 if (kvm_probe_user_return_msr(msr))
609 return -1;
610
611 kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
612 return kvm_nr_uret_msrs++;
613 }
614 EXPORT_SYMBOL_GPL(kvm_add_user_return_msr);
615
kvm_find_user_return_msr(u32 msr)616 int kvm_find_user_return_msr(u32 msr)
617 {
618 int i;
619
620 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
621 if (kvm_uret_msrs_list[i] == msr)
622 return i;
623 }
624 return -1;
625 }
626 EXPORT_SYMBOL_GPL(kvm_find_user_return_msr);
627
kvm_user_return_msr_cpu_online(void)628 static void kvm_user_return_msr_cpu_online(void)
629 {
630 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
631 u64 value;
632 int i;
633
634 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
635 rdmsrq_safe(kvm_uret_msrs_list[i], &value);
636 msrs->values[i].host = value;
637 msrs->values[i].curr = value;
638 }
639 }
640
kvm_user_return_register_notifier(struct kvm_user_return_msrs * msrs)641 static void kvm_user_return_register_notifier(struct kvm_user_return_msrs *msrs)
642 {
643 if (!msrs->registered) {
644 msrs->urn.on_user_return = kvm_on_user_return;
645 user_return_notifier_register(&msrs->urn);
646 msrs->registered = true;
647 }
648 }
649
kvm_set_user_return_msr(unsigned slot,u64 value,u64 mask)650 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
651 {
652 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
653 int err;
654
655 value = (value & mask) | (msrs->values[slot].host & ~mask);
656 if (value == msrs->values[slot].curr)
657 return 0;
658 err = wrmsrq_safe(kvm_uret_msrs_list[slot], value);
659 if (err)
660 return 1;
661
662 msrs->values[slot].curr = value;
663 kvm_user_return_register_notifier(msrs);
664 return 0;
665 }
666 EXPORT_SYMBOL_GPL(kvm_set_user_return_msr);
667
kvm_user_return_msr_update_cache(unsigned int slot,u64 value)668 void kvm_user_return_msr_update_cache(unsigned int slot, u64 value)
669 {
670 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
671
672 msrs->values[slot].curr = value;
673 kvm_user_return_register_notifier(msrs);
674 }
675 EXPORT_SYMBOL_GPL(kvm_user_return_msr_update_cache);
676
drop_user_return_notifiers(void)677 static void drop_user_return_notifiers(void)
678 {
679 struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
680
681 if (msrs->registered)
682 kvm_on_user_return(&msrs->urn);
683 }
684
685 /*
686 * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
687 *
688 * Hardware virtualization extension instructions may fault if a reboot turns
689 * off virtualization while processes are running. Usually after catching the
690 * fault we just panic; during reboot instead the instruction is ignored.
691 */
kvm_spurious_fault(void)692 noinstr void kvm_spurious_fault(void)
693 {
694 /* Fault while not rebooting. We want the trace. */
695 BUG_ON(!kvm_rebooting);
696 }
697 EXPORT_SYMBOL_GPL(kvm_spurious_fault);
698
699 #define EXCPT_BENIGN 0
700 #define EXCPT_CONTRIBUTORY 1
701 #define EXCPT_PF 2
702
exception_class(int vector)703 static int exception_class(int vector)
704 {
705 switch (vector) {
706 case PF_VECTOR:
707 return EXCPT_PF;
708 case DE_VECTOR:
709 case TS_VECTOR:
710 case NP_VECTOR:
711 case SS_VECTOR:
712 case GP_VECTOR:
713 return EXCPT_CONTRIBUTORY;
714 default:
715 break;
716 }
717 return EXCPT_BENIGN;
718 }
719
720 #define EXCPT_FAULT 0
721 #define EXCPT_TRAP 1
722 #define EXCPT_ABORT 2
723 #define EXCPT_INTERRUPT 3
724 #define EXCPT_DB 4
725
exception_type(int vector)726 static int exception_type(int vector)
727 {
728 unsigned int mask;
729
730 if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
731 return EXCPT_INTERRUPT;
732
733 mask = 1 << vector;
734
735 /*
736 * #DBs can be trap-like or fault-like, the caller must check other CPU
737 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
738 */
739 if (mask & (1 << DB_VECTOR))
740 return EXCPT_DB;
741
742 if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
743 return EXCPT_TRAP;
744
745 if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
746 return EXCPT_ABORT;
747
748 /* Reserved exceptions will result in fault */
749 return EXCPT_FAULT;
750 }
751
kvm_deliver_exception_payload(struct kvm_vcpu * vcpu,struct kvm_queued_exception * ex)752 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
753 struct kvm_queued_exception *ex)
754 {
755 if (!ex->has_payload)
756 return;
757
758 switch (ex->vector) {
759 case DB_VECTOR:
760 /*
761 * "Certain debug exceptions may clear bit 0-3. The
762 * remaining contents of the DR6 register are never
763 * cleared by the processor".
764 */
765 vcpu->arch.dr6 &= ~DR_TRAP_BITS;
766 /*
767 * In order to reflect the #DB exception payload in guest
768 * dr6, three components need to be considered: active low
769 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
770 * DR6_BS and DR6_BT)
771 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
772 * In the target guest dr6:
773 * FIXED_1 bits should always be set.
774 * Active low bits should be cleared if 1-setting in payload.
775 * Active high bits should be set if 1-setting in payload.
776 *
777 * Note, the payload is compatible with the pending debug
778 * exceptions/exit qualification under VMX, that active_low bits
779 * are active high in payload.
780 * So they need to be flipped for DR6.
781 */
782 vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
783 vcpu->arch.dr6 |= ex->payload;
784 vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
785
786 /*
787 * The #DB payload is defined as compatible with the 'pending
788 * debug exceptions' field under VMX, not DR6. While bit 12 is
789 * defined in the 'pending debug exceptions' field (enabled
790 * breakpoint), it is reserved and must be zero in DR6.
791 */
792 vcpu->arch.dr6 &= ~BIT(12);
793 break;
794 case PF_VECTOR:
795 vcpu->arch.cr2 = ex->payload;
796 break;
797 }
798
799 ex->has_payload = false;
800 ex->payload = 0;
801 }
802 EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
803
kvm_queue_exception_vmexit(struct kvm_vcpu * vcpu,unsigned int vector,bool has_error_code,u32 error_code,bool has_payload,unsigned long payload)804 static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
805 bool has_error_code, u32 error_code,
806 bool has_payload, unsigned long payload)
807 {
808 struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
809
810 ex->vector = vector;
811 ex->injected = false;
812 ex->pending = true;
813 ex->has_error_code = has_error_code;
814 ex->error_code = error_code;
815 ex->has_payload = has_payload;
816 ex->payload = payload;
817 }
818
kvm_multiple_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error,u32 error_code,bool has_payload,unsigned long payload)819 static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
820 bool has_error, u32 error_code,
821 bool has_payload, unsigned long payload)
822 {
823 u32 prev_nr;
824 int class1, class2;
825
826 kvm_make_request(KVM_REQ_EVENT, vcpu);
827
828 /*
829 * If the exception is destined for L2, morph it to a VM-Exit if L1
830 * wants to intercept the exception.
831 */
832 if (is_guest_mode(vcpu) &&
833 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
834 kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
835 has_payload, payload);
836 return;
837 }
838
839 if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
840 queue:
841 vcpu->arch.exception.pending = true;
842 vcpu->arch.exception.injected = false;
843
844 vcpu->arch.exception.has_error_code = has_error;
845 vcpu->arch.exception.vector = nr;
846 vcpu->arch.exception.error_code = error_code;
847 vcpu->arch.exception.has_payload = has_payload;
848 vcpu->arch.exception.payload = payload;
849 if (!is_guest_mode(vcpu))
850 kvm_deliver_exception_payload(vcpu,
851 &vcpu->arch.exception);
852 return;
853 }
854
855 /* to check exception */
856 prev_nr = vcpu->arch.exception.vector;
857 if (prev_nr == DF_VECTOR) {
858 /* triple fault -> shutdown */
859 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
860 return;
861 }
862 class1 = exception_class(prev_nr);
863 class2 = exception_class(nr);
864 if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
865 (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
866 /*
867 * Synthesize #DF. Clear the previously injected or pending
868 * exception so as not to incorrectly trigger shutdown.
869 */
870 vcpu->arch.exception.injected = false;
871 vcpu->arch.exception.pending = false;
872
873 kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
874 } else {
875 /* replace previous exception with a new one in a hope
876 that instruction re-execution will regenerate lost
877 exception */
878 goto queue;
879 }
880 }
881
kvm_queue_exception(struct kvm_vcpu * vcpu,unsigned nr)882 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
883 {
884 kvm_multiple_exception(vcpu, nr, false, 0, false, 0);
885 }
886 EXPORT_SYMBOL_GPL(kvm_queue_exception);
887
888
kvm_queue_exception_p(struct kvm_vcpu * vcpu,unsigned nr,unsigned long payload)889 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
890 unsigned long payload)
891 {
892 kvm_multiple_exception(vcpu, nr, false, 0, true, payload);
893 }
894 EXPORT_SYMBOL_GPL(kvm_queue_exception_p);
895
kvm_queue_exception_e_p(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code,unsigned long payload)896 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
897 u32 error_code, unsigned long payload)
898 {
899 kvm_multiple_exception(vcpu, nr, true, error_code, true, payload);
900 }
901
kvm_requeue_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error_code,u32 error_code)902 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
903 bool has_error_code, u32 error_code)
904 {
905
906 /*
907 * On VM-Entry, an exception can be pending if and only if event
908 * injection was blocked by nested_run_pending. In that case, however,
909 * vcpu_enter_guest() requests an immediate exit, and the guest
910 * shouldn't proceed far enough to need reinjection.
911 */
912 WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
913
914 /*
915 * Do not check for interception when injecting an event for L2, as the
916 * exception was checked for intercept when it was original queued, and
917 * re-checking is incorrect if _L1_ injected the exception, in which
918 * case it's exempt from interception.
919 */
920 kvm_make_request(KVM_REQ_EVENT, vcpu);
921
922 vcpu->arch.exception.injected = true;
923 vcpu->arch.exception.has_error_code = has_error_code;
924 vcpu->arch.exception.vector = nr;
925 vcpu->arch.exception.error_code = error_code;
926 vcpu->arch.exception.has_payload = false;
927 vcpu->arch.exception.payload = 0;
928 }
929 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
930
kvm_complete_insn_gp(struct kvm_vcpu * vcpu,int err)931 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
932 {
933 if (err)
934 kvm_inject_gp(vcpu, 0);
935 else
936 return kvm_skip_emulated_instruction(vcpu);
937
938 return 1;
939 }
940 EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
941
complete_emulated_insn_gp(struct kvm_vcpu * vcpu,int err)942 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
943 {
944 if (err) {
945 kvm_inject_gp(vcpu, 0);
946 return 1;
947 }
948
949 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
950 EMULTYPE_COMPLETE_USER_EXIT);
951 }
952
kvm_inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)953 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
954 {
955 ++vcpu->stat.pf_guest;
956
957 /*
958 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
959 * whether or not L1 wants to intercept "regular" #PF.
960 */
961 if (is_guest_mode(vcpu) && fault->async_page_fault)
962 kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
963 true, fault->error_code,
964 true, fault->address);
965 else
966 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
967 fault->address);
968 }
969
kvm_inject_emulated_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)970 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
971 struct x86_exception *fault)
972 {
973 struct kvm_mmu *fault_mmu;
974 WARN_ON_ONCE(fault->vector != PF_VECTOR);
975
976 fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
977 vcpu->arch.walk_mmu;
978
979 /*
980 * Invalidate the TLB entry for the faulting address, if it exists,
981 * else the access will fault indefinitely (and to emulate hardware).
982 */
983 if ((fault->error_code & PFERR_PRESENT_MASK) &&
984 !(fault->error_code & PFERR_RSVD_MASK))
985 kvm_mmu_invalidate_addr(vcpu, fault_mmu, fault->address,
986 KVM_MMU_ROOT_CURRENT);
987
988 fault_mmu->inject_page_fault(vcpu, fault);
989 }
990 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);
991
kvm_inject_nmi(struct kvm_vcpu * vcpu)992 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
993 {
994 atomic_inc(&vcpu->arch.nmi_queued);
995 kvm_make_request(KVM_REQ_NMI, vcpu);
996 }
997
kvm_queue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)998 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
999 {
1000 kvm_multiple_exception(vcpu, nr, true, error_code, false, 0);
1001 }
1002 EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
1003
1004 /*
1005 * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
1006 * a #GP and return false.
1007 */
kvm_require_cpl(struct kvm_vcpu * vcpu,int required_cpl)1008 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
1009 {
1010 if (kvm_x86_call(get_cpl)(vcpu) <= required_cpl)
1011 return true;
1012 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
1013 return false;
1014 }
1015
kvm_require_dr(struct kvm_vcpu * vcpu,int dr)1016 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
1017 {
1018 if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
1019 return true;
1020
1021 kvm_queue_exception(vcpu, UD_VECTOR);
1022 return false;
1023 }
1024 EXPORT_SYMBOL_GPL(kvm_require_dr);
1025
pdptr_rsvd_bits(struct kvm_vcpu * vcpu)1026 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
1027 {
1028 return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
1029 }
1030
1031 /*
1032 * Load the pae pdptrs. Return 1 if they are all valid, 0 otherwise.
1033 */
load_pdptrs(struct kvm_vcpu * vcpu,unsigned long cr3)1034 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
1035 {
1036 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
1037 gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
1038 gpa_t real_gpa;
1039 int i;
1040 int ret;
1041 u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
1042
1043 /*
1044 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
1045 * to an L1 GPA.
1046 */
1047 real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
1048 PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
1049 if (real_gpa == INVALID_GPA)
1050 return 0;
1051
1052 /* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
1053 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
1054 cr3 & GENMASK(11, 5), sizeof(pdpte));
1055 if (ret < 0)
1056 return 0;
1057
1058 for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
1059 if ((pdpte[i] & PT_PRESENT_MASK) &&
1060 (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
1061 return 0;
1062 }
1063 }
1064
1065 /*
1066 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
1067 * Shadow page roots need to be reconstructed instead.
1068 */
1069 if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
1070 kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
1071
1072 memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
1073 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
1074 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
1075 vcpu->arch.pdptrs_from_userspace = false;
1076
1077 return 1;
1078 }
1079 EXPORT_SYMBOL_GPL(load_pdptrs);
1080
kvm_is_valid_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1081 static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1082 {
1083 #ifdef CONFIG_X86_64
1084 if (cr0 & 0xffffffff00000000UL)
1085 return false;
1086 #endif
1087
1088 if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
1089 return false;
1090
1091 if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
1092 return false;
1093
1094 return kvm_x86_call(is_valid_cr0)(vcpu, cr0);
1095 }
1096
kvm_post_set_cr0(struct kvm_vcpu * vcpu,unsigned long old_cr0,unsigned long cr0)1097 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
1098 {
1099 /*
1100 * CR0.WP is incorporated into the MMU role, but only for non-nested,
1101 * indirect shadow MMUs. If paging is disabled, no updates are needed
1102 * as there are no permission bits to emulate. If TDP is enabled, the
1103 * MMU's metadata needs to be updated, e.g. so that emulating guest
1104 * translations does the right thing, but there's no need to unload the
1105 * root as CR0.WP doesn't affect SPTEs.
1106 */
1107 if ((cr0 ^ old_cr0) == X86_CR0_WP) {
1108 if (!(cr0 & X86_CR0_PG))
1109 return;
1110
1111 if (tdp_enabled) {
1112 kvm_init_mmu(vcpu);
1113 return;
1114 }
1115 }
1116
1117 if ((cr0 ^ old_cr0) & X86_CR0_PG) {
1118 kvm_clear_async_pf_completion_queue(vcpu);
1119 kvm_async_pf_hash_reset(vcpu);
1120
1121 /*
1122 * Clearing CR0.PG is defined to flush the TLB from the guest's
1123 * perspective.
1124 */
1125 if (!(cr0 & X86_CR0_PG))
1126 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1127 }
1128
1129 if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
1130 kvm_mmu_reset_context(vcpu);
1131 }
1132 EXPORT_SYMBOL_GPL(kvm_post_set_cr0);
1133
kvm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1134 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1135 {
1136 unsigned long old_cr0 = kvm_read_cr0(vcpu);
1137
1138 if (!kvm_is_valid_cr0(vcpu, cr0))
1139 return 1;
1140
1141 cr0 |= X86_CR0_ET;
1142
1143 /* Write to CR0 reserved bits are ignored, even on Intel. */
1144 cr0 &= ~CR0_RESERVED_BITS;
1145
1146 #ifdef CONFIG_X86_64
1147 if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
1148 (cr0 & X86_CR0_PG)) {
1149 int cs_db, cs_l;
1150
1151 if (!is_pae(vcpu))
1152 return 1;
1153 kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
1154 if (cs_l)
1155 return 1;
1156 }
1157 #endif
1158 if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
1159 is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
1160 !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1161 return 1;
1162
1163 if (!(cr0 & X86_CR0_PG) &&
1164 (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
1165 return 1;
1166
1167 kvm_x86_call(set_cr0)(vcpu, cr0);
1168
1169 kvm_post_set_cr0(vcpu, old_cr0, cr0);
1170
1171 return 0;
1172 }
1173 EXPORT_SYMBOL_GPL(kvm_set_cr0);
1174
kvm_lmsw(struct kvm_vcpu * vcpu,unsigned long msw)1175 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
1176 {
1177 (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
1178 }
1179 EXPORT_SYMBOL_GPL(kvm_lmsw);
1180
kvm_load_guest_xsave_state(struct kvm_vcpu * vcpu)1181 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
1182 {
1183 if (vcpu->arch.guest_state_protected)
1184 return;
1185
1186 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1187
1188 if (vcpu->arch.xcr0 != kvm_host.xcr0)
1189 xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
1190
1191 if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1192 vcpu->arch.ia32_xss != kvm_host.xss)
1193 wrmsrq(MSR_IA32_XSS, vcpu->arch.ia32_xss);
1194 }
1195
1196 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1197 vcpu->arch.pkru != vcpu->arch.host_pkru &&
1198 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1199 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
1200 wrpkru(vcpu->arch.pkru);
1201 }
1202 EXPORT_SYMBOL_GPL(kvm_load_guest_xsave_state);
1203
kvm_load_host_xsave_state(struct kvm_vcpu * vcpu)1204 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
1205 {
1206 if (vcpu->arch.guest_state_protected)
1207 return;
1208
1209 if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1210 ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1211 kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
1212 vcpu->arch.pkru = rdpkru();
1213 if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1214 wrpkru(vcpu->arch.host_pkru);
1215 }
1216
1217 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1218
1219 if (vcpu->arch.xcr0 != kvm_host.xcr0)
1220 xsetbv(XCR_XFEATURE_ENABLED_MASK, kvm_host.xcr0);
1221
1222 if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1223 vcpu->arch.ia32_xss != kvm_host.xss)
1224 wrmsrq(MSR_IA32_XSS, kvm_host.xss);
1225 }
1226
1227 }
1228 EXPORT_SYMBOL_GPL(kvm_load_host_xsave_state);
1229
1230 #ifdef CONFIG_X86_64
kvm_guest_supported_xfd(struct kvm_vcpu * vcpu)1231 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1232 {
1233 return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
1234 }
1235 #endif
1236
__kvm_set_xcr(struct kvm_vcpu * vcpu,u32 index,u64 xcr)1237 static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1238 {
1239 u64 xcr0 = xcr;
1240 u64 old_xcr0 = vcpu->arch.xcr0;
1241 u64 valid_bits;
1242
1243 /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
1244 if (index != XCR_XFEATURE_ENABLED_MASK)
1245 return 1;
1246 if (!(xcr0 & XFEATURE_MASK_FP))
1247 return 1;
1248 if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1249 return 1;
1250
1251 /*
1252 * Do not allow the guest to set bits that we do not support
1253 * saving. However, xcr0 bit 0 is always set, even if the
1254 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1255 */
1256 valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
1257 if (xcr0 & ~valid_bits)
1258 return 1;
1259
1260 if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1261 (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1262 return 1;
1263
1264 if (xcr0 & XFEATURE_MASK_AVX512) {
1265 if (!(xcr0 & XFEATURE_MASK_YMM))
1266 return 1;
1267 if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1268 return 1;
1269 }
1270
1271 if ((xcr0 & XFEATURE_MASK_XTILE) &&
1272 ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1273 return 1;
1274
1275 vcpu->arch.xcr0 = xcr0;
1276
1277 if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1278 vcpu->arch.cpuid_dynamic_bits_dirty = true;
1279 return 0;
1280 }
1281
kvm_emulate_xsetbv(struct kvm_vcpu * vcpu)1282 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1283 {
1284 /* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
1285 if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
1286 __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1287 kvm_inject_gp(vcpu, 0);
1288 return 1;
1289 }
1290
1291 return kvm_skip_emulated_instruction(vcpu);
1292 }
1293 EXPORT_SYMBOL_GPL(kvm_emulate_xsetbv);
1294
kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1295 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1296 {
1297 return __kvm_is_valid_cr4(vcpu, cr4) &&
1298 kvm_x86_call(is_valid_cr4)(vcpu, cr4);
1299 }
1300
kvm_post_set_cr4(struct kvm_vcpu * vcpu,unsigned long old_cr4,unsigned long cr4)1301 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1302 {
1303 if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1304 kvm_mmu_reset_context(vcpu);
1305
1306 /*
1307 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1308 * according to the SDM; however, stale prev_roots could be reused
1309 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1310 * free them all. This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1311 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1312 * so fall through.
1313 */
1314 if (!tdp_enabled &&
1315 (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1316 kvm_mmu_unload(vcpu);
1317
1318 /*
1319 * The TLB has to be flushed for all PCIDs if any of the following
1320 * (architecturally required) changes happen:
1321 * - CR4.PCIDE is changed from 1 to 0
1322 * - CR4.PGE is toggled
1323 *
1324 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1325 */
1326 if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1327 (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1328 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1329
1330 /*
1331 * The TLB has to be flushed for the current PCID if any of the
1332 * following (architecturally required) changes happen:
1333 * - CR4.SMEP is changed from 0 to 1
1334 * - CR4.PAE is toggled
1335 */
1336 else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1337 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1338 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1339
1340 }
1341 EXPORT_SYMBOL_GPL(kvm_post_set_cr4);
1342
kvm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1343 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1344 {
1345 unsigned long old_cr4 = kvm_read_cr4(vcpu);
1346
1347 if (!kvm_is_valid_cr4(vcpu, cr4))
1348 return 1;
1349
1350 if (is_long_mode(vcpu)) {
1351 if (!(cr4 & X86_CR4_PAE))
1352 return 1;
1353 if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1354 return 1;
1355 } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1356 && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1357 && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1358 return 1;
1359
1360 if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1361 /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1362 if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1363 return 1;
1364 }
1365
1366 kvm_x86_call(set_cr4)(vcpu, cr4);
1367
1368 kvm_post_set_cr4(vcpu, old_cr4, cr4);
1369
1370 return 0;
1371 }
1372 EXPORT_SYMBOL_GPL(kvm_set_cr4);
1373
kvm_invalidate_pcid(struct kvm_vcpu * vcpu,unsigned long pcid)1374 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1375 {
1376 struct kvm_mmu *mmu = vcpu->arch.mmu;
1377 unsigned long roots_to_free = 0;
1378 int i;
1379
1380 /*
1381 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1382 * this is reachable when running EPT=1 and unrestricted_guest=0, and
1383 * also via the emulator. KVM's TDP page tables are not in the scope of
1384 * the invalidation, but the guest's TLB entries need to be flushed as
1385 * the CPU may have cached entries in its TLB for the target PCID.
1386 */
1387 if (unlikely(tdp_enabled)) {
1388 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1389 return;
1390 }
1391
1392 /*
1393 * If neither the current CR3 nor any of the prev_roots use the given
1394 * PCID, then nothing needs to be done here because a resync will
1395 * happen anyway before switching to any other CR3.
1396 */
1397 if (kvm_get_active_pcid(vcpu) == pcid) {
1398 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1399 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1400 }
1401
1402 /*
1403 * If PCID is disabled, there is no need to free prev_roots even if the
1404 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1405 * with PCIDE=0.
1406 */
1407 if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
1408 return;
1409
1410 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1411 if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1412 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1413
1414 kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1415 }
1416
kvm_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)1417 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1418 {
1419 bool skip_tlb_flush = false;
1420 unsigned long pcid = 0;
1421 #ifdef CONFIG_X86_64
1422 if (kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)) {
1423 skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1424 cr3 &= ~X86_CR3_PCID_NOFLUSH;
1425 pcid = cr3 & X86_CR3_PCID_MASK;
1426 }
1427 #endif
1428
1429 /* PDPTRs are always reloaded for PAE paging. */
1430 if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1431 goto handle_tlb_flush;
1432
1433 /*
1434 * Do not condition the GPA check on long mode, this helper is used to
1435 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1436 * the current vCPU mode is accurate.
1437 */
1438 if (!kvm_vcpu_is_legal_cr3(vcpu, cr3))
1439 return 1;
1440
1441 if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1442 return 1;
1443
1444 if (cr3 != kvm_read_cr3(vcpu))
1445 kvm_mmu_new_pgd(vcpu, cr3);
1446
1447 vcpu->arch.cr3 = cr3;
1448 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1449 /* Do not call post_set_cr3, we do not get here for confidential guests. */
1450
1451 handle_tlb_flush:
1452 /*
1453 * A load of CR3 that flushes the TLB flushes only the current PCID,
1454 * even if PCID is disabled, in which case PCID=0 is flushed. It's a
1455 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1456 * and it's impossible to use a non-zero PCID when PCID is disabled,
1457 * i.e. only PCID=0 can be relevant.
1458 */
1459 if (!skip_tlb_flush)
1460 kvm_invalidate_pcid(vcpu, pcid);
1461
1462 return 0;
1463 }
1464 EXPORT_SYMBOL_GPL(kvm_set_cr3);
1465
kvm_set_cr8(struct kvm_vcpu * vcpu,unsigned long cr8)1466 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1467 {
1468 if (cr8 & CR8_RESERVED_BITS)
1469 return 1;
1470 if (lapic_in_kernel(vcpu))
1471 kvm_lapic_set_tpr(vcpu, cr8);
1472 else
1473 vcpu->arch.cr8 = cr8;
1474 return 0;
1475 }
1476 EXPORT_SYMBOL_GPL(kvm_set_cr8);
1477
kvm_get_cr8(struct kvm_vcpu * vcpu)1478 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1479 {
1480 if (lapic_in_kernel(vcpu))
1481 return kvm_lapic_get_cr8(vcpu);
1482 else
1483 return vcpu->arch.cr8;
1484 }
1485 EXPORT_SYMBOL_GPL(kvm_get_cr8);
1486
kvm_update_dr0123(struct kvm_vcpu * vcpu)1487 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1488 {
1489 int i;
1490
1491 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1492 for (i = 0; i < KVM_NR_DB_REGS; i++)
1493 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1494 }
1495 }
1496
kvm_update_dr7(struct kvm_vcpu * vcpu)1497 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1498 {
1499 unsigned long dr7;
1500
1501 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1502 dr7 = vcpu->arch.guest_debug_dr7;
1503 else
1504 dr7 = vcpu->arch.dr7;
1505 kvm_x86_call(set_dr7)(vcpu, dr7);
1506 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1507 if (dr7 & DR7_BP_EN_MASK)
1508 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1509 }
1510 EXPORT_SYMBOL_GPL(kvm_update_dr7);
1511
kvm_dr6_fixed(struct kvm_vcpu * vcpu)1512 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1513 {
1514 u64 fixed = DR6_FIXED_1;
1515
1516 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_RTM))
1517 fixed |= DR6_RTM;
1518
1519 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1520 fixed |= DR6_BUS_LOCK;
1521 return fixed;
1522 }
1523
kvm_set_dr(struct kvm_vcpu * vcpu,int dr,unsigned long val)1524 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1525 {
1526 size_t size = ARRAY_SIZE(vcpu->arch.db);
1527
1528 switch (dr) {
1529 case 0 ... 3:
1530 vcpu->arch.db[array_index_nospec(dr, size)] = val;
1531 if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1532 vcpu->arch.eff_db[dr] = val;
1533 break;
1534 case 4:
1535 case 6:
1536 if (!kvm_dr6_valid(val))
1537 return 1; /* #GP */
1538 vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1539 break;
1540 case 5:
1541 default: /* 7 */
1542 if (!kvm_dr7_valid(val))
1543 return 1; /* #GP */
1544 vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1545 kvm_update_dr7(vcpu);
1546 break;
1547 }
1548
1549 return 0;
1550 }
1551 EXPORT_SYMBOL_GPL(kvm_set_dr);
1552
kvm_get_dr(struct kvm_vcpu * vcpu,int dr)1553 unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr)
1554 {
1555 size_t size = ARRAY_SIZE(vcpu->arch.db);
1556
1557 switch (dr) {
1558 case 0 ... 3:
1559 return vcpu->arch.db[array_index_nospec(dr, size)];
1560 case 4:
1561 case 6:
1562 return vcpu->arch.dr6;
1563 case 5:
1564 default: /* 7 */
1565 return vcpu->arch.dr7;
1566 }
1567 }
1568 EXPORT_SYMBOL_GPL(kvm_get_dr);
1569
kvm_emulate_rdpmc(struct kvm_vcpu * vcpu)1570 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1571 {
1572 u32 ecx = kvm_rcx_read(vcpu);
1573 u64 data;
1574
1575 if (kvm_pmu_rdpmc(vcpu, ecx, &data)) {
1576 kvm_inject_gp(vcpu, 0);
1577 return 1;
1578 }
1579
1580 kvm_rax_write(vcpu, (u32)data);
1581 kvm_rdx_write(vcpu, data >> 32);
1582 return kvm_skip_emulated_instruction(vcpu);
1583 }
1584 EXPORT_SYMBOL_GPL(kvm_emulate_rdpmc);
1585
1586 /*
1587 * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1588 * does not yet virtualize. These include:
1589 * 10 - MISC_PACKAGE_CTRLS
1590 * 11 - ENERGY_FILTERING_CTL
1591 * 12 - DOITM
1592 * 18 - FB_CLEAR_CTRL
1593 * 21 - XAPIC_DISABLE_STATUS
1594 * 23 - OVERCLOCKING_STATUS
1595 */
1596
1597 #define KVM_SUPPORTED_ARCH_CAP \
1598 (ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1599 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1600 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1601 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1602 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
1603 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO | ARCH_CAP_ITS_NO)
1604
kvm_get_arch_capabilities(void)1605 static u64 kvm_get_arch_capabilities(void)
1606 {
1607 u64 data = kvm_host.arch_capabilities & KVM_SUPPORTED_ARCH_CAP;
1608
1609 /*
1610 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1611 * the nested hypervisor runs with NX huge pages. If it is not,
1612 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1613 * L1 guests, so it need not worry about its own (L2) guests.
1614 */
1615 data |= ARCH_CAP_PSCHANGE_MC_NO;
1616
1617 /*
1618 * If we're doing cache flushes (either "always" or "cond")
1619 * we will do one whenever the guest does a vmlaunch/vmresume.
1620 * If an outer hypervisor is doing the cache flush for us
1621 * (ARCH_CAP_SKIP_VMENTRY_L1DFLUSH), we can safely pass that
1622 * capability to the guest too, and if EPT is disabled we're not
1623 * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
1624 * require a nested hypervisor to do a flush of its own.
1625 */
1626 if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1627 data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1628
1629 if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1630 data |= ARCH_CAP_RDCL_NO;
1631 if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1632 data |= ARCH_CAP_SSB_NO;
1633 if (!boot_cpu_has_bug(X86_BUG_MDS))
1634 data |= ARCH_CAP_MDS_NO;
1635 if (!boot_cpu_has_bug(X86_BUG_RFDS))
1636 data |= ARCH_CAP_RFDS_NO;
1637 if (!boot_cpu_has_bug(X86_BUG_ITS))
1638 data |= ARCH_CAP_ITS_NO;
1639
1640 if (!boot_cpu_has(X86_FEATURE_RTM)) {
1641 /*
1642 * If RTM=0 because the kernel has disabled TSX, the host might
1643 * have TAA_NO or TSX_CTRL. Clear TAA_NO (the guest sees RTM=0
1644 * and therefore knows that there cannot be TAA) but keep
1645 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1646 * and we want to allow migrating those guests to tsx=off hosts.
1647 */
1648 data &= ~ARCH_CAP_TAA_NO;
1649 } else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1650 data |= ARCH_CAP_TAA_NO;
1651 } else {
1652 /*
1653 * Nothing to do here; we emulate TSX_CTRL if present on the
1654 * host so the guest can choose between disabling TSX or
1655 * using VERW to clear CPU buffers.
1656 */
1657 }
1658
1659 if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1660 data |= ARCH_CAP_GDS_NO;
1661
1662 return data;
1663 }
1664
kvm_get_feature_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1665 static int kvm_get_feature_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1666 bool host_initiated)
1667 {
1668 WARN_ON_ONCE(!host_initiated);
1669
1670 switch (index) {
1671 case MSR_IA32_ARCH_CAPABILITIES:
1672 *data = kvm_get_arch_capabilities();
1673 break;
1674 case MSR_IA32_PERF_CAPABILITIES:
1675 *data = kvm_caps.supported_perf_cap;
1676 break;
1677 case MSR_PLATFORM_INFO:
1678 *data = MSR_PLATFORM_INFO_CPUID_FAULT;
1679 break;
1680 case MSR_IA32_UCODE_REV:
1681 rdmsrq_safe(index, data);
1682 break;
1683 default:
1684 return kvm_x86_call(get_feature_msr)(index, data);
1685 }
1686 return 0;
1687 }
1688
do_get_feature_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)1689 static int do_get_feature_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1690 {
1691 return kvm_do_msr_access(vcpu, index, data, true, MSR_TYPE_R,
1692 kvm_get_feature_msr);
1693 }
1694
__kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1695 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1696 {
1697 if (efer & EFER_AUTOIBRS && !guest_cpu_cap_has(vcpu, X86_FEATURE_AUTOIBRS))
1698 return false;
1699
1700 if (efer & EFER_FFXSR && !guest_cpu_cap_has(vcpu, X86_FEATURE_FXSR_OPT))
1701 return false;
1702
1703 if (efer & EFER_SVME && !guest_cpu_cap_has(vcpu, X86_FEATURE_SVM))
1704 return false;
1705
1706 if (efer & (EFER_LME | EFER_LMA) &&
1707 !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1708 return false;
1709
1710 if (efer & EFER_NX && !guest_cpu_cap_has(vcpu, X86_FEATURE_NX))
1711 return false;
1712
1713 return true;
1714
1715 }
kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1716 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1717 {
1718 if (efer & efer_reserved_bits)
1719 return false;
1720
1721 return __kvm_valid_efer(vcpu, efer);
1722 }
1723 EXPORT_SYMBOL_GPL(kvm_valid_efer);
1724
set_efer(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1725 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1726 {
1727 u64 old_efer = vcpu->arch.efer;
1728 u64 efer = msr_info->data;
1729 int r;
1730
1731 if (efer & efer_reserved_bits)
1732 return 1;
1733
1734 if (!msr_info->host_initiated) {
1735 if (!__kvm_valid_efer(vcpu, efer))
1736 return 1;
1737
1738 if (is_paging(vcpu) &&
1739 (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1740 return 1;
1741 }
1742
1743 efer &= ~EFER_LMA;
1744 efer |= vcpu->arch.efer & EFER_LMA;
1745
1746 r = kvm_x86_call(set_efer)(vcpu, efer);
1747 if (r) {
1748 WARN_ON(r > 0);
1749 return r;
1750 }
1751
1752 if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1753 kvm_mmu_reset_context(vcpu);
1754
1755 if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1756 (efer & EFER_SVME))
1757 kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1758
1759 return 0;
1760 }
1761
kvm_enable_efer_bits(u64 mask)1762 void kvm_enable_efer_bits(u64 mask)
1763 {
1764 efer_reserved_bits &= ~mask;
1765 }
1766 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
1767
kvm_msr_allowed(struct kvm_vcpu * vcpu,u32 index,u32 type)1768 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1769 {
1770 struct kvm_x86_msr_filter *msr_filter;
1771 struct msr_bitmap_range *ranges;
1772 struct kvm *kvm = vcpu->kvm;
1773 bool allowed;
1774 int idx;
1775 u32 i;
1776
1777 /* x2APIC MSRs do not support filtering. */
1778 if (index >= 0x800 && index <= 0x8ff)
1779 return true;
1780
1781 idx = srcu_read_lock(&kvm->srcu);
1782
1783 msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1784 if (!msr_filter) {
1785 allowed = true;
1786 goto out;
1787 }
1788
1789 allowed = msr_filter->default_allow;
1790 ranges = msr_filter->ranges;
1791
1792 for (i = 0; i < msr_filter->count; i++) {
1793 u32 start = ranges[i].base;
1794 u32 end = start + ranges[i].nmsrs;
1795 u32 flags = ranges[i].flags;
1796 unsigned long *bitmap = ranges[i].bitmap;
1797
1798 if ((index >= start) && (index < end) && (flags & type)) {
1799 allowed = test_bit(index - start, bitmap);
1800 break;
1801 }
1802 }
1803
1804 out:
1805 srcu_read_unlock(&kvm->srcu, idx);
1806
1807 return allowed;
1808 }
1809 EXPORT_SYMBOL_GPL(kvm_msr_allowed);
1810
1811 /*
1812 * Write @data into the MSR specified by @index. Select MSR specific fault
1813 * checks are bypassed if @host_initiated is %true.
1814 * Returns 0 on success, non-0 otherwise.
1815 * Assumes vcpu_load() was already called.
1816 */
__kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1817 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1818 bool host_initiated)
1819 {
1820 struct msr_data msr;
1821
1822 switch (index) {
1823 case MSR_FS_BASE:
1824 case MSR_GS_BASE:
1825 case MSR_KERNEL_GS_BASE:
1826 case MSR_CSTAR:
1827 case MSR_LSTAR:
1828 if (is_noncanonical_msr_address(data, vcpu))
1829 return 1;
1830 break;
1831 case MSR_IA32_SYSENTER_EIP:
1832 case MSR_IA32_SYSENTER_ESP:
1833 /*
1834 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1835 * non-canonical address is written on Intel but not on
1836 * AMD (which ignores the top 32-bits, because it does
1837 * not implement 64-bit SYSENTER).
1838 *
1839 * 64-bit code should hence be able to write a non-canonical
1840 * value on AMD. Making the address canonical ensures that
1841 * vmentry does not fail on Intel after writing a non-canonical
1842 * value, and that something deterministic happens if the guest
1843 * invokes 64-bit SYSENTER.
1844 */
1845 data = __canonical_address(data, max_host_virt_addr_bits());
1846 break;
1847 case MSR_TSC_AUX:
1848 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1849 return 1;
1850
1851 if (!host_initiated &&
1852 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1853 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1854 return 1;
1855
1856 /*
1857 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1858 * incomplete and conflicting architectural behavior. Current
1859 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1860 * reserved and always read as zeros. Enforce Intel's reserved
1861 * bits check if the guest CPU is Intel compatible, otherwise
1862 * clear the bits. This ensures cross-vendor migration will
1863 * provide consistent behavior for the guest.
1864 */
1865 if (guest_cpuid_is_intel_compatible(vcpu) && (data >> 32) != 0)
1866 return 1;
1867
1868 data = (u32)data;
1869 break;
1870 }
1871
1872 msr.data = data;
1873 msr.index = index;
1874 msr.host_initiated = host_initiated;
1875
1876 return kvm_x86_call(set_msr)(vcpu, &msr);
1877 }
1878
_kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1879 static int _kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1880 bool host_initiated)
1881 {
1882 return __kvm_set_msr(vcpu, index, *data, host_initiated);
1883 }
1884
kvm_set_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1885 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1886 u32 index, u64 data, bool host_initiated)
1887 {
1888 return kvm_do_msr_access(vcpu, index, &data, host_initiated, MSR_TYPE_W,
1889 _kvm_set_msr);
1890 }
1891
1892 /*
1893 * Read the MSR specified by @index into @data. Select MSR specific fault
1894 * checks are bypassed if @host_initiated is %true.
1895 * Returns 0 on success, non-0 otherwise.
1896 * Assumes vcpu_load() was already called.
1897 */
__kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1898 int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1899 bool host_initiated)
1900 {
1901 struct msr_data msr;
1902 int ret;
1903
1904 switch (index) {
1905 case MSR_TSC_AUX:
1906 if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1907 return 1;
1908
1909 if (!host_initiated &&
1910 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1911 !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1912 return 1;
1913 break;
1914 }
1915
1916 msr.index = index;
1917 msr.host_initiated = host_initiated;
1918
1919 ret = kvm_x86_call(get_msr)(vcpu, &msr);
1920 if (!ret)
1921 *data = msr.data;
1922 return ret;
1923 }
1924
kvm_get_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1925 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
1926 u32 index, u64 *data, bool host_initiated)
1927 {
1928 return kvm_do_msr_access(vcpu, index, data, host_initiated, MSR_TYPE_R,
1929 __kvm_get_msr);
1930 }
1931
kvm_get_msr_with_filter(struct kvm_vcpu * vcpu,u32 index,u64 * data)1932 int kvm_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1933 {
1934 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
1935 return KVM_MSR_RET_FILTERED;
1936 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1937 }
1938 EXPORT_SYMBOL_GPL(kvm_get_msr_with_filter);
1939
kvm_set_msr_with_filter(struct kvm_vcpu * vcpu,u32 index,u64 data)1940 int kvm_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 index, u64 data)
1941 {
1942 if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
1943 return KVM_MSR_RET_FILTERED;
1944 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1945 }
1946 EXPORT_SYMBOL_GPL(kvm_set_msr_with_filter);
1947
kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data)1948 int kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
1949 {
1950 return kvm_get_msr_ignored_check(vcpu, index, data, false);
1951 }
1952 EXPORT_SYMBOL_GPL(kvm_get_msr);
1953
kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data)1954 int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
1955 {
1956 return kvm_set_msr_ignored_check(vcpu, index, data, false);
1957 }
1958 EXPORT_SYMBOL_GPL(kvm_set_msr);
1959
complete_userspace_rdmsr(struct kvm_vcpu * vcpu)1960 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
1961 {
1962 if (!vcpu->run->msr.error) {
1963 kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
1964 kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
1965 }
1966 }
1967
complete_emulated_msr_access(struct kvm_vcpu * vcpu)1968 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
1969 {
1970 return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
1971 }
1972
complete_emulated_rdmsr(struct kvm_vcpu * vcpu)1973 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
1974 {
1975 complete_userspace_rdmsr(vcpu);
1976 return complete_emulated_msr_access(vcpu);
1977 }
1978
complete_fast_msr_access(struct kvm_vcpu * vcpu)1979 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
1980 {
1981 return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
1982 }
1983
complete_fast_rdmsr(struct kvm_vcpu * vcpu)1984 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
1985 {
1986 complete_userspace_rdmsr(vcpu);
1987 return complete_fast_msr_access(vcpu);
1988 }
1989
kvm_msr_reason(int r)1990 static u64 kvm_msr_reason(int r)
1991 {
1992 switch (r) {
1993 case KVM_MSR_RET_UNSUPPORTED:
1994 return KVM_MSR_EXIT_REASON_UNKNOWN;
1995 case KVM_MSR_RET_FILTERED:
1996 return KVM_MSR_EXIT_REASON_FILTER;
1997 default:
1998 return KVM_MSR_EXIT_REASON_INVAL;
1999 }
2000 }
2001
kvm_msr_user_space(struct kvm_vcpu * vcpu,u32 index,u32 exit_reason,u64 data,int (* completion)(struct kvm_vcpu * vcpu),int r)2002 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
2003 u32 exit_reason, u64 data,
2004 int (*completion)(struct kvm_vcpu *vcpu),
2005 int r)
2006 {
2007 u64 msr_reason = kvm_msr_reason(r);
2008
2009 /* Check if the user wanted to know about this MSR fault */
2010 if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2011 return 0;
2012
2013 vcpu->run->exit_reason = exit_reason;
2014 vcpu->run->msr.error = 0;
2015 memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2016 vcpu->run->msr.reason = msr_reason;
2017 vcpu->run->msr.index = index;
2018 vcpu->run->msr.data = data;
2019 vcpu->arch.complete_userspace_io = completion;
2020
2021 return 1;
2022 }
2023
kvm_emulate_rdmsr(struct kvm_vcpu * vcpu)2024 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2025 {
2026 u32 ecx = kvm_rcx_read(vcpu);
2027 u64 data;
2028 int r;
2029
2030 r = kvm_get_msr_with_filter(vcpu, ecx, &data);
2031
2032 if (!r) {
2033 trace_kvm_msr_read(ecx, data);
2034
2035 kvm_rax_write(vcpu, data & -1u);
2036 kvm_rdx_write(vcpu, (data >> 32) & -1u);
2037 } else {
2038 /* MSR read failed? See if we should ask user space */
2039 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_RDMSR, 0,
2040 complete_fast_rdmsr, r))
2041 return 0;
2042 trace_kvm_msr_read_ex(ecx);
2043 }
2044
2045 return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2046 }
2047 EXPORT_SYMBOL_GPL(kvm_emulate_rdmsr);
2048
kvm_emulate_wrmsr(struct kvm_vcpu * vcpu)2049 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2050 {
2051 u32 ecx = kvm_rcx_read(vcpu);
2052 u64 data = kvm_read_edx_eax(vcpu);
2053 int r;
2054
2055 r = kvm_set_msr_with_filter(vcpu, ecx, data);
2056
2057 if (!r) {
2058 trace_kvm_msr_write(ecx, data);
2059 } else {
2060 /* MSR write failed? See if we should ask user space */
2061 if (kvm_msr_user_space(vcpu, ecx, KVM_EXIT_X86_WRMSR, data,
2062 complete_fast_msr_access, r))
2063 return 0;
2064 /* Signal all other negative errors to userspace */
2065 if (r < 0)
2066 return r;
2067 trace_kvm_msr_write_ex(ecx, data);
2068 }
2069
2070 return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2071 }
2072 EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
2073
kvm_emulate_as_nop(struct kvm_vcpu * vcpu)2074 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2075 {
2076 return kvm_skip_emulated_instruction(vcpu);
2077 }
2078
kvm_emulate_invd(struct kvm_vcpu * vcpu)2079 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2080 {
2081 /* Treat an INVD instruction as a NOP and just skip it. */
2082 return kvm_emulate_as_nop(vcpu);
2083 }
2084 EXPORT_SYMBOL_GPL(kvm_emulate_invd);
2085
kvm_handle_invalid_op(struct kvm_vcpu * vcpu)2086 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2087 {
2088 kvm_queue_exception(vcpu, UD_VECTOR);
2089 return 1;
2090 }
2091 EXPORT_SYMBOL_GPL(kvm_handle_invalid_op);
2092
2093
kvm_emulate_monitor_mwait(struct kvm_vcpu * vcpu,const char * insn)2094 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2095 {
2096 bool enabled;
2097
2098 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS))
2099 goto emulate_as_nop;
2100
2101 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
2102 enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_MWAIT);
2103 else
2104 enabled = vcpu->arch.ia32_misc_enable_msr & MSR_IA32_MISC_ENABLE_MWAIT;
2105
2106 if (!enabled)
2107 return kvm_handle_invalid_op(vcpu);
2108
2109 emulate_as_nop:
2110 pr_warn_once("%s instruction emulated as NOP!\n", insn);
2111 return kvm_emulate_as_nop(vcpu);
2112 }
kvm_emulate_mwait(struct kvm_vcpu * vcpu)2113 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2114 {
2115 return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2116 }
2117 EXPORT_SYMBOL_GPL(kvm_emulate_mwait);
2118
kvm_emulate_monitor(struct kvm_vcpu * vcpu)2119 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2120 {
2121 return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2122 }
2123 EXPORT_SYMBOL_GPL(kvm_emulate_monitor);
2124
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu)2125 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2126 {
2127 xfer_to_guest_mode_prepare();
2128
2129 return READ_ONCE(vcpu->mode) == EXITING_GUEST_MODE ||
2130 kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending();
2131 }
2132
2133 /*
2134 * The fast path for frequent and performance sensitive wrmsr emulation,
2135 * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
2136 * the latency of virtual IPI by avoiding the expensive bits of transitioning
2137 * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
2138 * other cases which must be called after interrupts are enabled on the host.
2139 */
handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu * vcpu,u64 data)2140 static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
2141 {
2142 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic))
2143 return 1;
2144
2145 if (((data & APIC_SHORT_MASK) == APIC_DEST_NOSHORT) &&
2146 ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
2147 ((data & APIC_MODE_MASK) == APIC_DM_FIXED) &&
2148 ((u32)(data >> 32) != X2APIC_BROADCAST))
2149 return kvm_x2apic_icr_write(vcpu->arch.apic, data);
2150
2151 return 1;
2152 }
2153
handle_fastpath_set_tscdeadline(struct kvm_vcpu * vcpu,u64 data)2154 static int handle_fastpath_set_tscdeadline(struct kvm_vcpu *vcpu, u64 data)
2155 {
2156 if (!kvm_can_use_hv_timer(vcpu))
2157 return 1;
2158
2159 kvm_set_lapic_tscdeadline_msr(vcpu, data);
2160 return 0;
2161 }
2162
handle_fastpath_set_msr_irqoff(struct kvm_vcpu * vcpu)2163 fastpath_t handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
2164 {
2165 u32 msr = kvm_rcx_read(vcpu);
2166 u64 data;
2167 fastpath_t ret;
2168 bool handled;
2169
2170 kvm_vcpu_srcu_read_lock(vcpu);
2171
2172 switch (msr) {
2173 case APIC_BASE_MSR + (APIC_ICR >> 4):
2174 data = kvm_read_edx_eax(vcpu);
2175 handled = !handle_fastpath_set_x2apic_icr_irqoff(vcpu, data);
2176 break;
2177 case MSR_IA32_TSC_DEADLINE:
2178 data = kvm_read_edx_eax(vcpu);
2179 handled = !handle_fastpath_set_tscdeadline(vcpu, data);
2180 break;
2181 default:
2182 handled = false;
2183 break;
2184 }
2185
2186 if (handled) {
2187 if (!kvm_skip_emulated_instruction(vcpu))
2188 ret = EXIT_FASTPATH_EXIT_USERSPACE;
2189 else
2190 ret = EXIT_FASTPATH_REENTER_GUEST;
2191 trace_kvm_msr_write(msr, data);
2192 } else {
2193 ret = EXIT_FASTPATH_NONE;
2194 }
2195
2196 kvm_vcpu_srcu_read_unlock(vcpu);
2197
2198 return ret;
2199 }
2200 EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
2201
2202 /*
2203 * Adapt set_msr() to msr_io()'s calling convention
2204 */
do_get_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2205 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2206 {
2207 return kvm_get_msr_ignored_check(vcpu, index, data, true);
2208 }
2209
do_set_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2210 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2211 {
2212 u64 val;
2213
2214 /*
2215 * Disallow writes to immutable feature MSRs after KVM_RUN. KVM does
2216 * not support modifying the guest vCPU model on the fly, e.g. changing
2217 * the nVMX capabilities while L2 is running is nonsensical. Allow
2218 * writes of the same value, e.g. to allow userspace to blindly stuff
2219 * all MSRs when emulating RESET.
2220 */
2221 if (kvm_vcpu_has_run(vcpu) && kvm_is_immutable_feature_msr(index) &&
2222 (do_get_msr(vcpu, index, &val) || *data != val))
2223 return -EINVAL;
2224
2225 return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2226 }
2227
2228 #ifdef CONFIG_X86_64
2229 struct pvclock_clock {
2230 int vclock_mode;
2231 u64 cycle_last;
2232 u64 mask;
2233 u32 mult;
2234 u32 shift;
2235 u64 base_cycles;
2236 u64 offset;
2237 };
2238
2239 struct pvclock_gtod_data {
2240 seqcount_t seq;
2241
2242 struct pvclock_clock clock; /* extract of a clocksource struct */
2243 struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2244
2245 ktime_t offs_boot;
2246 u64 wall_time_sec;
2247 };
2248
2249 static struct pvclock_gtod_data pvclock_gtod_data;
2250
update_pvclock_gtod(struct timekeeper * tk)2251 static void update_pvclock_gtod(struct timekeeper *tk)
2252 {
2253 struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2254
2255 write_seqcount_begin(&vdata->seq);
2256
2257 /* copy pvclock gtod data */
2258 vdata->clock.vclock_mode = tk->tkr_mono.clock->vdso_clock_mode;
2259 vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
2260 vdata->clock.mask = tk->tkr_mono.mask;
2261 vdata->clock.mult = tk->tkr_mono.mult;
2262 vdata->clock.shift = tk->tkr_mono.shift;
2263 vdata->clock.base_cycles = tk->tkr_mono.xtime_nsec;
2264 vdata->clock.offset = tk->tkr_mono.base;
2265
2266 vdata->raw_clock.vclock_mode = tk->tkr_raw.clock->vdso_clock_mode;
2267 vdata->raw_clock.cycle_last = tk->tkr_raw.cycle_last;
2268 vdata->raw_clock.mask = tk->tkr_raw.mask;
2269 vdata->raw_clock.mult = tk->tkr_raw.mult;
2270 vdata->raw_clock.shift = tk->tkr_raw.shift;
2271 vdata->raw_clock.base_cycles = tk->tkr_raw.xtime_nsec;
2272 vdata->raw_clock.offset = tk->tkr_raw.base;
2273
2274 vdata->wall_time_sec = tk->xtime_sec;
2275
2276 vdata->offs_boot = tk->offs_boot;
2277
2278 write_seqcount_end(&vdata->seq);
2279 }
2280
get_kvmclock_base_ns(void)2281 static s64 get_kvmclock_base_ns(void)
2282 {
2283 /* Count up from boot time, but with the frequency of the raw clock. */
2284 return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2285 }
2286 #else
get_kvmclock_base_ns(void)2287 static s64 get_kvmclock_base_ns(void)
2288 {
2289 /* Master clock not used, so we can just use CLOCK_BOOTTIME. */
2290 return ktime_get_boottime_ns();
2291 }
2292 #endif
2293
kvm_write_wall_clock(struct kvm * kvm,gpa_t wall_clock,int sec_hi_ofs)2294 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2295 {
2296 int version;
2297 int r;
2298 struct pvclock_wall_clock wc;
2299 u32 wc_sec_hi;
2300 u64 wall_nsec;
2301
2302 if (!wall_clock)
2303 return;
2304
2305 r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2306 if (r)
2307 return;
2308
2309 if (version & 1)
2310 ++version; /* first time write, random junk */
2311
2312 ++version;
2313
2314 if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2315 return;
2316
2317 wall_nsec = kvm_get_wall_clock_epoch(kvm);
2318
2319 wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
2320 wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2321 wc.version = version;
2322
2323 kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2324
2325 if (sec_hi_ofs) {
2326 wc_sec_hi = wall_nsec >> 32;
2327 kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2328 &wc_sec_hi, sizeof(wc_sec_hi));
2329 }
2330
2331 version++;
2332 kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2333 }
2334
kvm_write_system_time(struct kvm_vcpu * vcpu,gpa_t system_time,bool old_msr,bool host_initiated)2335 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2336 bool old_msr, bool host_initiated)
2337 {
2338 struct kvm_arch *ka = &vcpu->kvm->arch;
2339
2340 if (vcpu->vcpu_id == 0 && !host_initiated) {
2341 if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2342 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2343
2344 ka->boot_vcpu_runs_old_kvmclock = old_msr;
2345 }
2346
2347 vcpu->arch.time = system_time;
2348 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2349
2350 /* we verify if the enable bit is set... */
2351 if (system_time & 1)
2352 kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
2353 sizeof(struct pvclock_vcpu_time_info));
2354 else
2355 kvm_gpc_deactivate(&vcpu->arch.pv_time);
2356
2357 return;
2358 }
2359
div_frac(uint32_t dividend,uint32_t divisor)2360 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2361 {
2362 do_shl32_div32(dividend, divisor);
2363 return dividend;
2364 }
2365
kvm_get_time_scale(uint64_t scaled_hz,uint64_t base_hz,s8 * pshift,u32 * pmultiplier)2366 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2367 s8 *pshift, u32 *pmultiplier)
2368 {
2369 uint64_t scaled64;
2370 int32_t shift = 0;
2371 uint64_t tps64;
2372 uint32_t tps32;
2373
2374 tps64 = base_hz;
2375 scaled64 = scaled_hz;
2376 while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2377 tps64 >>= 1;
2378 shift--;
2379 }
2380
2381 tps32 = (uint32_t)tps64;
2382 while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2383 if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2384 scaled64 >>= 1;
2385 else
2386 tps32 <<= 1;
2387 shift++;
2388 }
2389
2390 *pshift = shift;
2391 *pmultiplier = div_frac(scaled64, tps32);
2392 }
2393
2394 #ifdef CONFIG_X86_64
2395 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2396 #endif
2397
2398 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2399 static unsigned long max_tsc_khz;
2400
adjust_tsc_khz(u32 khz,s32 ppm)2401 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2402 {
2403 u64 v = (u64)khz * (1000000 + ppm);
2404 do_div(v, 1000000);
2405 return v;
2406 }
2407
2408 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2409
set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz,bool scale)2410 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2411 {
2412 u64 ratio;
2413
2414 /* Guest TSC same frequency as host TSC? */
2415 if (!scale) {
2416 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2417 return 0;
2418 }
2419
2420 /* TSC scaling supported? */
2421 if (!kvm_caps.has_tsc_control) {
2422 if (user_tsc_khz > tsc_khz) {
2423 vcpu->arch.tsc_catchup = 1;
2424 vcpu->arch.tsc_always_catchup = 1;
2425 return 0;
2426 } else {
2427 pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2428 return -1;
2429 }
2430 }
2431
2432 /* TSC scaling required - calculate ratio */
2433 ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2434 user_tsc_khz, tsc_khz);
2435
2436 if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2437 pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2438 user_tsc_khz);
2439 return -1;
2440 }
2441
2442 kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2443 return 0;
2444 }
2445
kvm_set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz)2446 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2447 {
2448 u32 thresh_lo, thresh_hi;
2449 int use_scaling = 0;
2450
2451 /* tsc_khz can be zero if TSC calibration fails */
2452 if (user_tsc_khz == 0) {
2453 /* set tsc_scaling_ratio to a safe value */
2454 kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2455 return -1;
2456 }
2457
2458 /* Compute a scale to convert nanoseconds in TSC cycles */
2459 kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2460 &vcpu->arch.virtual_tsc_shift,
2461 &vcpu->arch.virtual_tsc_mult);
2462 vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2463
2464 /*
2465 * Compute the variation in TSC rate which is acceptable
2466 * within the range of tolerance and decide if the
2467 * rate being applied is within that bounds of the hardware
2468 * rate. If so, no scaling or compensation need be done.
2469 */
2470 thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2471 thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2472 if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2473 pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2474 user_tsc_khz, thresh_lo, thresh_hi);
2475 use_scaling = 1;
2476 }
2477 return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2478 }
2479
compute_guest_tsc(struct kvm_vcpu * vcpu,s64 kernel_ns)2480 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2481 {
2482 u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2483 vcpu->arch.virtual_tsc_mult,
2484 vcpu->arch.virtual_tsc_shift);
2485 tsc += vcpu->arch.this_tsc_write;
2486 return tsc;
2487 }
2488
2489 #ifdef CONFIG_X86_64
gtod_is_based_on_tsc(int mode)2490 static inline bool gtod_is_based_on_tsc(int mode)
2491 {
2492 return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2493 }
2494 #endif
2495
kvm_track_tsc_matching(struct kvm_vcpu * vcpu,bool new_generation)2496 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
2497 {
2498 #ifdef CONFIG_X86_64
2499 struct kvm_arch *ka = &vcpu->kvm->arch;
2500 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2501
2502 /*
2503 * To use the masterclock, the host clocksource must be based on TSC
2504 * and all vCPUs must have matching TSCs. Note, the count for matching
2505 * vCPUs doesn't include the reference vCPU, hence "+1".
2506 */
2507 bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2508 atomic_read(&vcpu->kvm->online_vcpus)) &&
2509 gtod_is_based_on_tsc(gtod->clock.vclock_mode);
2510
2511 /*
2512 * Request a masterclock update if the masterclock needs to be toggled
2513 * on/off, or when starting a new generation and the masterclock is
2514 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2515 * taken _after_ the new generation is created).
2516 */
2517 if ((ka->use_master_clock && new_generation) ||
2518 (ka->use_master_clock != use_master_clock))
2519 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2520
2521 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2522 atomic_read(&vcpu->kvm->online_vcpus),
2523 ka->use_master_clock, gtod->clock.vclock_mode);
2524 #endif
2525 }
2526
2527 /*
2528 * Multiply tsc by a fixed point number represented by ratio.
2529 *
2530 * The most significant 64-N bits (mult) of ratio represent the
2531 * integral part of the fixed point number; the remaining N bits
2532 * (frac) represent the fractional part, ie. ratio represents a fixed
2533 * point number (mult + frac * 2^(-N)).
2534 *
2535 * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2536 */
__scale_tsc(u64 ratio,u64 tsc)2537 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2538 {
2539 return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2540 }
2541
kvm_scale_tsc(u64 tsc,u64 ratio)2542 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2543 {
2544 u64 _tsc = tsc;
2545
2546 if (ratio != kvm_caps.default_tsc_scaling_ratio)
2547 _tsc = __scale_tsc(ratio, tsc);
2548
2549 return _tsc;
2550 }
2551
kvm_compute_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 target_tsc)2552 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2553 {
2554 u64 tsc;
2555
2556 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2557
2558 return target_tsc - tsc;
2559 }
2560
kvm_read_l1_tsc(struct kvm_vcpu * vcpu,u64 host_tsc)2561 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2562 {
2563 return vcpu->arch.l1_tsc_offset +
2564 kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2565 }
2566 EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
2567
kvm_calc_nested_tsc_offset(u64 l1_offset,u64 l2_offset,u64 l2_multiplier)2568 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2569 {
2570 u64 nested_offset;
2571
2572 if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2573 nested_offset = l1_offset;
2574 else
2575 nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2576 kvm_caps.tsc_scaling_ratio_frac_bits);
2577
2578 nested_offset += l2_offset;
2579 return nested_offset;
2580 }
2581 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_offset);
2582
kvm_calc_nested_tsc_multiplier(u64 l1_multiplier,u64 l2_multiplier)2583 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2584 {
2585 if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2586 return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2587 kvm_caps.tsc_scaling_ratio_frac_bits);
2588
2589 return l1_multiplier;
2590 }
2591 EXPORT_SYMBOL_GPL(kvm_calc_nested_tsc_multiplier);
2592
kvm_vcpu_write_tsc_offset(struct kvm_vcpu * vcpu,u64 l1_offset)2593 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2594 {
2595 if (vcpu->arch.guest_tsc_protected)
2596 return;
2597
2598 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2599 vcpu->arch.l1_tsc_offset,
2600 l1_offset);
2601
2602 vcpu->arch.l1_tsc_offset = l1_offset;
2603
2604 /*
2605 * If we are here because L1 chose not to trap WRMSR to TSC then
2606 * according to the spec this should set L1's TSC (as opposed to
2607 * setting L1's offset for L2).
2608 */
2609 if (is_guest_mode(vcpu))
2610 vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2611 l1_offset,
2612 kvm_x86_call(get_l2_tsc_offset)(vcpu),
2613 kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2614 else
2615 vcpu->arch.tsc_offset = l1_offset;
2616
2617 kvm_x86_call(write_tsc_offset)(vcpu);
2618 }
2619
kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu * vcpu,u64 l1_multiplier)2620 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2621 {
2622 vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2623
2624 /* Userspace is changing the multiplier while L2 is active */
2625 if (is_guest_mode(vcpu))
2626 vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2627 l1_multiplier,
2628 kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2629 else
2630 vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2631
2632 if (kvm_caps.has_tsc_control)
2633 kvm_x86_call(write_tsc_multiplier)(vcpu);
2634 }
2635
kvm_check_tsc_unstable(void)2636 static inline bool kvm_check_tsc_unstable(void)
2637 {
2638 #ifdef CONFIG_X86_64
2639 /*
2640 * TSC is marked unstable when we're running on Hyper-V,
2641 * 'TSC page' clocksource is good.
2642 */
2643 if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2644 return false;
2645 #endif
2646 return check_tsc_unstable();
2647 }
2648
2649 /*
2650 * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2651 * offset for the vcpu and tracks the TSC matching generation that the vcpu
2652 * participates in.
2653 */
__kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 offset,u64 tsc,u64 ns,bool matched,bool user_set_tsc)2654 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2655 u64 ns, bool matched, bool user_set_tsc)
2656 {
2657 struct kvm *kvm = vcpu->kvm;
2658
2659 lockdep_assert_held(&kvm->arch.tsc_write_lock);
2660
2661 if (vcpu->arch.guest_tsc_protected)
2662 return;
2663
2664 if (user_set_tsc)
2665 vcpu->kvm->arch.user_set_tsc = true;
2666
2667 /*
2668 * We also track th most recent recorded KHZ, write and time to
2669 * allow the matching interval to be extended at each write.
2670 */
2671 kvm->arch.last_tsc_nsec = ns;
2672 kvm->arch.last_tsc_write = tsc;
2673 kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2674 kvm->arch.last_tsc_offset = offset;
2675
2676 vcpu->arch.last_guest_tsc = tsc;
2677
2678 kvm_vcpu_write_tsc_offset(vcpu, offset);
2679
2680 if (!matched) {
2681 /*
2682 * We split periods of matched TSC writes into generations.
2683 * For each generation, we track the original measured
2684 * nanosecond time, offset, and write, so if TSCs are in
2685 * sync, we can match exact offset, and if not, we can match
2686 * exact software computation in compute_guest_tsc()
2687 *
2688 * These values are tracked in kvm->arch.cur_xxx variables.
2689 */
2690 kvm->arch.cur_tsc_generation++;
2691 kvm->arch.cur_tsc_nsec = ns;
2692 kvm->arch.cur_tsc_write = tsc;
2693 kvm->arch.cur_tsc_offset = offset;
2694 kvm->arch.nr_vcpus_matched_tsc = 0;
2695 } else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2696 kvm->arch.nr_vcpus_matched_tsc++;
2697 }
2698
2699 /* Keep track of which generation this VCPU has synchronized to */
2700 vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2701 vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2702 vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2703
2704 kvm_track_tsc_matching(vcpu, !matched);
2705 }
2706
kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 * user_value)2707 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
2708 {
2709 u64 data = user_value ? *user_value : 0;
2710 struct kvm *kvm = vcpu->kvm;
2711 u64 offset, ns, elapsed;
2712 unsigned long flags;
2713 bool matched = false;
2714 bool synchronizing = false;
2715
2716 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2717 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2718 ns = get_kvmclock_base_ns();
2719 elapsed = ns - kvm->arch.last_tsc_nsec;
2720
2721 if (vcpu->arch.virtual_tsc_khz) {
2722 if (data == 0) {
2723 /*
2724 * Force synchronization when creating a vCPU, or when
2725 * userspace explicitly writes a zero value.
2726 */
2727 synchronizing = true;
2728 } else if (kvm->arch.user_set_tsc) {
2729 u64 tsc_exp = kvm->arch.last_tsc_write +
2730 nsec_to_cycles(vcpu, elapsed);
2731 u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2732 /*
2733 * Here lies UAPI baggage: when a user-initiated TSC write has
2734 * a small delta (1 second) of virtual cycle time against the
2735 * previously set vCPU, we assume that they were intended to be
2736 * in sync and the delta was only due to the racy nature of the
2737 * legacy API.
2738 *
2739 * This trick falls down when restoring a guest which genuinely
2740 * has been running for less time than the 1 second of imprecision
2741 * which we allow for in the legacy API. In this case, the first
2742 * value written by userspace (on any vCPU) should not be subject
2743 * to this 'correction' to make it sync up with values that only
2744 * come from the kernel's default vCPU creation. Make the 1-second
2745 * slop hack only trigger if the user_set_tsc flag is already set.
2746 */
2747 synchronizing = data < tsc_exp + tsc_hz &&
2748 data + tsc_hz > tsc_exp;
2749 }
2750 }
2751
2752
2753 /*
2754 * For a reliable TSC, we can match TSC offsets, and for an unstable
2755 * TSC, we add elapsed time in this computation. We could let the
2756 * compensation code attempt to catch up if we fall behind, but
2757 * it's better to try to match offsets from the beginning.
2758 */
2759 if (synchronizing &&
2760 vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2761 if (!kvm_check_tsc_unstable()) {
2762 offset = kvm->arch.cur_tsc_offset;
2763 } else {
2764 u64 delta = nsec_to_cycles(vcpu, elapsed);
2765 data += delta;
2766 offset = kvm_compute_l1_tsc_offset(vcpu, data);
2767 }
2768 matched = true;
2769 }
2770
2771 __kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value);
2772 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2773 }
2774
adjust_tsc_offset_guest(struct kvm_vcpu * vcpu,s64 adjustment)2775 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2776 s64 adjustment)
2777 {
2778 u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2779 kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2780 }
2781
adjust_tsc_offset_host(struct kvm_vcpu * vcpu,s64 adjustment)2782 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2783 {
2784 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2785 WARN_ON(adjustment < 0);
2786 adjustment = kvm_scale_tsc((u64) adjustment,
2787 vcpu->arch.l1_tsc_scaling_ratio);
2788 adjust_tsc_offset_guest(vcpu, adjustment);
2789 }
2790
2791 #ifdef CONFIG_X86_64
2792
read_tsc(void)2793 static u64 read_tsc(void)
2794 {
2795 u64 ret = (u64)rdtsc_ordered();
2796 u64 last = pvclock_gtod_data.clock.cycle_last;
2797
2798 if (likely(ret >= last))
2799 return ret;
2800
2801 /*
2802 * GCC likes to generate cmov here, but this branch is extremely
2803 * predictable (it's just a function of time and the likely is
2804 * very likely) and there's a data dependence, so force GCC
2805 * to generate a branch instead. I don't barrier() because
2806 * we don't actually need a barrier, and if this function
2807 * ever gets inlined it will generate worse code.
2808 */
2809 asm volatile ("");
2810 return last;
2811 }
2812
vgettsc(struct pvclock_clock * clock,u64 * tsc_timestamp,int * mode)2813 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2814 int *mode)
2815 {
2816 u64 tsc_pg_val;
2817 long v;
2818
2819 switch (clock->vclock_mode) {
2820 case VDSO_CLOCKMODE_HVCLOCK:
2821 if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2822 tsc_timestamp, &tsc_pg_val)) {
2823 /* TSC page valid */
2824 *mode = VDSO_CLOCKMODE_HVCLOCK;
2825 v = (tsc_pg_val - clock->cycle_last) &
2826 clock->mask;
2827 } else {
2828 /* TSC page invalid */
2829 *mode = VDSO_CLOCKMODE_NONE;
2830 }
2831 break;
2832 case VDSO_CLOCKMODE_TSC:
2833 *mode = VDSO_CLOCKMODE_TSC;
2834 *tsc_timestamp = read_tsc();
2835 v = (*tsc_timestamp - clock->cycle_last) &
2836 clock->mask;
2837 break;
2838 default:
2839 *mode = VDSO_CLOCKMODE_NONE;
2840 }
2841
2842 if (*mode == VDSO_CLOCKMODE_NONE)
2843 *tsc_timestamp = v = 0;
2844
2845 return v * clock->mult;
2846 }
2847
2848 /*
2849 * As with get_kvmclock_base_ns(), this counts from boot time, at the
2850 * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2851 */
do_kvmclock_base(s64 * t,u64 * tsc_timestamp)2852 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
2853 {
2854 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2855 unsigned long seq;
2856 int mode;
2857 u64 ns;
2858
2859 do {
2860 seq = read_seqcount_begin(>od->seq);
2861 ns = gtod->raw_clock.base_cycles;
2862 ns += vgettsc(>od->raw_clock, tsc_timestamp, &mode);
2863 ns >>= gtod->raw_clock.shift;
2864 ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2865 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2866 *t = ns;
2867
2868 return mode;
2869 }
2870
2871 /*
2872 * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2873 * no boot time offset.
2874 */
do_monotonic(s64 * t,u64 * tsc_timestamp)2875 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2876 {
2877 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2878 unsigned long seq;
2879 int mode;
2880 u64 ns;
2881
2882 do {
2883 seq = read_seqcount_begin(>od->seq);
2884 ns = gtod->clock.base_cycles;
2885 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2886 ns >>= gtod->clock.shift;
2887 ns += ktime_to_ns(gtod->clock.offset);
2888 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2889 *t = ns;
2890
2891 return mode;
2892 }
2893
do_realtime(struct timespec64 * ts,u64 * tsc_timestamp)2894 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
2895 {
2896 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2897 unsigned long seq;
2898 int mode;
2899 u64 ns;
2900
2901 do {
2902 seq = read_seqcount_begin(>od->seq);
2903 ts->tv_sec = gtod->wall_time_sec;
2904 ns = gtod->clock.base_cycles;
2905 ns += vgettsc(>od->clock, tsc_timestamp, &mode);
2906 ns >>= gtod->clock.shift;
2907 } while (unlikely(read_seqcount_retry(>od->seq, seq)));
2908
2909 ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
2910 ts->tv_nsec = ns;
2911
2912 return mode;
2913 }
2914
2915 /*
2916 * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
2917 * reports the TSC value from which it do so. Returns true if host is
2918 * using TSC based clocksource.
2919 */
kvm_get_time_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)2920 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2921 {
2922 /* checked again under seqlock below */
2923 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2924 return false;
2925
2926 return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
2927 tsc_timestamp));
2928 }
2929
2930 /*
2931 * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
2932 * so. Returns true if host is using TSC based clocksource.
2933 */
kvm_get_monotonic_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)2934 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
2935 {
2936 /* checked again under seqlock below */
2937 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2938 return false;
2939
2940 return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
2941 tsc_timestamp));
2942 }
2943
2944 /*
2945 * Calculates CLOCK_REALTIME and reports the TSC value from which it did
2946 * so. Returns true if host is using TSC based clocksource.
2947 *
2948 * DO NOT USE this for anything related to migration. You want CLOCK_TAI
2949 * for that.
2950 */
kvm_get_walltime_and_clockread(struct timespec64 * ts,u64 * tsc_timestamp)2951 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
2952 u64 *tsc_timestamp)
2953 {
2954 /* checked again under seqlock below */
2955 if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
2956 return false;
2957
2958 return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
2959 }
2960 #endif
2961
2962 /*
2963 *
2964 * Assuming a stable TSC across physical CPUS, and a stable TSC
2965 * across virtual CPUs, the following condition is possible.
2966 * Each numbered line represents an event visible to both
2967 * CPUs at the next numbered event.
2968 *
2969 * "timespecX" represents host monotonic time. "tscX" represents
2970 * RDTSC value.
2971 *
2972 * VCPU0 on CPU0 | VCPU1 on CPU1
2973 *
2974 * 1. read timespec0,tsc0
2975 * 2. | timespec1 = timespec0 + N
2976 * | tsc1 = tsc0 + M
2977 * 3. transition to guest | transition to guest
2978 * 4. ret0 = timespec0 + (rdtsc - tsc0) |
2979 * 5. | ret1 = timespec1 + (rdtsc - tsc1)
2980 * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
2981 *
2982 * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
2983 *
2984 * - ret0 < ret1
2985 * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
2986 * ...
2987 * - 0 < N - M => M < N
2988 *
2989 * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
2990 * always the case (the difference between two distinct xtime instances
2991 * might be smaller then the difference between corresponding TSC reads,
2992 * when updating guest vcpus pvclock areas).
2993 *
2994 * To avoid that problem, do not allow visibility of distinct
2995 * system_timestamp/tsc_timestamp values simultaneously: use a master
2996 * copy of host monotonic time values. Update that master copy
2997 * in lockstep.
2998 *
2999 * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
3000 *
3001 */
3002
pvclock_update_vm_gtod_copy(struct kvm * kvm)3003 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
3004 {
3005 #ifdef CONFIG_X86_64
3006 struct kvm_arch *ka = &kvm->arch;
3007 int vclock_mode;
3008 bool host_tsc_clocksource, vcpus_matched;
3009
3010 lockdep_assert_held(&kvm->arch.tsc_write_lock);
3011 vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
3012 atomic_read(&kvm->online_vcpus));
3013
3014 /*
3015 * If the host uses TSC clock, then passthrough TSC as stable
3016 * to the guest.
3017 */
3018 host_tsc_clocksource = kvm_get_time_and_clockread(
3019 &ka->master_kernel_ns,
3020 &ka->master_cycle_now);
3021
3022 ka->use_master_clock = host_tsc_clocksource && vcpus_matched
3023 && !ka->backwards_tsc_observed
3024 && !ka->boot_vcpu_runs_old_kvmclock;
3025
3026 if (ka->use_master_clock)
3027 atomic_set(&kvm_guest_has_master_clock, 1);
3028
3029 vclock_mode = pvclock_gtod_data.clock.vclock_mode;
3030 trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3031 vcpus_matched);
3032 #endif
3033 }
3034
kvm_make_mclock_inprogress_request(struct kvm * kvm)3035 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
3036 {
3037 kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3038 }
3039
__kvm_start_pvclock_update(struct kvm * kvm)3040 static void __kvm_start_pvclock_update(struct kvm *kvm)
3041 {
3042 raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3043 write_seqcount_begin(&kvm->arch.pvclock_sc);
3044 }
3045
kvm_start_pvclock_update(struct kvm * kvm)3046 static void kvm_start_pvclock_update(struct kvm *kvm)
3047 {
3048 kvm_make_mclock_inprogress_request(kvm);
3049
3050 /* no guest entries from this point */
3051 __kvm_start_pvclock_update(kvm);
3052 }
3053
kvm_end_pvclock_update(struct kvm * kvm)3054 static void kvm_end_pvclock_update(struct kvm *kvm)
3055 {
3056 struct kvm_arch *ka = &kvm->arch;
3057 struct kvm_vcpu *vcpu;
3058 unsigned long i;
3059
3060 write_seqcount_end(&ka->pvclock_sc);
3061 raw_spin_unlock_irq(&ka->tsc_write_lock);
3062 kvm_for_each_vcpu(i, vcpu, kvm)
3063 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3064
3065 /* guest entries allowed */
3066 kvm_for_each_vcpu(i, vcpu, kvm)
3067 kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
3068 }
3069
kvm_update_masterclock(struct kvm * kvm)3070 static void kvm_update_masterclock(struct kvm *kvm)
3071 {
3072 kvm_hv_request_tsc_page_update(kvm);
3073 kvm_start_pvclock_update(kvm);
3074 pvclock_update_vm_gtod_copy(kvm);
3075 kvm_end_pvclock_update(kvm);
3076 }
3077
3078 /*
3079 * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3080 * per-CPU value (which may be zero if a CPU is going offline). Note, tsc_khz
3081 * can change during boot even if the TSC is constant, as it's possible for KVM
3082 * to be loaded before TSC calibration completes. Ideally, KVM would get a
3083 * notification when calibration completes, but practically speaking calibration
3084 * will complete before userspace is alive enough to create VMs.
3085 */
get_cpu_tsc_khz(void)3086 static unsigned long get_cpu_tsc_khz(void)
3087 {
3088 if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3089 return tsc_khz;
3090 else
3091 return __this_cpu_read(cpu_tsc_khz);
3092 }
3093
3094 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc. */
__get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3095 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3096 {
3097 struct kvm_arch *ka = &kvm->arch;
3098 struct pvclock_vcpu_time_info hv_clock;
3099
3100 /* both __this_cpu_read() and rdtsc() should be on the same cpu */
3101 get_cpu();
3102
3103 data->flags = 0;
3104 if (ka->use_master_clock &&
3105 (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
3106 #ifdef CONFIG_X86_64
3107 struct timespec64 ts;
3108
3109 if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3110 data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3111 data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3112 } else
3113 #endif
3114 data->host_tsc = rdtsc();
3115
3116 data->flags |= KVM_CLOCK_TSC_STABLE;
3117 hv_clock.tsc_timestamp = ka->master_cycle_now;
3118 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3119 kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
3120 &hv_clock.tsc_shift,
3121 &hv_clock.tsc_to_system_mul);
3122 data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3123 } else {
3124 data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3125 }
3126
3127 put_cpu();
3128 }
3129
get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3130 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3131 {
3132 struct kvm_arch *ka = &kvm->arch;
3133 unsigned seq;
3134
3135 do {
3136 seq = read_seqcount_begin(&ka->pvclock_sc);
3137 __get_kvmclock(kvm, data);
3138 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3139 }
3140
get_kvmclock_ns(struct kvm * kvm)3141 u64 get_kvmclock_ns(struct kvm *kvm)
3142 {
3143 struct kvm_clock_data data;
3144
3145 get_kvmclock(kvm, &data);
3146 return data.clock;
3147 }
3148
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)3149 static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
3150 struct kvm_vcpu *vcpu,
3151 struct gfn_to_pfn_cache *gpc,
3152 unsigned int offset)
3153 {
3154 struct pvclock_vcpu_time_info *guest_hv_clock;
3155 struct pvclock_vcpu_time_info hv_clock;
3156 unsigned long flags;
3157
3158 memcpy(&hv_clock, ref_hv_clock, sizeof(hv_clock));
3159
3160 read_lock_irqsave(&gpc->lock, flags);
3161 while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
3162 read_unlock_irqrestore(&gpc->lock, flags);
3163
3164 if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
3165 return;
3166
3167 read_lock_irqsave(&gpc->lock, flags);
3168 }
3169
3170 guest_hv_clock = (void *)(gpc->khva + offset);
3171
3172 /*
3173 * This VCPU is paused, but it's legal for a guest to read another
3174 * VCPU's kvmclock, so we really have to follow the specification where
3175 * it says that version is odd if data is being modified, and even after
3176 * it is consistent.
3177 */
3178
3179 guest_hv_clock->version = hv_clock.version = (guest_hv_clock->version + 1) | 1;
3180 smp_wmb();
3181
3182 /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3183 hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3184
3185 memcpy(guest_hv_clock, &hv_clock, sizeof(*guest_hv_clock));
3186
3187 smp_wmb();
3188
3189 guest_hv_clock->version = ++hv_clock.version;
3190
3191 kvm_gpc_mark_dirty_in_slot(gpc);
3192 read_unlock_irqrestore(&gpc->lock, flags);
3193
3194 trace_kvm_pvclock_update(vcpu->vcpu_id, &hv_clock);
3195 }
3196
kvm_guest_time_update(struct kvm_vcpu * v)3197 int kvm_guest_time_update(struct kvm_vcpu *v)
3198 {
3199 struct pvclock_vcpu_time_info hv_clock = {};
3200 unsigned long flags, tgt_tsc_khz;
3201 unsigned seq;
3202 struct kvm_vcpu_arch *vcpu = &v->arch;
3203 struct kvm_arch *ka = &v->kvm->arch;
3204 s64 kernel_ns;
3205 u64 tsc_timestamp, host_tsc;
3206 bool use_master_clock;
3207
3208 kernel_ns = 0;
3209 host_tsc = 0;
3210
3211 /*
3212 * If the host uses TSC clock, then passthrough TSC as stable
3213 * to the guest.
3214 */
3215 do {
3216 seq = read_seqcount_begin(&ka->pvclock_sc);
3217 use_master_clock = ka->use_master_clock;
3218 if (use_master_clock) {
3219 host_tsc = ka->master_cycle_now;
3220 kernel_ns = ka->master_kernel_ns;
3221 }
3222 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3223
3224 /* Keep irq disabled to prevent changes to the clock */
3225 local_irq_save(flags);
3226 tgt_tsc_khz = get_cpu_tsc_khz();
3227 if (unlikely(tgt_tsc_khz == 0)) {
3228 local_irq_restore(flags);
3229 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3230 return 1;
3231 }
3232 if (!use_master_clock) {
3233 host_tsc = rdtsc();
3234 kernel_ns = get_kvmclock_base_ns();
3235 }
3236
3237 tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3238
3239 /*
3240 * We may have to catch up the TSC to match elapsed wall clock
3241 * time for two reasons, even if kvmclock is used.
3242 * 1) CPU could have been running below the maximum TSC rate
3243 * 2) Broken TSC compensation resets the base at each VCPU
3244 * entry to avoid unknown leaps of TSC even when running
3245 * again on the same CPU. This may cause apparent elapsed
3246 * time to disappear, and the guest to stand still or run
3247 * very slowly.
3248 */
3249 if (vcpu->tsc_catchup) {
3250 u64 tsc = compute_guest_tsc(v, kernel_ns);
3251 if (tsc > tsc_timestamp) {
3252 adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3253 tsc_timestamp = tsc;
3254 }
3255 }
3256
3257 local_irq_restore(flags);
3258
3259 /* With all the info we got, fill in the values */
3260
3261 if (kvm_caps.has_tsc_control)
3262 tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3263 v->arch.l1_tsc_scaling_ratio);
3264
3265 if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3266 kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3267 &vcpu->pvclock_tsc_shift,
3268 &vcpu->pvclock_tsc_mul);
3269 vcpu->hw_tsc_khz = tgt_tsc_khz;
3270 }
3271
3272 hv_clock.tsc_shift = vcpu->pvclock_tsc_shift;
3273 hv_clock.tsc_to_system_mul = vcpu->pvclock_tsc_mul;
3274 hv_clock.tsc_timestamp = tsc_timestamp;
3275 hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3276 vcpu->last_guest_tsc = tsc_timestamp;
3277
3278 /* If the host uses TSC clocksource, then it is stable */
3279 hv_clock.flags = 0;
3280 if (use_master_clock)
3281 hv_clock.flags |= PVCLOCK_TSC_STABLE_BIT;
3282
3283 if (vcpu->pv_time.active) {
3284 /*
3285 * GUEST_STOPPED is only supported by kvmclock, and KVM's
3286 * historic behavior is to only process the request if kvmclock
3287 * is active/enabled.
3288 */
3289 if (vcpu->pvclock_set_guest_stopped_request) {
3290 hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3291 vcpu->pvclock_set_guest_stopped_request = false;
3292 }
3293 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->pv_time, 0);
3294
3295 hv_clock.flags &= ~PVCLOCK_GUEST_STOPPED;
3296 }
3297
3298 kvm_hv_setup_tsc_page(v->kvm, &hv_clock);
3299
3300 #ifdef CONFIG_KVM_XEN
3301 /*
3302 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3303 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3304 * This default behaviour led to bugs in some guest kernels which cause
3305 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3306 *
3307 * Note! Clear TSC_STABLE only for Xen clocks, i.e. the order matters!
3308 */
3309 if (ka->xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
3310 hv_clock.flags &= ~PVCLOCK_TSC_STABLE_BIT;
3311
3312 if (vcpu->xen.vcpu_info_cache.active)
3313 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_info_cache,
3314 offsetof(struct compat_vcpu_info, time));
3315 if (vcpu->xen.vcpu_time_info_cache.active)
3316 kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_time_info_cache, 0);
3317 #endif
3318 return 0;
3319 }
3320
3321 /*
3322 * The pvclock_wall_clock ABI tells the guest the wall clock time at
3323 * which it started (i.e. its epoch, when its kvmclock was zero).
3324 *
3325 * In fact those clocks are subtly different; wall clock frequency is
3326 * adjusted by NTP and has leap seconds, while the kvmclock is a
3327 * simple function of the TSC without any such adjustment.
3328 *
3329 * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3330 * that and kvmclock, but even that would be subject to change over
3331 * time.
3332 *
3333 * Attempt to calculate the epoch at a given moment using the *same*
3334 * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3335 * wallclock and kvmclock times, and subtracting one from the other.
3336 *
3337 * Fall back to using their values at slightly different moments by
3338 * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3339 */
kvm_get_wall_clock_epoch(struct kvm * kvm)3340 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3341 {
3342 #ifdef CONFIG_X86_64
3343 struct pvclock_vcpu_time_info hv_clock;
3344 struct kvm_arch *ka = &kvm->arch;
3345 unsigned long seq, local_tsc_khz;
3346 struct timespec64 ts;
3347 uint64_t host_tsc;
3348
3349 do {
3350 seq = read_seqcount_begin(&ka->pvclock_sc);
3351
3352 local_tsc_khz = 0;
3353 if (!ka->use_master_clock)
3354 break;
3355
3356 /*
3357 * The TSC read and the call to get_cpu_tsc_khz() must happen
3358 * on the same CPU.
3359 */
3360 get_cpu();
3361
3362 local_tsc_khz = get_cpu_tsc_khz();
3363
3364 if (local_tsc_khz &&
3365 !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3366 local_tsc_khz = 0; /* Fall back to old method */
3367
3368 put_cpu();
3369
3370 /*
3371 * These values must be snapshotted within the seqcount loop.
3372 * After that, it's just mathematics which can happen on any
3373 * CPU at any time.
3374 */
3375 hv_clock.tsc_timestamp = ka->master_cycle_now;
3376 hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3377
3378 } while (read_seqcount_retry(&ka->pvclock_sc, seq));
3379
3380 /*
3381 * If the conditions were right, and obtaining the wallclock+TSC was
3382 * successful, calculate the KVM clock at the corresponding time and
3383 * subtract one from the other to get the guest's epoch in nanoseconds
3384 * since 1970-01-01.
3385 */
3386 if (local_tsc_khz) {
3387 kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3388 &hv_clock.tsc_shift,
3389 &hv_clock.tsc_to_system_mul);
3390 return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3391 __pvclock_read_cycles(&hv_clock, host_tsc);
3392 }
3393 #endif
3394 return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3395 }
3396
3397 /*
3398 * kvmclock updates which are isolated to a given vcpu, such as
3399 * vcpu->cpu migration, should not allow system_timestamp from
3400 * the rest of the vcpus to remain static. Otherwise ntp frequency
3401 * correction applies to one vcpu's system_timestamp but not
3402 * the others.
3403 *
3404 * So in those cases, request a kvmclock update for all vcpus.
3405 * We need to rate-limit these requests though, as they can
3406 * considerably slow guests that have a large number of vcpus.
3407 * The time for a remote vcpu to update its kvmclock is bound
3408 * by the delay we use to rate-limit the updates.
3409 */
3410
3411 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3412
kvmclock_update_fn(struct work_struct * work)3413 static void kvmclock_update_fn(struct work_struct *work)
3414 {
3415 unsigned long i;
3416 struct delayed_work *dwork = to_delayed_work(work);
3417 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3418 kvmclock_update_work);
3419 struct kvm *kvm = container_of(ka, struct kvm, arch);
3420 struct kvm_vcpu *vcpu;
3421
3422 kvm_for_each_vcpu(i, vcpu, kvm) {
3423 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3424 kvm_vcpu_kick(vcpu);
3425 }
3426 }
3427
kvm_gen_kvmclock_update(struct kvm_vcpu * v)3428 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3429 {
3430 struct kvm *kvm = v->kvm;
3431
3432 kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3433 schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3434 KVMCLOCK_UPDATE_DELAY);
3435 }
3436
3437 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3438
kvmclock_sync_fn(struct work_struct * work)3439 static void kvmclock_sync_fn(struct work_struct *work)
3440 {
3441 struct delayed_work *dwork = to_delayed_work(work);
3442 struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3443 kvmclock_sync_work);
3444 struct kvm *kvm = container_of(ka, struct kvm, arch);
3445
3446 schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3447 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3448 KVMCLOCK_SYNC_PERIOD);
3449 }
3450
3451 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
is_mci_control_msr(u32 msr)3452 static bool is_mci_control_msr(u32 msr)
3453 {
3454 return (msr & 3) == 0;
3455 }
is_mci_status_msr(u32 msr)3456 static bool is_mci_status_msr(u32 msr)
3457 {
3458 return (msr & 3) == 1;
3459 }
3460
3461 /*
3462 * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3463 */
can_set_mci_status(struct kvm_vcpu * vcpu)3464 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3465 {
3466 /* McStatusWrEn enabled? */
3467 if (guest_cpuid_is_amd_compatible(vcpu))
3468 return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3469
3470 return false;
3471 }
3472
set_msr_mce(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3473 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3474 {
3475 u64 mcg_cap = vcpu->arch.mcg_cap;
3476 unsigned bank_num = mcg_cap & 0xff;
3477 u32 msr = msr_info->index;
3478 u64 data = msr_info->data;
3479 u32 offset, last_msr;
3480
3481 switch (msr) {
3482 case MSR_IA32_MCG_STATUS:
3483 vcpu->arch.mcg_status = data;
3484 break;
3485 case MSR_IA32_MCG_CTL:
3486 if (!(mcg_cap & MCG_CTL_P) &&
3487 (data || !msr_info->host_initiated))
3488 return 1;
3489 if (data != 0 && data != ~(u64)0)
3490 return 1;
3491 vcpu->arch.mcg_ctl = data;
3492 break;
3493 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3494 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3495 if (msr > last_msr)
3496 return 1;
3497
3498 if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3499 return 1;
3500 /* An attempt to write a 1 to a reserved bit raises #GP */
3501 if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3502 return 1;
3503 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3504 last_msr + 1 - MSR_IA32_MC0_CTL2);
3505 vcpu->arch.mci_ctl2_banks[offset] = data;
3506 break;
3507 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3508 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3509 if (msr > last_msr)
3510 return 1;
3511
3512 /*
3513 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3514 * values are architecturally undefined. But, some Linux
3515 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3516 * issue on AMD K8s, allow bit 10 to be clear when setting all
3517 * other bits in order to avoid an uncaught #GP in the guest.
3518 *
3519 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3520 * single-bit ECC data errors.
3521 */
3522 if (is_mci_control_msr(msr) &&
3523 data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3524 return 1;
3525
3526 /*
3527 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3528 * AMD-based CPUs allow non-zero values, but if and only if
3529 * HWCR[McStatusWrEn] is set.
3530 */
3531 if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3532 data != 0 && !can_set_mci_status(vcpu))
3533 return 1;
3534
3535 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3536 last_msr + 1 - MSR_IA32_MC0_CTL);
3537 vcpu->arch.mce_banks[offset] = data;
3538 break;
3539 default:
3540 return 1;
3541 }
3542 return 0;
3543 }
3544
kvm_pv_async_pf_enabled(struct kvm_vcpu * vcpu)3545 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3546 {
3547 u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3548
3549 return (vcpu->arch.apf.msr_en_val & mask) == mask;
3550 }
3551
kvm_pv_enable_async_pf(struct kvm_vcpu * vcpu,u64 data)3552 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3553 {
3554 gpa_t gpa = data & ~0x3f;
3555
3556 /* Bits 4:5 are reserved, Should be zero */
3557 if (data & 0x30)
3558 return 1;
3559
3560 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3561 (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3562 return 1;
3563
3564 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3565 (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3566 return 1;
3567
3568 if (!lapic_in_kernel(vcpu))
3569 return data ? 1 : 0;
3570
3571 vcpu->arch.apf.msr_en_val = data;
3572
3573 if (!kvm_pv_async_pf_enabled(vcpu)) {
3574 kvm_clear_async_pf_completion_queue(vcpu);
3575 kvm_async_pf_hash_reset(vcpu);
3576 return 0;
3577 }
3578
3579 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3580 sizeof(u64)))
3581 return 1;
3582
3583 vcpu->arch.apf.send_always = (data & KVM_ASYNC_PF_SEND_ALWAYS);
3584 vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3585
3586 kvm_async_pf_wakeup_all(vcpu);
3587
3588 return 0;
3589 }
3590
kvm_pv_enable_async_pf_int(struct kvm_vcpu * vcpu,u64 data)3591 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3592 {
3593 /* Bits 8-63 are reserved */
3594 if (data >> 8)
3595 return 1;
3596
3597 if (!lapic_in_kernel(vcpu))
3598 return 1;
3599
3600 vcpu->arch.apf.msr_int_val = data;
3601
3602 vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3603
3604 return 0;
3605 }
3606
kvmclock_reset(struct kvm_vcpu * vcpu)3607 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3608 {
3609 kvm_gpc_deactivate(&vcpu->arch.pv_time);
3610 vcpu->arch.time = 0;
3611 }
3612
kvm_vcpu_flush_tlb_all(struct kvm_vcpu * vcpu)3613 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3614 {
3615 ++vcpu->stat.tlb_flush;
3616 kvm_x86_call(flush_tlb_all)(vcpu);
3617
3618 /* Flushing all ASIDs flushes the current ASID... */
3619 kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3620 }
3621
kvm_vcpu_flush_tlb_guest(struct kvm_vcpu * vcpu)3622 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3623 {
3624 ++vcpu->stat.tlb_flush;
3625
3626 if (!tdp_enabled) {
3627 /*
3628 * A TLB flush on behalf of the guest is equivalent to
3629 * INVPCID(all), toggling CR4.PGE, etc., which requires
3630 * a forced sync of the shadow page tables. Ensure all the
3631 * roots are synced and the guest TLB in hardware is clean.
3632 */
3633 kvm_mmu_sync_roots(vcpu);
3634 kvm_mmu_sync_prev_roots(vcpu);
3635 }
3636
3637 kvm_x86_call(flush_tlb_guest)(vcpu);
3638
3639 /*
3640 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3641 * grained flushing.
3642 */
3643 kvm_hv_vcpu_purge_flush_tlb(vcpu);
3644 }
3645
3646
kvm_vcpu_flush_tlb_current(struct kvm_vcpu * vcpu)3647 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3648 {
3649 ++vcpu->stat.tlb_flush;
3650 kvm_x86_call(flush_tlb_current)(vcpu);
3651 }
3652
3653 /*
3654 * Service "local" TLB flush requests, which are specific to the current MMU
3655 * context. In addition to the generic event handling in vcpu_enter_guest(),
3656 * TLB flushes that are targeted at an MMU context also need to be serviced
3657 * prior before nested VM-Enter/VM-Exit.
3658 */
kvm_service_local_tlb_flush_requests(struct kvm_vcpu * vcpu)3659 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3660 {
3661 if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3662 kvm_vcpu_flush_tlb_current(vcpu);
3663
3664 if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3665 kvm_vcpu_flush_tlb_guest(vcpu);
3666 }
3667 EXPORT_SYMBOL_GPL(kvm_service_local_tlb_flush_requests);
3668
record_steal_time(struct kvm_vcpu * vcpu)3669 static void record_steal_time(struct kvm_vcpu *vcpu)
3670 {
3671 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3672 struct kvm_steal_time __user *st;
3673 struct kvm_memslots *slots;
3674 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3675 u64 steal;
3676 u32 version;
3677
3678 if (kvm_xen_msr_enabled(vcpu->kvm)) {
3679 kvm_xen_runstate_set_running(vcpu);
3680 return;
3681 }
3682
3683 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3684 return;
3685
3686 if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3687 return;
3688
3689 slots = kvm_memslots(vcpu->kvm);
3690
3691 if (unlikely(slots->generation != ghc->generation ||
3692 gpa != ghc->gpa ||
3693 kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3694 /* We rely on the fact that it fits in a single page. */
3695 BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3696
3697 if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3698 kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3699 return;
3700 }
3701
3702 st = (struct kvm_steal_time __user *)ghc->hva;
3703 /*
3704 * Doing a TLB flush here, on the guest's behalf, can avoid
3705 * expensive IPIs.
3706 */
3707 if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3708 u8 st_preempted = 0;
3709 int err = -EFAULT;
3710
3711 if (!user_access_begin(st, sizeof(*st)))
3712 return;
3713
3714 asm volatile("1: xchgb %0, %2\n"
3715 "xor %1, %1\n"
3716 "2:\n"
3717 _ASM_EXTABLE_UA(1b, 2b)
3718 : "+q" (st_preempted),
3719 "+&r" (err),
3720 "+m" (st->preempted));
3721 if (err)
3722 goto out;
3723
3724 user_access_end();
3725
3726 vcpu->arch.st.preempted = 0;
3727
3728 trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3729 st_preempted & KVM_VCPU_FLUSH_TLB);
3730 if (st_preempted & KVM_VCPU_FLUSH_TLB)
3731 kvm_vcpu_flush_tlb_guest(vcpu);
3732
3733 if (!user_access_begin(st, sizeof(*st)))
3734 goto dirty;
3735 } else {
3736 if (!user_access_begin(st, sizeof(*st)))
3737 return;
3738
3739 unsafe_put_user(0, &st->preempted, out);
3740 vcpu->arch.st.preempted = 0;
3741 }
3742
3743 unsafe_get_user(version, &st->version, out);
3744 if (version & 1)
3745 version += 1; /* first time write, random junk */
3746
3747 version += 1;
3748 unsafe_put_user(version, &st->version, out);
3749
3750 smp_wmb();
3751
3752 unsafe_get_user(steal, &st->steal, out);
3753 steal += current->sched_info.run_delay -
3754 vcpu->arch.st.last_steal;
3755 vcpu->arch.st.last_steal = current->sched_info.run_delay;
3756 unsafe_put_user(steal, &st->steal, out);
3757
3758 version += 1;
3759 unsafe_put_user(version, &st->version, out);
3760
3761 out:
3762 user_access_end();
3763 dirty:
3764 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3765 }
3766
kvm_set_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3767 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3768 {
3769 u32 msr = msr_info->index;
3770 u64 data = msr_info->data;
3771
3772 /*
3773 * Do not allow host-initiated writes to trigger the Xen hypercall
3774 * page setup; it could incur locking paths which are not expected
3775 * if userspace sets the MSR in an unusual location.
3776 */
3777 if (kvm_xen_is_hypercall_page_msr(vcpu->kvm, msr) &&
3778 !msr_info->host_initiated)
3779 return kvm_xen_write_hypercall_page(vcpu, data);
3780
3781 switch (msr) {
3782 case MSR_AMD64_NB_CFG:
3783 case MSR_IA32_UCODE_WRITE:
3784 case MSR_VM_HSAVE_PA:
3785 case MSR_AMD64_PATCH_LOADER:
3786 case MSR_AMD64_BU_CFG2:
3787 case MSR_AMD64_DC_CFG:
3788 case MSR_AMD64_TW_CFG:
3789 case MSR_F15H_EX_CFG:
3790 break;
3791
3792 case MSR_IA32_UCODE_REV:
3793 if (msr_info->host_initiated)
3794 vcpu->arch.microcode_version = data;
3795 break;
3796 case MSR_IA32_ARCH_CAPABILITIES:
3797 if (!msr_info->host_initiated ||
3798 !guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3799 return KVM_MSR_RET_UNSUPPORTED;
3800 vcpu->arch.arch_capabilities = data;
3801 break;
3802 case MSR_IA32_PERF_CAPABILITIES:
3803 if (!msr_info->host_initiated ||
3804 !guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
3805 return KVM_MSR_RET_UNSUPPORTED;
3806
3807 if (data & ~kvm_caps.supported_perf_cap)
3808 return 1;
3809
3810 /*
3811 * Note, this is not just a performance optimization! KVM
3812 * disallows changing feature MSRs after the vCPU has run; PMU
3813 * refresh will bug the VM if called after the vCPU has run.
3814 */
3815 if (vcpu->arch.perf_capabilities == data)
3816 break;
3817
3818 vcpu->arch.perf_capabilities = data;
3819 kvm_pmu_refresh(vcpu);
3820 break;
3821 case MSR_IA32_PRED_CMD: {
3822 u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3823
3824 if (!msr_info->host_initiated) {
3825 if ((!guest_has_pred_cmd_msr(vcpu)))
3826 return 1;
3827
3828 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3829 !guest_cpu_cap_has(vcpu, X86_FEATURE_AMD_IBPB))
3830 reserved_bits |= PRED_CMD_IBPB;
3831
3832 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SBPB))
3833 reserved_bits |= PRED_CMD_SBPB;
3834 }
3835
3836 if (!boot_cpu_has(X86_FEATURE_IBPB))
3837 reserved_bits |= PRED_CMD_IBPB;
3838
3839 if (!boot_cpu_has(X86_FEATURE_SBPB))
3840 reserved_bits |= PRED_CMD_SBPB;
3841
3842 if (data & reserved_bits)
3843 return 1;
3844
3845 if (!data)
3846 break;
3847
3848 wrmsrq(MSR_IA32_PRED_CMD, data);
3849 break;
3850 }
3851 case MSR_IA32_FLUSH_CMD:
3852 if (!msr_info->host_initiated &&
3853 !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D))
3854 return 1;
3855
3856 if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
3857 return 1;
3858 if (!data)
3859 break;
3860
3861 wrmsrq(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
3862 break;
3863 case MSR_EFER:
3864 return set_efer(vcpu, msr_info);
3865 case MSR_K7_HWCR:
3866 data &= ~(u64)0x40; /* ignore flush filter disable */
3867 data &= ~(u64)0x100; /* ignore ignne emulation enable */
3868 data &= ~(u64)0x8; /* ignore TLB cache disable */
3869
3870 /*
3871 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
3872 * through at least v6.6 whine if TscFreqSel is clear,
3873 * depending on F/M/S.
3874 */
3875 if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
3876 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
3877 return 1;
3878 }
3879 vcpu->arch.msr_hwcr = data;
3880 break;
3881 case MSR_FAM10H_MMIO_CONF_BASE:
3882 if (data != 0) {
3883 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
3884 return 1;
3885 }
3886 break;
3887 case MSR_IA32_CR_PAT:
3888 if (!kvm_pat_valid(data))
3889 return 1;
3890
3891 vcpu->arch.pat = data;
3892 break;
3893 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
3894 case MSR_MTRRdefType:
3895 return kvm_mtrr_set_msr(vcpu, msr, data);
3896 case MSR_IA32_APICBASE:
3897 return kvm_apic_set_base(vcpu, data, msr_info->host_initiated);
3898 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
3899 return kvm_x2apic_msr_write(vcpu, msr, data);
3900 case MSR_IA32_TSC_DEADLINE:
3901 kvm_set_lapic_tscdeadline_msr(vcpu, data);
3902 break;
3903 case MSR_IA32_TSC_ADJUST:
3904 if (guest_cpu_cap_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
3905 if (!msr_info->host_initiated) {
3906 s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
3907 adjust_tsc_offset_guest(vcpu, adj);
3908 /* Before back to guest, tsc_timestamp must be adjusted
3909 * as well, otherwise guest's percpu pvclock time could jump.
3910 */
3911 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3912 }
3913 vcpu->arch.ia32_tsc_adjust_msr = data;
3914 }
3915 break;
3916 case MSR_IA32_MISC_ENABLE: {
3917 u64 old_val = vcpu->arch.ia32_misc_enable_msr;
3918
3919 if (!msr_info->host_initiated) {
3920 /* RO bits */
3921 if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
3922 return 1;
3923
3924 /* R bits, i.e. writes are ignored, but don't fault. */
3925 data = data & ~MSR_IA32_MISC_ENABLE_EMON;
3926 data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
3927 }
3928
3929 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
3930 ((old_val ^ data) & MSR_IA32_MISC_ENABLE_MWAIT)) {
3931 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_XMM3))
3932 return 1;
3933 vcpu->arch.ia32_misc_enable_msr = data;
3934 vcpu->arch.cpuid_dynamic_bits_dirty = true;
3935 } else {
3936 vcpu->arch.ia32_misc_enable_msr = data;
3937 }
3938 break;
3939 }
3940 case MSR_IA32_SMBASE:
3941 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
3942 return 1;
3943 vcpu->arch.smbase = data;
3944 break;
3945 case MSR_IA32_POWER_CTL:
3946 vcpu->arch.msr_ia32_power_ctl = data;
3947 break;
3948 case MSR_IA32_TSC:
3949 if (msr_info->host_initiated) {
3950 kvm_synchronize_tsc(vcpu, &data);
3951 } else if (!vcpu->arch.guest_tsc_protected) {
3952 u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
3953 adjust_tsc_offset_guest(vcpu, adj);
3954 vcpu->arch.ia32_tsc_adjust_msr += adj;
3955 }
3956 break;
3957 case MSR_IA32_XSS:
3958 if (!msr_info->host_initiated &&
3959 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3960 return 1;
3961 /*
3962 * KVM supports exposing PT to the guest, but does not support
3963 * IA32_XSS[bit 8]. Guests have to use RDMSR/WRMSR rather than
3964 * XSAVES/XRSTORS to save/restore PT MSRs.
3965 */
3966 if (data & ~kvm_caps.supported_xss)
3967 return 1;
3968 vcpu->arch.ia32_xss = data;
3969 vcpu->arch.cpuid_dynamic_bits_dirty = true;
3970 break;
3971 case MSR_SMI_COUNT:
3972 if (!msr_info->host_initiated)
3973 return 1;
3974 vcpu->arch.smi_count = data;
3975 break;
3976 case MSR_KVM_WALL_CLOCK_NEW:
3977 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3978 return 1;
3979
3980 vcpu->kvm->arch.wall_clock = data;
3981 kvm_write_wall_clock(vcpu->kvm, data, 0);
3982 break;
3983 case MSR_KVM_WALL_CLOCK:
3984 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3985 return 1;
3986
3987 vcpu->kvm->arch.wall_clock = data;
3988 kvm_write_wall_clock(vcpu->kvm, data, 0);
3989 break;
3990 case MSR_KVM_SYSTEM_TIME_NEW:
3991 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
3992 return 1;
3993
3994 kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
3995 break;
3996 case MSR_KVM_SYSTEM_TIME:
3997 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
3998 return 1;
3999
4000 kvm_write_system_time(vcpu, data, true, msr_info->host_initiated);
4001 break;
4002 case MSR_KVM_ASYNC_PF_EN:
4003 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4004 return 1;
4005
4006 if (kvm_pv_enable_async_pf(vcpu, data))
4007 return 1;
4008 break;
4009 case MSR_KVM_ASYNC_PF_INT:
4010 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4011 return 1;
4012
4013 if (kvm_pv_enable_async_pf_int(vcpu, data))
4014 return 1;
4015 break;
4016 case MSR_KVM_ASYNC_PF_ACK:
4017 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4018 return 1;
4019 if (data & 0x1) {
4020 vcpu->arch.apf.pageready_pending = false;
4021 kvm_check_async_pf_completion(vcpu);
4022 }
4023 break;
4024 case MSR_KVM_STEAL_TIME:
4025 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4026 return 1;
4027
4028 if (unlikely(!sched_info_on()))
4029 return 1;
4030
4031 if (data & KVM_STEAL_RESERVED_MASK)
4032 return 1;
4033
4034 vcpu->arch.st.msr_val = data;
4035
4036 if (!(data & KVM_MSR_ENABLED))
4037 break;
4038
4039 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4040
4041 break;
4042 case MSR_KVM_PV_EOI_EN:
4043 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4044 return 1;
4045
4046 if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
4047 return 1;
4048 break;
4049
4050 case MSR_KVM_POLL_CONTROL:
4051 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4052 return 1;
4053
4054 /* only enable bit supported */
4055 if (data & (-1ULL << 1))
4056 return 1;
4057
4058 vcpu->arch.msr_kvm_poll_control = data;
4059 break;
4060
4061 case MSR_IA32_MCG_CTL:
4062 case MSR_IA32_MCG_STATUS:
4063 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4064 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4065 return set_msr_mce(vcpu, msr_info);
4066
4067 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4068 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4069 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4070 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4071 if (kvm_pmu_is_valid_msr(vcpu, msr))
4072 return kvm_pmu_set_msr(vcpu, msr_info);
4073
4074 if (data)
4075 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4076 break;
4077 case MSR_K7_CLK_CTL:
4078 /*
4079 * Ignore all writes to this no longer documented MSR.
4080 * Writes are only relevant for old K7 processors,
4081 * all pre-dating SVM, but a recommended workaround from
4082 * AMD for these chips. It is possible to specify the
4083 * affected processor models on the command line, hence
4084 * the need to ignore the workaround.
4085 */
4086 break;
4087 #ifdef CONFIG_KVM_HYPERV
4088 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4089 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4090 case HV_X64_MSR_SYNDBG_OPTIONS:
4091 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4092 case HV_X64_MSR_CRASH_CTL:
4093 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4094 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4095 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4096 case HV_X64_MSR_TSC_EMULATION_STATUS:
4097 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4098 return kvm_hv_set_msr_common(vcpu, msr, data,
4099 msr_info->host_initiated);
4100 #endif
4101 case MSR_IA32_BBL_CR_CTL3:
4102 /* Drop writes to this legacy MSR -- see rdmsr
4103 * counterpart for further detail.
4104 */
4105 kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4106 break;
4107 case MSR_AMD64_OSVW_ID_LENGTH:
4108 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4109 return 1;
4110 vcpu->arch.osvw.length = data;
4111 break;
4112 case MSR_AMD64_OSVW_STATUS:
4113 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4114 return 1;
4115 vcpu->arch.osvw.status = data;
4116 break;
4117 case MSR_PLATFORM_INFO:
4118 if (!msr_info->host_initiated)
4119 return 1;
4120 vcpu->arch.msr_platform_info = data;
4121 break;
4122 case MSR_MISC_FEATURES_ENABLES:
4123 if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4124 (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4125 !supports_cpuid_fault(vcpu)))
4126 return 1;
4127 vcpu->arch.msr_misc_features_enables = data;
4128 break;
4129 #ifdef CONFIG_X86_64
4130 case MSR_IA32_XFD:
4131 if (!msr_info->host_initiated &&
4132 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4133 return 1;
4134
4135 if (data & ~kvm_guest_supported_xfd(vcpu))
4136 return 1;
4137
4138 fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4139 break;
4140 case MSR_IA32_XFD_ERR:
4141 if (!msr_info->host_initiated &&
4142 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4143 return 1;
4144
4145 if (data & ~kvm_guest_supported_xfd(vcpu))
4146 return 1;
4147
4148 vcpu->arch.guest_fpu.xfd_err = data;
4149 break;
4150 #endif
4151 default:
4152 if (kvm_pmu_is_valid_msr(vcpu, msr))
4153 return kvm_pmu_set_msr(vcpu, msr_info);
4154
4155 return KVM_MSR_RET_UNSUPPORTED;
4156 }
4157 return 0;
4158 }
4159 EXPORT_SYMBOL_GPL(kvm_set_msr_common);
4160
get_msr_mce(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)4161 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
4162 {
4163 u64 data;
4164 u64 mcg_cap = vcpu->arch.mcg_cap;
4165 unsigned bank_num = mcg_cap & 0xff;
4166 u32 offset, last_msr;
4167
4168 switch (msr) {
4169 case MSR_IA32_P5_MC_ADDR:
4170 case MSR_IA32_P5_MC_TYPE:
4171 data = 0;
4172 break;
4173 case MSR_IA32_MCG_CAP:
4174 data = vcpu->arch.mcg_cap;
4175 break;
4176 case MSR_IA32_MCG_CTL:
4177 if (!(mcg_cap & MCG_CTL_P) && !host)
4178 return 1;
4179 data = vcpu->arch.mcg_ctl;
4180 break;
4181 case MSR_IA32_MCG_STATUS:
4182 data = vcpu->arch.mcg_status;
4183 break;
4184 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4185 last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4186 if (msr > last_msr)
4187 return 1;
4188
4189 if (!(mcg_cap & MCG_CMCI_P) && !host)
4190 return 1;
4191 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4192 last_msr + 1 - MSR_IA32_MC0_CTL2);
4193 data = vcpu->arch.mci_ctl2_banks[offset];
4194 break;
4195 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4196 last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4197 if (msr > last_msr)
4198 return 1;
4199
4200 offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4201 last_msr + 1 - MSR_IA32_MC0_CTL);
4202 data = vcpu->arch.mce_banks[offset];
4203 break;
4204 default:
4205 return 1;
4206 }
4207 *pdata = data;
4208 return 0;
4209 }
4210
kvm_get_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4211 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4212 {
4213 switch (msr_info->index) {
4214 case MSR_IA32_PLATFORM_ID:
4215 case MSR_IA32_EBL_CR_POWERON:
4216 case MSR_IA32_LASTBRANCHFROMIP:
4217 case MSR_IA32_LASTBRANCHTOIP:
4218 case MSR_IA32_LASTINTFROMIP:
4219 case MSR_IA32_LASTINTTOIP:
4220 case MSR_AMD64_SYSCFG:
4221 case MSR_K8_TSEG_ADDR:
4222 case MSR_K8_TSEG_MASK:
4223 case MSR_VM_HSAVE_PA:
4224 case MSR_K8_INT_PENDING_MSG:
4225 case MSR_AMD64_NB_CFG:
4226 case MSR_FAM10H_MMIO_CONF_BASE:
4227 case MSR_AMD64_BU_CFG2:
4228 case MSR_IA32_PERF_CTL:
4229 case MSR_AMD64_DC_CFG:
4230 case MSR_AMD64_TW_CFG:
4231 case MSR_F15H_EX_CFG:
4232 /*
4233 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4234 * limit) MSRs. Just return 0, as we do not want to expose the host
4235 * data here. Do not conditionalize this on CPUID, as KVM does not do
4236 * so for existing CPU-specific MSRs.
4237 */
4238 case MSR_RAPL_POWER_UNIT:
4239 case MSR_PP0_ENERGY_STATUS: /* Power plane 0 (core) */
4240 case MSR_PP1_ENERGY_STATUS: /* Power plane 1 (graphics uncore) */
4241 case MSR_PKG_ENERGY_STATUS: /* Total package */
4242 case MSR_DRAM_ENERGY_STATUS: /* DRAM controller */
4243 msr_info->data = 0;
4244 break;
4245 case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4246 case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4247 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4248 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4249 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4250 return kvm_pmu_get_msr(vcpu, msr_info);
4251 msr_info->data = 0;
4252 break;
4253 case MSR_IA32_UCODE_REV:
4254 msr_info->data = vcpu->arch.microcode_version;
4255 break;
4256 case MSR_IA32_ARCH_CAPABILITIES:
4257 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4258 return KVM_MSR_RET_UNSUPPORTED;
4259 msr_info->data = vcpu->arch.arch_capabilities;
4260 break;
4261 case MSR_IA32_PERF_CAPABILITIES:
4262 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
4263 return KVM_MSR_RET_UNSUPPORTED;
4264 msr_info->data = vcpu->arch.perf_capabilities;
4265 break;
4266 case MSR_IA32_POWER_CTL:
4267 msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4268 break;
4269 case MSR_IA32_TSC: {
4270 /*
4271 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4272 * even when not intercepted. AMD manual doesn't explicitly
4273 * state this but appears to behave the same.
4274 *
4275 * On userspace reads and writes, however, we unconditionally
4276 * return L1's TSC value to ensure backwards-compatible
4277 * behavior for migration.
4278 */
4279 u64 offset, ratio;
4280
4281 if (msr_info->host_initiated) {
4282 offset = vcpu->arch.l1_tsc_offset;
4283 ratio = vcpu->arch.l1_tsc_scaling_ratio;
4284 } else {
4285 offset = vcpu->arch.tsc_offset;
4286 ratio = vcpu->arch.tsc_scaling_ratio;
4287 }
4288
4289 msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4290 break;
4291 }
4292 case MSR_IA32_CR_PAT:
4293 msr_info->data = vcpu->arch.pat;
4294 break;
4295 case MSR_MTRRcap:
4296 case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4297 case MSR_MTRRdefType:
4298 return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4299 case 0xcd: /* fsb frequency */
4300 msr_info->data = 3;
4301 break;
4302 /*
4303 * MSR_EBC_FREQUENCY_ID
4304 * Conservative value valid for even the basic CPU models.
4305 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4306 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4307 * and 266MHz for model 3, or 4. Set Core Clock
4308 * Frequency to System Bus Frequency Ratio to 1 (bits
4309 * 31:24) even though these are only valid for CPU
4310 * models > 2, however guests may end up dividing or
4311 * multiplying by zero otherwise.
4312 */
4313 case MSR_EBC_FREQUENCY_ID:
4314 msr_info->data = 1 << 24;
4315 break;
4316 case MSR_IA32_APICBASE:
4317 msr_info->data = vcpu->arch.apic_base;
4318 break;
4319 case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4320 return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4321 case MSR_IA32_TSC_DEADLINE:
4322 msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4323 break;
4324 case MSR_IA32_TSC_ADJUST:
4325 msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4326 break;
4327 case MSR_IA32_MISC_ENABLE:
4328 msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4329 break;
4330 case MSR_IA32_SMBASE:
4331 if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4332 return 1;
4333 msr_info->data = vcpu->arch.smbase;
4334 break;
4335 case MSR_SMI_COUNT:
4336 msr_info->data = vcpu->arch.smi_count;
4337 break;
4338 case MSR_IA32_PERF_STATUS:
4339 /* TSC increment by tick */
4340 msr_info->data = 1000ULL;
4341 /* CPU multiplier */
4342 msr_info->data |= (((uint64_t)4ULL) << 40);
4343 break;
4344 case MSR_EFER:
4345 msr_info->data = vcpu->arch.efer;
4346 break;
4347 case MSR_KVM_WALL_CLOCK:
4348 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4349 return 1;
4350
4351 msr_info->data = vcpu->kvm->arch.wall_clock;
4352 break;
4353 case MSR_KVM_WALL_CLOCK_NEW:
4354 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4355 return 1;
4356
4357 msr_info->data = vcpu->kvm->arch.wall_clock;
4358 break;
4359 case MSR_KVM_SYSTEM_TIME:
4360 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4361 return 1;
4362
4363 msr_info->data = vcpu->arch.time;
4364 break;
4365 case MSR_KVM_SYSTEM_TIME_NEW:
4366 if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4367 return 1;
4368
4369 msr_info->data = vcpu->arch.time;
4370 break;
4371 case MSR_KVM_ASYNC_PF_EN:
4372 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4373 return 1;
4374
4375 msr_info->data = vcpu->arch.apf.msr_en_val;
4376 break;
4377 case MSR_KVM_ASYNC_PF_INT:
4378 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4379 return 1;
4380
4381 msr_info->data = vcpu->arch.apf.msr_int_val;
4382 break;
4383 case MSR_KVM_ASYNC_PF_ACK:
4384 if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4385 return 1;
4386
4387 msr_info->data = 0;
4388 break;
4389 case MSR_KVM_STEAL_TIME:
4390 if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4391 return 1;
4392
4393 msr_info->data = vcpu->arch.st.msr_val;
4394 break;
4395 case MSR_KVM_PV_EOI_EN:
4396 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4397 return 1;
4398
4399 msr_info->data = vcpu->arch.pv_eoi.msr_val;
4400 break;
4401 case MSR_KVM_POLL_CONTROL:
4402 if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4403 return 1;
4404
4405 msr_info->data = vcpu->arch.msr_kvm_poll_control;
4406 break;
4407 case MSR_IA32_P5_MC_ADDR:
4408 case MSR_IA32_P5_MC_TYPE:
4409 case MSR_IA32_MCG_CAP:
4410 case MSR_IA32_MCG_CTL:
4411 case MSR_IA32_MCG_STATUS:
4412 case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4413 case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4414 return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4415 msr_info->host_initiated);
4416 case MSR_IA32_XSS:
4417 if (!msr_info->host_initiated &&
4418 !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4419 return 1;
4420 msr_info->data = vcpu->arch.ia32_xss;
4421 break;
4422 case MSR_K7_CLK_CTL:
4423 /*
4424 * Provide expected ramp-up count for K7. All other
4425 * are set to zero, indicating minimum divisors for
4426 * every field.
4427 *
4428 * This prevents guest kernels on AMD host with CPU
4429 * type 6, model 8 and higher from exploding due to
4430 * the rdmsr failing.
4431 */
4432 msr_info->data = 0x20000000;
4433 break;
4434 #ifdef CONFIG_KVM_HYPERV
4435 case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4436 case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4437 case HV_X64_MSR_SYNDBG_OPTIONS:
4438 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4439 case HV_X64_MSR_CRASH_CTL:
4440 case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4441 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4442 case HV_X64_MSR_TSC_EMULATION_CONTROL:
4443 case HV_X64_MSR_TSC_EMULATION_STATUS:
4444 case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4445 return kvm_hv_get_msr_common(vcpu,
4446 msr_info->index, &msr_info->data,
4447 msr_info->host_initiated);
4448 #endif
4449 case MSR_IA32_BBL_CR_CTL3:
4450 /* This legacy MSR exists but isn't fully documented in current
4451 * silicon. It is however accessed by winxp in very narrow
4452 * scenarios where it sets bit #19, itself documented as
4453 * a "reserved" bit. Best effort attempt to source coherent
4454 * read data here should the balance of the register be
4455 * interpreted by the guest:
4456 *
4457 * L2 cache control register 3: 64GB range, 256KB size,
4458 * enabled, latency 0x1, configured
4459 */
4460 msr_info->data = 0xbe702111;
4461 break;
4462 case MSR_AMD64_OSVW_ID_LENGTH:
4463 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4464 return 1;
4465 msr_info->data = vcpu->arch.osvw.length;
4466 break;
4467 case MSR_AMD64_OSVW_STATUS:
4468 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4469 return 1;
4470 msr_info->data = vcpu->arch.osvw.status;
4471 break;
4472 case MSR_PLATFORM_INFO:
4473 if (!msr_info->host_initiated &&
4474 !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4475 return 1;
4476 msr_info->data = vcpu->arch.msr_platform_info;
4477 break;
4478 case MSR_MISC_FEATURES_ENABLES:
4479 msr_info->data = vcpu->arch.msr_misc_features_enables;
4480 break;
4481 case MSR_K7_HWCR:
4482 msr_info->data = vcpu->arch.msr_hwcr;
4483 break;
4484 #ifdef CONFIG_X86_64
4485 case MSR_IA32_XFD:
4486 if (!msr_info->host_initiated &&
4487 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4488 return 1;
4489
4490 msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4491 break;
4492 case MSR_IA32_XFD_ERR:
4493 if (!msr_info->host_initiated &&
4494 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4495 return 1;
4496
4497 msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4498 break;
4499 #endif
4500 default:
4501 if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4502 return kvm_pmu_get_msr(vcpu, msr_info);
4503
4504 return KVM_MSR_RET_UNSUPPORTED;
4505 }
4506 return 0;
4507 }
4508 EXPORT_SYMBOL_GPL(kvm_get_msr_common);
4509
4510 /*
4511 * Read or write a bunch of msrs. All parameters are kernel addresses.
4512 *
4513 * @return number of msrs set successfully.
4514 */
__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))4515 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4516 struct kvm_msr_entry *entries,
4517 int (*do_msr)(struct kvm_vcpu *vcpu,
4518 unsigned index, u64 *data))
4519 {
4520 int i;
4521
4522 for (i = 0; i < msrs->nmsrs; ++i)
4523 if (do_msr(vcpu, entries[i].index, &entries[i].data))
4524 break;
4525
4526 return i;
4527 }
4528
4529 /*
4530 * Read or write a bunch of msrs. Parameters are user addresses.
4531 *
4532 * @return number of msrs set successfully.
4533 */
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)4534 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4535 int (*do_msr)(struct kvm_vcpu *vcpu,
4536 unsigned index, u64 *data),
4537 int writeback)
4538 {
4539 struct kvm_msrs msrs;
4540 struct kvm_msr_entry *entries;
4541 unsigned size;
4542 int r;
4543
4544 r = -EFAULT;
4545 if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4546 goto out;
4547
4548 r = -E2BIG;
4549 if (msrs.nmsrs >= MAX_IO_MSRS)
4550 goto out;
4551
4552 size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4553 entries = memdup_user(user_msrs->entries, size);
4554 if (IS_ERR(entries)) {
4555 r = PTR_ERR(entries);
4556 goto out;
4557 }
4558
4559 r = __msr_io(vcpu, &msrs, entries, do_msr);
4560
4561 if (writeback && copy_to_user(user_msrs->entries, entries, size))
4562 r = -EFAULT;
4563
4564 kfree(entries);
4565 out:
4566 return r;
4567 }
4568
kvm_can_mwait_in_guest(void)4569 static inline bool kvm_can_mwait_in_guest(void)
4570 {
4571 return boot_cpu_has(X86_FEATURE_MWAIT) &&
4572 !boot_cpu_has_bug(X86_BUG_MONITOR) &&
4573 boot_cpu_has(X86_FEATURE_ARAT);
4574 }
4575
kvm_get_allowed_disable_exits(void)4576 static u64 kvm_get_allowed_disable_exits(void)
4577 {
4578 u64 r = KVM_X86_DISABLE_EXITS_PAUSE;
4579
4580 if (!mitigate_smt_rsb) {
4581 r |= KVM_X86_DISABLE_EXITS_HLT |
4582 KVM_X86_DISABLE_EXITS_CSTATE;
4583
4584 if (kvm_can_mwait_in_guest())
4585 r |= KVM_X86_DISABLE_EXITS_MWAIT;
4586 }
4587 return r;
4588 }
4589
4590 #ifdef CONFIG_KVM_HYPERV
kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 __user * cpuid_arg)4591 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4592 struct kvm_cpuid2 __user *cpuid_arg)
4593 {
4594 struct kvm_cpuid2 cpuid;
4595 int r;
4596
4597 r = -EFAULT;
4598 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4599 return r;
4600
4601 r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4602 if (r)
4603 return r;
4604
4605 r = -EFAULT;
4606 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4607 return r;
4608
4609 return 0;
4610 }
4611 #endif
4612
kvm_is_vm_type_supported(unsigned long type)4613 static bool kvm_is_vm_type_supported(unsigned long type)
4614 {
4615 return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
4616 }
4617
kvm_sync_valid_fields(struct kvm * kvm)4618 static inline u64 kvm_sync_valid_fields(struct kvm *kvm)
4619 {
4620 return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
4621 }
4622
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)4623 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4624 {
4625 int r = 0;
4626
4627 switch (ext) {
4628 case KVM_CAP_IRQCHIP:
4629 case KVM_CAP_HLT:
4630 case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4631 case KVM_CAP_SET_TSS_ADDR:
4632 case KVM_CAP_EXT_CPUID:
4633 case KVM_CAP_EXT_EMUL_CPUID:
4634 case KVM_CAP_CLOCKSOURCE:
4635 case KVM_CAP_PIT:
4636 case KVM_CAP_NOP_IO_DELAY:
4637 case KVM_CAP_MP_STATE:
4638 case KVM_CAP_SYNC_MMU:
4639 case KVM_CAP_USER_NMI:
4640 case KVM_CAP_REINJECT_CONTROL:
4641 case KVM_CAP_IRQ_INJECT_STATUS:
4642 case KVM_CAP_IOEVENTFD:
4643 case KVM_CAP_IOEVENTFD_NO_LENGTH:
4644 case KVM_CAP_PIT2:
4645 case KVM_CAP_PIT_STATE2:
4646 case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4647 case KVM_CAP_VCPU_EVENTS:
4648 #ifdef CONFIG_KVM_HYPERV
4649 case KVM_CAP_HYPERV:
4650 case KVM_CAP_HYPERV_VAPIC:
4651 case KVM_CAP_HYPERV_SPIN:
4652 case KVM_CAP_HYPERV_TIME:
4653 case KVM_CAP_HYPERV_SYNIC:
4654 case KVM_CAP_HYPERV_SYNIC2:
4655 case KVM_CAP_HYPERV_VP_INDEX:
4656 case KVM_CAP_HYPERV_EVENTFD:
4657 case KVM_CAP_HYPERV_TLBFLUSH:
4658 case KVM_CAP_HYPERV_SEND_IPI:
4659 case KVM_CAP_HYPERV_CPUID:
4660 case KVM_CAP_HYPERV_ENFORCE_CPUID:
4661 case KVM_CAP_SYS_HYPERV_CPUID:
4662 #endif
4663 case KVM_CAP_PCI_SEGMENT:
4664 case KVM_CAP_DEBUGREGS:
4665 case KVM_CAP_X86_ROBUST_SINGLESTEP:
4666 case KVM_CAP_XSAVE:
4667 case KVM_CAP_ASYNC_PF:
4668 case KVM_CAP_ASYNC_PF_INT:
4669 case KVM_CAP_GET_TSC_KHZ:
4670 case KVM_CAP_KVMCLOCK_CTRL:
4671 case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4672 case KVM_CAP_TSC_DEADLINE_TIMER:
4673 case KVM_CAP_DISABLE_QUIRKS:
4674 case KVM_CAP_SET_BOOT_CPU_ID:
4675 case KVM_CAP_SPLIT_IRQCHIP:
4676 case KVM_CAP_IMMEDIATE_EXIT:
4677 case KVM_CAP_PMU_EVENT_FILTER:
4678 case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
4679 case KVM_CAP_GET_MSR_FEATURES:
4680 case KVM_CAP_MSR_PLATFORM_INFO:
4681 case KVM_CAP_EXCEPTION_PAYLOAD:
4682 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4683 case KVM_CAP_SET_GUEST_DEBUG:
4684 case KVM_CAP_LAST_CPU:
4685 case KVM_CAP_X86_USER_SPACE_MSR:
4686 case KVM_CAP_X86_MSR_FILTER:
4687 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4688 #ifdef CONFIG_X86_SGX_KVM
4689 case KVM_CAP_SGX_ATTRIBUTE:
4690 #endif
4691 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4692 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4693 case KVM_CAP_SREGS2:
4694 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4695 case KVM_CAP_VCPU_ATTRIBUTES:
4696 case KVM_CAP_SYS_ATTRIBUTES:
4697 case KVM_CAP_VAPIC:
4698 case KVM_CAP_ENABLE_CAP:
4699 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4700 case KVM_CAP_IRQFD_RESAMPLE:
4701 case KVM_CAP_MEMORY_FAULT_INFO:
4702 case KVM_CAP_X86_GUEST_MODE:
4703 r = 1;
4704 break;
4705 case KVM_CAP_PRE_FAULT_MEMORY:
4706 r = tdp_enabled;
4707 break;
4708 case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
4709 r = APIC_BUS_CYCLE_NS_DEFAULT;
4710 break;
4711 case KVM_CAP_EXIT_HYPERCALL:
4712 r = KVM_EXIT_HYPERCALL_VALID_MASK;
4713 break;
4714 case KVM_CAP_SET_GUEST_DEBUG2:
4715 return KVM_GUESTDBG_VALID_MASK;
4716 #ifdef CONFIG_KVM_XEN
4717 case KVM_CAP_XEN_HVM:
4718 r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4719 KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4720 KVM_XEN_HVM_CONFIG_SHARED_INFO |
4721 KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4722 KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
4723 KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4724 KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
4725 if (sched_info_on())
4726 r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4727 KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
4728 break;
4729 #endif
4730 case KVM_CAP_SYNC_REGS:
4731 r = kvm_sync_valid_fields(kvm);
4732 break;
4733 case KVM_CAP_ADJUST_CLOCK:
4734 r = KVM_CLOCK_VALID_FLAGS;
4735 break;
4736 case KVM_CAP_X86_DISABLE_EXITS:
4737 r = kvm_get_allowed_disable_exits();
4738 break;
4739 case KVM_CAP_X86_SMM:
4740 if (!IS_ENABLED(CONFIG_KVM_SMM))
4741 break;
4742
4743 /* SMBASE is usually relocated above 1M on modern chipsets,
4744 * and SMM handlers might indeed rely on 4G segment limits,
4745 * so do not report SMM to be available if real mode is
4746 * emulated via vm86 mode. Still, do not go to great lengths
4747 * to avoid userspace's usage of the feature, because it is a
4748 * fringe case that is not enabled except via specific settings
4749 * of the module parameters.
4750 */
4751 r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4752 break;
4753 case KVM_CAP_NR_VCPUS:
4754 r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4755 break;
4756 case KVM_CAP_MAX_VCPUS:
4757 r = KVM_MAX_VCPUS;
4758 if (kvm)
4759 r = kvm->max_vcpus;
4760 break;
4761 case KVM_CAP_MAX_VCPU_ID:
4762 r = KVM_MAX_VCPU_IDS;
4763 break;
4764 case KVM_CAP_PV_MMU: /* obsolete */
4765 r = 0;
4766 break;
4767 case KVM_CAP_MCE:
4768 r = KVM_MAX_MCE_BANKS;
4769 break;
4770 case KVM_CAP_XCRS:
4771 r = boot_cpu_has(X86_FEATURE_XSAVE);
4772 break;
4773 case KVM_CAP_TSC_CONTROL:
4774 case KVM_CAP_VM_TSC_CONTROL:
4775 r = kvm_caps.has_tsc_control;
4776 break;
4777 case KVM_CAP_X2APIC_API:
4778 r = KVM_X2APIC_API_VALID_FLAGS;
4779 break;
4780 case KVM_CAP_NESTED_STATE:
4781 r = kvm_x86_ops.nested_ops->get_state ?
4782 kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4783 break;
4784 #ifdef CONFIG_KVM_HYPERV
4785 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4786 r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
4787 break;
4788 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4789 r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4790 break;
4791 #endif
4792 case KVM_CAP_SMALLER_MAXPHYADDR:
4793 r = (int) allow_smaller_maxphyaddr;
4794 break;
4795 case KVM_CAP_STEAL_TIME:
4796 r = sched_info_on();
4797 break;
4798 case KVM_CAP_X86_BUS_LOCK_EXIT:
4799 if (kvm_caps.has_bus_lock_exit)
4800 r = KVM_BUS_LOCK_DETECTION_OFF |
4801 KVM_BUS_LOCK_DETECTION_EXIT;
4802 else
4803 r = 0;
4804 break;
4805 case KVM_CAP_XSAVE2: {
4806 r = xstate_required_size(kvm_get_filtered_xcr0(), false);
4807 if (r < sizeof(struct kvm_xsave))
4808 r = sizeof(struct kvm_xsave);
4809 break;
4810 }
4811 case KVM_CAP_PMU_CAPABILITY:
4812 r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
4813 break;
4814 case KVM_CAP_DISABLE_QUIRKS2:
4815 r = kvm_caps.supported_quirks;
4816 break;
4817 case KVM_CAP_X86_NOTIFY_VMEXIT:
4818 r = kvm_caps.has_notify_vmexit;
4819 break;
4820 case KVM_CAP_VM_TYPES:
4821 r = kvm_caps.supported_vm_types;
4822 break;
4823 case KVM_CAP_READONLY_MEM:
4824 r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
4825 break;
4826 default:
4827 break;
4828 }
4829 return r;
4830 }
4831
__kvm_x86_dev_get_attr(struct kvm_device_attr * attr,u64 * val)4832 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
4833 {
4834 if (attr->group) {
4835 if (kvm_x86_ops.dev_get_attr)
4836 return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
4837 return -ENXIO;
4838 }
4839
4840 switch (attr->attr) {
4841 case KVM_X86_XCOMP_GUEST_SUPP:
4842 *val = kvm_caps.supported_xcr0;
4843 return 0;
4844 default:
4845 return -ENXIO;
4846 }
4847 }
4848
kvm_x86_dev_get_attr(struct kvm_device_attr * attr)4849 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
4850 {
4851 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
4852 int r;
4853 u64 val;
4854
4855 r = __kvm_x86_dev_get_attr(attr, &val);
4856 if (r < 0)
4857 return r;
4858
4859 if (put_user(val, uaddr))
4860 return -EFAULT;
4861
4862 return 0;
4863 }
4864
kvm_x86_dev_has_attr(struct kvm_device_attr * attr)4865 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
4866 {
4867 u64 val;
4868
4869 return __kvm_x86_dev_get_attr(attr, &val);
4870 }
4871
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)4872 long kvm_arch_dev_ioctl(struct file *filp,
4873 unsigned int ioctl, unsigned long arg)
4874 {
4875 void __user *argp = (void __user *)arg;
4876 long r;
4877
4878 switch (ioctl) {
4879 case KVM_GET_MSR_INDEX_LIST: {
4880 struct kvm_msr_list __user *user_msr_list = argp;
4881 struct kvm_msr_list msr_list;
4882 unsigned n;
4883
4884 r = -EFAULT;
4885 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4886 goto out;
4887 n = msr_list.nmsrs;
4888 msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
4889 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4890 goto out;
4891 r = -E2BIG;
4892 if (n < msr_list.nmsrs)
4893 goto out;
4894 r = -EFAULT;
4895 if (copy_to_user(user_msr_list->indices, &msrs_to_save,
4896 num_msrs_to_save * sizeof(u32)))
4897 goto out;
4898 if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
4899 &emulated_msrs,
4900 num_emulated_msrs * sizeof(u32)))
4901 goto out;
4902 r = 0;
4903 break;
4904 }
4905 case KVM_GET_SUPPORTED_CPUID:
4906 case KVM_GET_EMULATED_CPUID: {
4907 struct kvm_cpuid2 __user *cpuid_arg = argp;
4908 struct kvm_cpuid2 cpuid;
4909
4910 r = -EFAULT;
4911 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4912 goto out;
4913
4914 r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
4915 ioctl);
4916 if (r)
4917 goto out;
4918
4919 r = -EFAULT;
4920 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4921 goto out;
4922 r = 0;
4923 break;
4924 }
4925 case KVM_X86_GET_MCE_CAP_SUPPORTED:
4926 r = -EFAULT;
4927 if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
4928 sizeof(kvm_caps.supported_mce_cap)))
4929 goto out;
4930 r = 0;
4931 break;
4932 case KVM_GET_MSR_FEATURE_INDEX_LIST: {
4933 struct kvm_msr_list __user *user_msr_list = argp;
4934 struct kvm_msr_list msr_list;
4935 unsigned int n;
4936
4937 r = -EFAULT;
4938 if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
4939 goto out;
4940 n = msr_list.nmsrs;
4941 msr_list.nmsrs = num_msr_based_features;
4942 if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
4943 goto out;
4944 r = -E2BIG;
4945 if (n < msr_list.nmsrs)
4946 goto out;
4947 r = -EFAULT;
4948 if (copy_to_user(user_msr_list->indices, &msr_based_features,
4949 num_msr_based_features * sizeof(u32)))
4950 goto out;
4951 r = 0;
4952 break;
4953 }
4954 case KVM_GET_MSRS:
4955 r = msr_io(NULL, argp, do_get_feature_msr, 1);
4956 break;
4957 #ifdef CONFIG_KVM_HYPERV
4958 case KVM_GET_SUPPORTED_HV_CPUID:
4959 r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
4960 break;
4961 #endif
4962 case KVM_GET_DEVICE_ATTR: {
4963 struct kvm_device_attr attr;
4964 r = -EFAULT;
4965 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4966 break;
4967 r = kvm_x86_dev_get_attr(&attr);
4968 break;
4969 }
4970 case KVM_HAS_DEVICE_ATTR: {
4971 struct kvm_device_attr attr;
4972 r = -EFAULT;
4973 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
4974 break;
4975 r = kvm_x86_dev_has_attr(&attr);
4976 break;
4977 }
4978 default:
4979 r = -EINVAL;
4980 break;
4981 }
4982 out:
4983 return r;
4984 }
4985
wbinvd_ipi(void * garbage)4986 static void wbinvd_ipi(void *garbage)
4987 {
4988 wbinvd();
4989 }
4990
need_emulate_wbinvd(struct kvm_vcpu * vcpu)4991 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
4992 {
4993 return kvm_arch_has_noncoherent_dma(vcpu->kvm);
4994 }
4995
4996 static DEFINE_PER_CPU(struct kvm_vcpu *, last_vcpu);
4997
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)4998 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
4999 {
5000 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
5001
5002 vcpu->arch.l1tf_flush_l1d = true;
5003
5004 if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
5005 pmu->need_cleanup = true;
5006 kvm_make_request(KVM_REQ_PMU, vcpu);
5007 }
5008
5009 /* Address WBINVD may be executed by guest */
5010 if (need_emulate_wbinvd(vcpu)) {
5011 if (kvm_x86_call(has_wbinvd_exit)())
5012 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5013 else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
5014 smp_call_function_single(vcpu->cpu,
5015 wbinvd_ipi, NULL, 1);
5016 }
5017
5018 kvm_x86_call(vcpu_load)(vcpu, cpu);
5019
5020 if (vcpu != per_cpu(last_vcpu, cpu)) {
5021 /*
5022 * Flush the branch predictor when switching vCPUs on the same
5023 * physical CPU, as each vCPU needs its own branch prediction
5024 * domain. No IBPB is needed when switching between L1 and L2
5025 * on the same vCPU unless IBRS is advertised to the vCPU; that
5026 * is handled on the nested VM-Exit path.
5027 */
5028 if (static_branch_likely(&switch_vcpu_ibpb))
5029 indirect_branch_prediction_barrier();
5030 per_cpu(last_vcpu, cpu) = vcpu;
5031 }
5032
5033 /* Save host pkru register if supported */
5034 vcpu->arch.host_pkru = read_pkru();
5035
5036 /* Apply any externally detected TSC adjustments (due to suspend) */
5037 if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5038 adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5039 vcpu->arch.tsc_offset_adjustment = 0;
5040 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5041 }
5042
5043 if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
5044 s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
5045 rdtsc() - vcpu->arch.last_host_tsc;
5046 if (tsc_delta < 0)
5047 mark_tsc_unstable("KVM discovered backwards TSC");
5048
5049 if (kvm_check_tsc_unstable()) {
5050 u64 offset = kvm_compute_l1_tsc_offset(vcpu,
5051 vcpu->arch.last_guest_tsc);
5052 kvm_vcpu_write_tsc_offset(vcpu, offset);
5053 if (!vcpu->arch.guest_tsc_protected)
5054 vcpu->arch.tsc_catchup = 1;
5055 }
5056
5057 if (kvm_lapic_hv_timer_in_use(vcpu))
5058 kvm_lapic_restart_hv_timer(vcpu);
5059
5060 /*
5061 * On a host with synchronized TSC, there is no need to update
5062 * kvmclock on vcpu->cpu migration
5063 */
5064 if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
5065 kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
5066 if (vcpu->cpu != cpu)
5067 kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
5068 vcpu->cpu = cpu;
5069 }
5070
5071 kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
5072 }
5073
kvm_steal_time_set_preempted(struct kvm_vcpu * vcpu)5074 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
5075 {
5076 struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
5077 struct kvm_steal_time __user *st;
5078 struct kvm_memslots *slots;
5079 static const u8 preempted = KVM_VCPU_PREEMPTED;
5080 gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
5081
5082 /*
5083 * The vCPU can be marked preempted if and only if the VM-Exit was on
5084 * an instruction boundary and will not trigger guest emulation of any
5085 * kind (see vcpu_run). Vendor specific code controls (conservatively)
5086 * when this is true, for example allowing the vCPU to be marked
5087 * preempted if and only if the VM-Exit was due to a host interrupt.
5088 */
5089 if (!vcpu->arch.at_instruction_boundary) {
5090 vcpu->stat.preemption_other++;
5091 return;
5092 }
5093
5094 vcpu->stat.preemption_reported++;
5095 if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
5096 return;
5097
5098 if (vcpu->arch.st.preempted)
5099 return;
5100
5101 /* This happens on process exit */
5102 if (unlikely(current->mm != vcpu->kvm->mm))
5103 return;
5104
5105 slots = kvm_memslots(vcpu->kvm);
5106
5107 if (unlikely(slots->generation != ghc->generation ||
5108 gpa != ghc->gpa ||
5109 kvm_is_error_hva(ghc->hva) || !ghc->memslot))
5110 return;
5111
5112 st = (struct kvm_steal_time __user *)ghc->hva;
5113 BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
5114
5115 if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
5116 vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
5117
5118 mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
5119 }
5120
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)5121 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
5122 {
5123 int idx;
5124
5125 if (vcpu->preempted) {
5126 /*
5127 * Assume protected guests are in-kernel. Inefficient yielding
5128 * due to false positives is preferable to never yielding due
5129 * to false negatives.
5130 */
5131 vcpu->arch.preempted_in_kernel = vcpu->arch.guest_state_protected ||
5132 !kvm_x86_call(get_cpl_no_cache)(vcpu);
5133
5134 /*
5135 * Take the srcu lock as memslots will be accessed to check the gfn
5136 * cache generation against the memslots generation.
5137 */
5138 idx = srcu_read_lock(&vcpu->kvm->srcu);
5139 if (kvm_xen_msr_enabled(vcpu->kvm))
5140 kvm_xen_runstate_set_preempted(vcpu);
5141 else
5142 kvm_steal_time_set_preempted(vcpu);
5143 srcu_read_unlock(&vcpu->kvm->srcu, idx);
5144 }
5145
5146 kvm_x86_call(vcpu_put)(vcpu);
5147 vcpu->arch.last_host_tsc = rdtsc();
5148 }
5149
kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5150 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5151 struct kvm_lapic_state *s)
5152 {
5153 if (vcpu->arch.apic->guest_apic_protected)
5154 return -EINVAL;
5155
5156 kvm_x86_call(sync_pir_to_irr)(vcpu);
5157
5158 return kvm_apic_get_state(vcpu, s);
5159 }
5160
kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5161 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5162 struct kvm_lapic_state *s)
5163 {
5164 int r;
5165
5166 if (vcpu->arch.apic->guest_apic_protected)
5167 return -EINVAL;
5168
5169 r = kvm_apic_set_state(vcpu, s);
5170 if (r)
5171 return r;
5172 update_cr8_intercept(vcpu);
5173
5174 return 0;
5175 }
5176
kvm_cpu_accept_dm_intr(struct kvm_vcpu * vcpu)5177 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5178 {
5179 /*
5180 * We can accept userspace's request for interrupt injection
5181 * as long as we have a place to store the interrupt number.
5182 * The actual injection will happen when the CPU is able to
5183 * deliver the interrupt.
5184 */
5185 if (kvm_cpu_has_extint(vcpu))
5186 return false;
5187
5188 /* Acknowledging ExtINT does not happen if LINT0 is masked. */
5189 return (!lapic_in_kernel(vcpu) ||
5190 kvm_apic_accept_pic_intr(vcpu));
5191 }
5192
kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu * vcpu)5193 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5194 {
5195 /*
5196 * Do not cause an interrupt window exit if an exception
5197 * is pending or an event needs reinjection; userspace
5198 * might want to inject the interrupt manually using KVM_SET_REGS
5199 * or KVM_SET_SREGS. For that to work, we must be at an
5200 * instruction boundary and with no events half-injected.
5201 */
5202 return (kvm_arch_interrupt_allowed(vcpu) &&
5203 kvm_cpu_accept_dm_intr(vcpu) &&
5204 !kvm_event_needs_reinjection(vcpu) &&
5205 !kvm_is_exception_pending(vcpu));
5206 }
5207
kvm_vcpu_ioctl_interrupt(struct kvm_vcpu * vcpu,struct kvm_interrupt * irq)5208 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5209 struct kvm_interrupt *irq)
5210 {
5211 if (irq->irq >= KVM_NR_INTERRUPTS)
5212 return -EINVAL;
5213
5214 if (!irqchip_in_kernel(vcpu->kvm)) {
5215 kvm_queue_interrupt(vcpu, irq->irq, false);
5216 kvm_make_request(KVM_REQ_EVENT, vcpu);
5217 return 0;
5218 }
5219
5220 /*
5221 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5222 * fail for in-kernel 8259.
5223 */
5224 if (pic_in_kernel(vcpu->kvm))
5225 return -ENXIO;
5226
5227 if (vcpu->arch.pending_external_vector != -1)
5228 return -EEXIST;
5229
5230 vcpu->arch.pending_external_vector = irq->irq;
5231 kvm_make_request(KVM_REQ_EVENT, vcpu);
5232 return 0;
5233 }
5234
kvm_vcpu_ioctl_nmi(struct kvm_vcpu * vcpu)5235 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5236 {
5237 kvm_inject_nmi(vcpu);
5238
5239 return 0;
5240 }
5241
vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu * vcpu,struct kvm_tpr_access_ctl * tac)5242 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5243 struct kvm_tpr_access_ctl *tac)
5244 {
5245 if (tac->flags)
5246 return -EINVAL;
5247 vcpu->arch.tpr_access_reporting = !!tac->enabled;
5248 return 0;
5249 }
5250
kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu * vcpu,u64 mcg_cap)5251 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5252 u64 mcg_cap)
5253 {
5254 int r;
5255 unsigned bank_num = mcg_cap & 0xff, bank;
5256
5257 r = -EINVAL;
5258 if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
5259 goto out;
5260 if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
5261 goto out;
5262 r = 0;
5263 vcpu->arch.mcg_cap = mcg_cap;
5264 /* Init IA32_MCG_CTL to all 1s */
5265 if (mcg_cap & MCG_CTL_P)
5266 vcpu->arch.mcg_ctl = ~(u64)0;
5267 /* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5268 for (bank = 0; bank < bank_num; bank++) {
5269 vcpu->arch.mce_banks[bank*4] = ~(u64)0;
5270 if (mcg_cap & MCG_CMCI_P)
5271 vcpu->arch.mci_ctl2_banks[bank] = 0;
5272 }
5273
5274 kvm_apic_after_set_mcg_cap(vcpu);
5275
5276 kvm_x86_call(setup_mce)(vcpu);
5277 out:
5278 return r;
5279 }
5280
5281 /*
5282 * Validate this is an UCNA (uncorrectable no action) error by checking the
5283 * MCG_STATUS and MCi_STATUS registers:
5284 * - none of the bits for Machine Check Exceptions are set
5285 * - both the VAL (valid) and UC (uncorrectable) bits are set
5286 * MCI_STATUS_PCC - Processor Context Corrupted
5287 * MCI_STATUS_S - Signaled as a Machine Check Exception
5288 * MCI_STATUS_AR - Software recoverable Action Required
5289 */
is_ucna(struct kvm_x86_mce * mce)5290 static bool is_ucna(struct kvm_x86_mce *mce)
5291 {
5292 return !mce->mcg_status &&
5293 !(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5294 (mce->status & MCI_STATUS_VAL) &&
5295 (mce->status & MCI_STATUS_UC);
5296 }
5297
kvm_vcpu_x86_set_ucna(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce,u64 * banks)5298 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5299 {
5300 u64 mcg_cap = vcpu->arch.mcg_cap;
5301
5302 banks[1] = mce->status;
5303 banks[2] = mce->addr;
5304 banks[3] = mce->misc;
5305 vcpu->arch.mcg_status = mce->mcg_status;
5306
5307 if (!(mcg_cap & MCG_CMCI_P) ||
5308 !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5309 return 0;
5310
5311 if (lapic_in_kernel(vcpu))
5312 kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5313
5314 return 0;
5315 }
5316
kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce)5317 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5318 struct kvm_x86_mce *mce)
5319 {
5320 u64 mcg_cap = vcpu->arch.mcg_cap;
5321 unsigned bank_num = mcg_cap & 0xff;
5322 u64 *banks = vcpu->arch.mce_banks;
5323
5324 if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5325 return -EINVAL;
5326
5327 banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5328
5329 if (is_ucna(mce))
5330 return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5331
5332 /*
5333 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5334 * reporting is disabled
5335 */
5336 if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5337 vcpu->arch.mcg_ctl != ~(u64)0)
5338 return 0;
5339 /*
5340 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5341 * reporting is disabled for the bank
5342 */
5343 if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5344 return 0;
5345 if (mce->status & MCI_STATUS_UC) {
5346 if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5347 !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
5348 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5349 return 0;
5350 }
5351 if (banks[1] & MCI_STATUS_VAL)
5352 mce->status |= MCI_STATUS_OVER;
5353 banks[2] = mce->addr;
5354 banks[3] = mce->misc;
5355 vcpu->arch.mcg_status = mce->mcg_status;
5356 banks[1] = mce->status;
5357 kvm_queue_exception(vcpu, MC_VECTOR);
5358 } else if (!(banks[1] & MCI_STATUS_VAL)
5359 || !(banks[1] & MCI_STATUS_UC)) {
5360 if (banks[1] & MCI_STATUS_VAL)
5361 mce->status |= MCI_STATUS_OVER;
5362 banks[2] = mce->addr;
5363 banks[3] = mce->misc;
5364 banks[1] = mce->status;
5365 } else
5366 banks[1] |= MCI_STATUS_OVER;
5367 return 0;
5368 }
5369
kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5370 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5371 struct kvm_vcpu_events *events)
5372 {
5373 struct kvm_queued_exception *ex;
5374
5375 process_nmi(vcpu);
5376
5377 #ifdef CONFIG_KVM_SMM
5378 if (kvm_check_request(KVM_REQ_SMI, vcpu))
5379 process_smi(vcpu);
5380 #endif
5381
5382 /*
5383 * KVM's ABI only allows for one exception to be migrated. Luckily,
5384 * the only time there can be two queued exceptions is if there's a
5385 * non-exiting _injected_ exception, and a pending exiting exception.
5386 * In that case, ignore the VM-Exiting exception as it's an extension
5387 * of the injected exception.
5388 */
5389 if (vcpu->arch.exception_vmexit.pending &&
5390 !vcpu->arch.exception.pending &&
5391 !vcpu->arch.exception.injected)
5392 ex = &vcpu->arch.exception_vmexit;
5393 else
5394 ex = &vcpu->arch.exception;
5395
5396 /*
5397 * In guest mode, payload delivery should be deferred if the exception
5398 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5399 * intercepts #PF, ditto for DR6 and #DBs. If the per-VM capability,
5400 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5401 * propagate the payload and so it cannot be safely deferred. Deliver
5402 * the payload if the capability hasn't been requested.
5403 */
5404 if (!vcpu->kvm->arch.exception_payload_enabled &&
5405 ex->pending && ex->has_payload)
5406 kvm_deliver_exception_payload(vcpu, ex);
5407
5408 memset(events, 0, sizeof(*events));
5409
5410 /*
5411 * The API doesn't provide the instruction length for software
5412 * exceptions, so don't report them. As long as the guest RIP
5413 * isn't advanced, we should expect to encounter the exception
5414 * again.
5415 */
5416 if (!kvm_exception_is_soft(ex->vector)) {
5417 events->exception.injected = ex->injected;
5418 events->exception.pending = ex->pending;
5419 /*
5420 * For ABI compatibility, deliberately conflate
5421 * pending and injected exceptions when
5422 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5423 */
5424 if (!vcpu->kvm->arch.exception_payload_enabled)
5425 events->exception.injected |= ex->pending;
5426 }
5427 events->exception.nr = ex->vector;
5428 events->exception.has_error_code = ex->has_error_code;
5429 events->exception.error_code = ex->error_code;
5430 events->exception_has_payload = ex->has_payload;
5431 events->exception_payload = ex->payload;
5432
5433 events->interrupt.injected =
5434 vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5435 events->interrupt.nr = vcpu->arch.interrupt.nr;
5436 events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
5437
5438 events->nmi.injected = vcpu->arch.nmi_injected;
5439 events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
5440 events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
5441
5442 /* events->sipi_vector is never valid when reporting to user space */
5443
5444 #ifdef CONFIG_KVM_SMM
5445 events->smi.smm = is_smm(vcpu);
5446 events->smi.pending = vcpu->arch.smi_pending;
5447 events->smi.smm_inside_nmi =
5448 !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5449 #endif
5450 events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5451
5452 events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5453 | KVM_VCPUEVENT_VALID_SHADOW
5454 | KVM_VCPUEVENT_VALID_SMM);
5455 if (vcpu->kvm->arch.exception_payload_enabled)
5456 events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5457 if (vcpu->kvm->arch.triple_fault_event) {
5458 events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5459 events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5460 }
5461 }
5462
kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5463 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5464 struct kvm_vcpu_events *events)
5465 {
5466 if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5467 | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5468 | KVM_VCPUEVENT_VALID_SHADOW
5469 | KVM_VCPUEVENT_VALID_SMM
5470 | KVM_VCPUEVENT_VALID_PAYLOAD
5471 | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5472 return -EINVAL;
5473
5474 if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5475 if (!vcpu->kvm->arch.exception_payload_enabled)
5476 return -EINVAL;
5477 if (events->exception.pending)
5478 events->exception.injected = 0;
5479 else
5480 events->exception_has_payload = 0;
5481 } else {
5482 events->exception.pending = 0;
5483 events->exception_has_payload = 0;
5484 }
5485
5486 if ((events->exception.injected || events->exception.pending) &&
5487 (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5488 return -EINVAL;
5489
5490 /* INITs are latched while in SMM */
5491 if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
5492 (events->smi.smm || events->smi.pending) &&
5493 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
5494 return -EINVAL;
5495
5496 process_nmi(vcpu);
5497
5498 /*
5499 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5500 * morph the exception to a VM-Exit if appropriate. Do this only for
5501 * pending exceptions, already-injected exceptions are not subject to
5502 * intercpetion. Note, userspace that conflates pending and injected
5503 * is hosed, and will incorrectly convert an injected exception into a
5504 * pending exception, which in turn may cause a spurious VM-Exit.
5505 */
5506 vcpu->arch.exception_from_userspace = events->exception.pending;
5507
5508 vcpu->arch.exception_vmexit.pending = false;
5509
5510 vcpu->arch.exception.injected = events->exception.injected;
5511 vcpu->arch.exception.pending = events->exception.pending;
5512 vcpu->arch.exception.vector = events->exception.nr;
5513 vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5514 vcpu->arch.exception.error_code = events->exception.error_code;
5515 vcpu->arch.exception.has_payload = events->exception_has_payload;
5516 vcpu->arch.exception.payload = events->exception_payload;
5517
5518 vcpu->arch.interrupt.injected = events->interrupt.injected;
5519 vcpu->arch.interrupt.nr = events->interrupt.nr;
5520 vcpu->arch.interrupt.soft = events->interrupt.soft;
5521 if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5522 kvm_x86_call(set_interrupt_shadow)(vcpu,
5523 events->interrupt.shadow);
5524
5525 vcpu->arch.nmi_injected = events->nmi.injected;
5526 if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
5527 vcpu->arch.nmi_pending = 0;
5528 atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
5529 if (events->nmi.pending)
5530 kvm_make_request(KVM_REQ_NMI, vcpu);
5531 }
5532 kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
5533
5534 if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5535 lapic_in_kernel(vcpu))
5536 vcpu->arch.apic->sipi_vector = events->sipi_vector;
5537
5538 if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5539 #ifdef CONFIG_KVM_SMM
5540 if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5541 kvm_leave_nested(vcpu);
5542 kvm_smm_changed(vcpu, events->smi.smm);
5543 }
5544
5545 vcpu->arch.smi_pending = events->smi.pending;
5546
5547 if (events->smi.smm) {
5548 if (events->smi.smm_inside_nmi)
5549 vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5550 else
5551 vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5552 }
5553
5554 #else
5555 if (events->smi.smm || events->smi.pending ||
5556 events->smi.smm_inside_nmi)
5557 return -EINVAL;
5558 #endif
5559
5560 if (lapic_in_kernel(vcpu)) {
5561 if (events->smi.latched_init)
5562 set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5563 else
5564 clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5565 }
5566 }
5567
5568 if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5569 if (!vcpu->kvm->arch.triple_fault_event)
5570 return -EINVAL;
5571 if (events->triple_fault.pending)
5572 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5573 else
5574 kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5575 }
5576
5577 kvm_make_request(KVM_REQ_EVENT, vcpu);
5578
5579 return 0;
5580 }
5581
kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5582 static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5583 struct kvm_debugregs *dbgregs)
5584 {
5585 unsigned int i;
5586
5587 if (vcpu->kvm->arch.has_protected_state &&
5588 vcpu->arch.guest_state_protected)
5589 return -EINVAL;
5590
5591 memset(dbgregs, 0, sizeof(*dbgregs));
5592
5593 BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5594 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5595 dbgregs->db[i] = vcpu->arch.db[i];
5596
5597 dbgregs->dr6 = vcpu->arch.dr6;
5598 dbgregs->dr7 = vcpu->arch.dr7;
5599 return 0;
5600 }
5601
kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5602 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5603 struct kvm_debugregs *dbgregs)
5604 {
5605 unsigned int i;
5606
5607 if (vcpu->kvm->arch.has_protected_state &&
5608 vcpu->arch.guest_state_protected)
5609 return -EINVAL;
5610
5611 if (dbgregs->flags)
5612 return -EINVAL;
5613
5614 if (!kvm_dr6_valid(dbgregs->dr6))
5615 return -EINVAL;
5616 if (!kvm_dr7_valid(dbgregs->dr7))
5617 return -EINVAL;
5618
5619 for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5620 vcpu->arch.db[i] = dbgregs->db[i];
5621
5622 kvm_update_dr0123(vcpu);
5623 vcpu->arch.dr6 = dbgregs->dr6;
5624 vcpu->arch.dr7 = dbgregs->dr7;
5625 kvm_update_dr7(vcpu);
5626
5627 return 0;
5628 }
5629
5630
kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu * vcpu,u8 * state,unsigned int size)5631 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5632 u8 *state, unsigned int size)
5633 {
5634 /*
5635 * Only copy state for features that are enabled for the guest. The
5636 * state itself isn't problematic, but setting bits in the header for
5637 * features that are supported in *this* host but not exposed to the
5638 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5639 * compatible host without the features that are NOT exposed to the
5640 * guest.
5641 *
5642 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5643 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5644 * supported by the host.
5645 */
5646 u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5647 XFEATURE_MASK_FPSSE;
5648
5649 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5650 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5651
5652 fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5653 supported_xcr0, vcpu->arch.pkru);
5654 return 0;
5655 }
5656
kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5657 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5658 struct kvm_xsave *guest_xsave)
5659 {
5660 return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5661 sizeof(guest_xsave->region));
5662 }
5663
kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5664 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5665 struct kvm_xsave *guest_xsave)
5666 {
5667 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5668 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5669
5670 return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5671 guest_xsave->region,
5672 kvm_caps.supported_xcr0,
5673 &vcpu->arch.pkru);
5674 }
5675
kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5676 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5677 struct kvm_xcrs *guest_xcrs)
5678 {
5679 if (vcpu->kvm->arch.has_protected_state &&
5680 vcpu->arch.guest_state_protected)
5681 return -EINVAL;
5682
5683 if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5684 guest_xcrs->nr_xcrs = 0;
5685 return 0;
5686 }
5687
5688 guest_xcrs->nr_xcrs = 1;
5689 guest_xcrs->flags = 0;
5690 guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5691 guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5692 return 0;
5693 }
5694
kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5695 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5696 struct kvm_xcrs *guest_xcrs)
5697 {
5698 int i, r = 0;
5699
5700 if (vcpu->kvm->arch.has_protected_state &&
5701 vcpu->arch.guest_state_protected)
5702 return -EINVAL;
5703
5704 if (!boot_cpu_has(X86_FEATURE_XSAVE))
5705 return -EINVAL;
5706
5707 if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5708 return -EINVAL;
5709
5710 for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5711 /* Only support XCR0 currently */
5712 if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5713 r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5714 guest_xcrs->xcrs[i].value);
5715 break;
5716 }
5717 if (r)
5718 r = -EINVAL;
5719 return r;
5720 }
5721
5722 /*
5723 * kvm_set_guest_paused() indicates to the guest kernel that it has been
5724 * stopped by the hypervisor. This function will be called from the host only.
5725 * EINVAL is returned when the host attempts to set the flag for a guest that
5726 * does not support pv clocks.
5727 */
kvm_set_guest_paused(struct kvm_vcpu * vcpu)5728 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5729 {
5730 if (!vcpu->arch.pv_time.active)
5731 return -EINVAL;
5732 vcpu->arch.pvclock_set_guest_stopped_request = true;
5733 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5734 return 0;
5735 }
5736
kvm_arch_tsc_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5737 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5738 struct kvm_device_attr *attr)
5739 {
5740 int r;
5741
5742 switch (attr->attr) {
5743 case KVM_VCPU_TSC_OFFSET:
5744 r = 0;
5745 break;
5746 default:
5747 r = -ENXIO;
5748 }
5749
5750 return r;
5751 }
5752
kvm_arch_tsc_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5753 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5754 struct kvm_device_attr *attr)
5755 {
5756 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5757 int r;
5758
5759 switch (attr->attr) {
5760 case KVM_VCPU_TSC_OFFSET:
5761 r = -EFAULT;
5762 if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5763 break;
5764 r = 0;
5765 break;
5766 default:
5767 r = -ENXIO;
5768 }
5769
5770 return r;
5771 }
5772
kvm_arch_tsc_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5773 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5774 struct kvm_device_attr *attr)
5775 {
5776 u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5777 struct kvm *kvm = vcpu->kvm;
5778 int r;
5779
5780 switch (attr->attr) {
5781 case KVM_VCPU_TSC_OFFSET: {
5782 u64 offset, tsc, ns;
5783 unsigned long flags;
5784 bool matched;
5785
5786 r = -EFAULT;
5787 if (get_user(offset, uaddr))
5788 break;
5789
5790 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5791
5792 matched = (vcpu->arch.virtual_tsc_khz &&
5793 kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5794 kvm->arch.last_tsc_offset == offset);
5795
5796 tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5797 ns = get_kvmclock_base_ns();
5798
5799 __kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched, true);
5800 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5801
5802 r = 0;
5803 break;
5804 }
5805 default:
5806 r = -ENXIO;
5807 }
5808
5809 return r;
5810 }
5811
kvm_vcpu_ioctl_device_attr(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)5812 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5813 unsigned int ioctl,
5814 void __user *argp)
5815 {
5816 struct kvm_device_attr attr;
5817 int r;
5818
5819 if (copy_from_user(&attr, argp, sizeof(attr)))
5820 return -EFAULT;
5821
5822 if (attr.group != KVM_VCPU_TSC_CTRL)
5823 return -ENXIO;
5824
5825 switch (ioctl) {
5826 case KVM_HAS_DEVICE_ATTR:
5827 r = kvm_arch_tsc_has_attr(vcpu, &attr);
5828 break;
5829 case KVM_GET_DEVICE_ATTR:
5830 r = kvm_arch_tsc_get_attr(vcpu, &attr);
5831 break;
5832 case KVM_SET_DEVICE_ATTR:
5833 r = kvm_arch_tsc_set_attr(vcpu, &attr);
5834 break;
5835 }
5836
5837 return r;
5838 }
5839
kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu * vcpu,struct kvm_enable_cap * cap)5840 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
5841 struct kvm_enable_cap *cap)
5842 {
5843 if (cap->flags)
5844 return -EINVAL;
5845
5846 switch (cap->cap) {
5847 #ifdef CONFIG_KVM_HYPERV
5848 case KVM_CAP_HYPERV_SYNIC2:
5849 if (cap->args[0])
5850 return -EINVAL;
5851 fallthrough;
5852
5853 case KVM_CAP_HYPERV_SYNIC:
5854 if (!irqchip_in_kernel(vcpu->kvm))
5855 return -EINVAL;
5856 return kvm_hv_activate_synic(vcpu, cap->cap ==
5857 KVM_CAP_HYPERV_SYNIC2);
5858 case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
5859 {
5860 int r;
5861 uint16_t vmcs_version;
5862 void __user *user_ptr;
5863
5864 if (!kvm_x86_ops.nested_ops->enable_evmcs)
5865 return -ENOTTY;
5866 r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
5867 if (!r) {
5868 user_ptr = (void __user *)(uintptr_t)cap->args[0];
5869 if (copy_to_user(user_ptr, &vmcs_version,
5870 sizeof(vmcs_version)))
5871 r = -EFAULT;
5872 }
5873 return r;
5874 }
5875 case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
5876 if (!kvm_x86_ops.enable_l2_tlb_flush)
5877 return -ENOTTY;
5878
5879 return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
5880
5881 case KVM_CAP_HYPERV_ENFORCE_CPUID:
5882 return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
5883 #endif
5884
5885 case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
5886 vcpu->arch.pv_cpuid.enforce = cap->args[0];
5887 return 0;
5888 default:
5889 return -EINVAL;
5890 }
5891 }
5892
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5893 long kvm_arch_vcpu_ioctl(struct file *filp,
5894 unsigned int ioctl, unsigned long arg)
5895 {
5896 struct kvm_vcpu *vcpu = filp->private_data;
5897 void __user *argp = (void __user *)arg;
5898 int r;
5899 union {
5900 struct kvm_sregs2 *sregs2;
5901 struct kvm_lapic_state *lapic;
5902 struct kvm_xsave *xsave;
5903 struct kvm_xcrs *xcrs;
5904 void *buffer;
5905 } u;
5906
5907 vcpu_load(vcpu);
5908
5909 u.buffer = NULL;
5910 switch (ioctl) {
5911 case KVM_GET_LAPIC: {
5912 r = -EINVAL;
5913 if (!lapic_in_kernel(vcpu))
5914 goto out;
5915 u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
5916
5917 r = -ENOMEM;
5918 if (!u.lapic)
5919 goto out;
5920 r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
5921 if (r)
5922 goto out;
5923 r = -EFAULT;
5924 if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
5925 goto out;
5926 r = 0;
5927 break;
5928 }
5929 case KVM_SET_LAPIC: {
5930 r = -EINVAL;
5931 if (!lapic_in_kernel(vcpu))
5932 goto out;
5933 u.lapic = memdup_user(argp, sizeof(*u.lapic));
5934 if (IS_ERR(u.lapic)) {
5935 r = PTR_ERR(u.lapic);
5936 goto out_nofree;
5937 }
5938
5939 r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
5940 break;
5941 }
5942 case KVM_INTERRUPT: {
5943 struct kvm_interrupt irq;
5944
5945 r = -EFAULT;
5946 if (copy_from_user(&irq, argp, sizeof(irq)))
5947 goto out;
5948 r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
5949 break;
5950 }
5951 case KVM_NMI: {
5952 r = kvm_vcpu_ioctl_nmi(vcpu);
5953 break;
5954 }
5955 case KVM_SMI: {
5956 r = kvm_inject_smi(vcpu);
5957 break;
5958 }
5959 case KVM_SET_CPUID: {
5960 struct kvm_cpuid __user *cpuid_arg = argp;
5961 struct kvm_cpuid cpuid;
5962
5963 r = -EFAULT;
5964 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5965 goto out;
5966 r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
5967 break;
5968 }
5969 case KVM_SET_CPUID2: {
5970 struct kvm_cpuid2 __user *cpuid_arg = argp;
5971 struct kvm_cpuid2 cpuid;
5972
5973 r = -EFAULT;
5974 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5975 goto out;
5976 r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
5977 cpuid_arg->entries);
5978 break;
5979 }
5980 case KVM_GET_CPUID2: {
5981 struct kvm_cpuid2 __user *cpuid_arg = argp;
5982 struct kvm_cpuid2 cpuid;
5983
5984 r = -EFAULT;
5985 if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5986 goto out;
5987 r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
5988 cpuid_arg->entries);
5989 if (r)
5990 goto out;
5991 r = -EFAULT;
5992 if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5993 goto out;
5994 r = 0;
5995 break;
5996 }
5997 case KVM_GET_MSRS: {
5998 int idx = srcu_read_lock(&vcpu->kvm->srcu);
5999 r = msr_io(vcpu, argp, do_get_msr, 1);
6000 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6001 break;
6002 }
6003 case KVM_SET_MSRS: {
6004 int idx = srcu_read_lock(&vcpu->kvm->srcu);
6005 r = msr_io(vcpu, argp, do_set_msr, 0);
6006 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6007 break;
6008 }
6009 case KVM_TPR_ACCESS_REPORTING: {
6010 struct kvm_tpr_access_ctl tac;
6011
6012 r = -EFAULT;
6013 if (copy_from_user(&tac, argp, sizeof(tac)))
6014 goto out;
6015 r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
6016 if (r)
6017 goto out;
6018 r = -EFAULT;
6019 if (copy_to_user(argp, &tac, sizeof(tac)))
6020 goto out;
6021 r = 0;
6022 break;
6023 };
6024 case KVM_SET_VAPIC_ADDR: {
6025 struct kvm_vapic_addr va;
6026 int idx;
6027
6028 r = -EINVAL;
6029 if (!lapic_in_kernel(vcpu))
6030 goto out;
6031 r = -EFAULT;
6032 if (copy_from_user(&va, argp, sizeof(va)))
6033 goto out;
6034 idx = srcu_read_lock(&vcpu->kvm->srcu);
6035 r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
6036 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6037 break;
6038 }
6039 case KVM_X86_SETUP_MCE: {
6040 u64 mcg_cap;
6041
6042 r = -EFAULT;
6043 if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
6044 goto out;
6045 r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6046 break;
6047 }
6048 case KVM_X86_SET_MCE: {
6049 struct kvm_x86_mce mce;
6050
6051 r = -EFAULT;
6052 if (copy_from_user(&mce, argp, sizeof(mce)))
6053 goto out;
6054 r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6055 break;
6056 }
6057 case KVM_GET_VCPU_EVENTS: {
6058 struct kvm_vcpu_events events;
6059
6060 kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6061
6062 r = -EFAULT;
6063 if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6064 break;
6065 r = 0;
6066 break;
6067 }
6068 case KVM_SET_VCPU_EVENTS: {
6069 struct kvm_vcpu_events events;
6070
6071 r = -EFAULT;
6072 if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6073 break;
6074
6075 kvm_vcpu_srcu_read_lock(vcpu);
6076 r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
6077 kvm_vcpu_srcu_read_unlock(vcpu);
6078 break;
6079 }
6080 case KVM_GET_DEBUGREGS: {
6081 struct kvm_debugregs dbgregs;
6082
6083 r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6084 if (r < 0)
6085 break;
6086
6087 r = -EFAULT;
6088 if (copy_to_user(argp, &dbgregs,
6089 sizeof(struct kvm_debugregs)))
6090 break;
6091 r = 0;
6092 break;
6093 }
6094 case KVM_SET_DEBUGREGS: {
6095 struct kvm_debugregs dbgregs;
6096
6097 r = -EFAULT;
6098 if (copy_from_user(&dbgregs, argp,
6099 sizeof(struct kvm_debugregs)))
6100 break;
6101
6102 r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6103 break;
6104 }
6105 case KVM_GET_XSAVE: {
6106 r = -EINVAL;
6107 if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6108 break;
6109
6110 u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
6111 r = -ENOMEM;
6112 if (!u.xsave)
6113 break;
6114
6115 r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6116 if (r < 0)
6117 break;
6118
6119 r = -EFAULT;
6120 if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
6121 break;
6122 r = 0;
6123 break;
6124 }
6125 case KVM_SET_XSAVE: {
6126 int size = vcpu->arch.guest_fpu.uabi_size;
6127
6128 u.xsave = memdup_user(argp, size);
6129 if (IS_ERR(u.xsave)) {
6130 r = PTR_ERR(u.xsave);
6131 goto out_nofree;
6132 }
6133
6134 r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
6135 break;
6136 }
6137
6138 case KVM_GET_XSAVE2: {
6139 int size = vcpu->arch.guest_fpu.uabi_size;
6140
6141 u.xsave = kzalloc(size, GFP_KERNEL);
6142 r = -ENOMEM;
6143 if (!u.xsave)
6144 break;
6145
6146 r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6147 if (r < 0)
6148 break;
6149
6150 r = -EFAULT;
6151 if (copy_to_user(argp, u.xsave, size))
6152 break;
6153
6154 r = 0;
6155 break;
6156 }
6157
6158 case KVM_GET_XCRS: {
6159 u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
6160 r = -ENOMEM;
6161 if (!u.xcrs)
6162 break;
6163
6164 r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6165 if (r < 0)
6166 break;
6167
6168 r = -EFAULT;
6169 if (copy_to_user(argp, u.xcrs,
6170 sizeof(struct kvm_xcrs)))
6171 break;
6172 r = 0;
6173 break;
6174 }
6175 case KVM_SET_XCRS: {
6176 u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
6177 if (IS_ERR(u.xcrs)) {
6178 r = PTR_ERR(u.xcrs);
6179 goto out_nofree;
6180 }
6181
6182 r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
6183 break;
6184 }
6185 case KVM_SET_TSC_KHZ: {
6186 u32 user_tsc_khz;
6187
6188 r = -EINVAL;
6189 user_tsc_khz = (u32)arg;
6190
6191 if (kvm_caps.has_tsc_control &&
6192 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6193 goto out;
6194
6195 if (user_tsc_khz == 0)
6196 user_tsc_khz = tsc_khz;
6197
6198 if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6199 r = 0;
6200
6201 goto out;
6202 }
6203 case KVM_GET_TSC_KHZ: {
6204 r = vcpu->arch.virtual_tsc_khz;
6205 goto out;
6206 }
6207 case KVM_KVMCLOCK_CTRL: {
6208 r = kvm_set_guest_paused(vcpu);
6209 goto out;
6210 }
6211 case KVM_ENABLE_CAP: {
6212 struct kvm_enable_cap cap;
6213
6214 r = -EFAULT;
6215 if (copy_from_user(&cap, argp, sizeof(cap)))
6216 goto out;
6217 r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6218 break;
6219 }
6220 case KVM_GET_NESTED_STATE: {
6221 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6222 u32 user_data_size;
6223
6224 r = -EINVAL;
6225 if (!kvm_x86_ops.nested_ops->get_state)
6226 break;
6227
6228 BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
6229 r = -EFAULT;
6230 if (get_user(user_data_size, &user_kvm_nested_state->size))
6231 break;
6232
6233 r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6234 user_data_size);
6235 if (r < 0)
6236 break;
6237
6238 if (r > user_data_size) {
6239 if (put_user(r, &user_kvm_nested_state->size))
6240 r = -EFAULT;
6241 else
6242 r = -E2BIG;
6243 break;
6244 }
6245
6246 r = 0;
6247 break;
6248 }
6249 case KVM_SET_NESTED_STATE: {
6250 struct kvm_nested_state __user *user_kvm_nested_state = argp;
6251 struct kvm_nested_state kvm_state;
6252 int idx;
6253
6254 r = -EINVAL;
6255 if (!kvm_x86_ops.nested_ops->set_state)
6256 break;
6257
6258 r = -EFAULT;
6259 if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
6260 break;
6261
6262 r = -EINVAL;
6263 if (kvm_state.size < sizeof(kvm_state))
6264 break;
6265
6266 if (kvm_state.flags &
6267 ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
6268 | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6269 | KVM_STATE_NESTED_GIF_SET))
6270 break;
6271
6272 /* nested_run_pending implies guest_mode. */
6273 if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6274 && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
6275 break;
6276
6277 idx = srcu_read_lock(&vcpu->kvm->srcu);
6278 r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
6279 srcu_read_unlock(&vcpu->kvm->srcu, idx);
6280 break;
6281 }
6282 #ifdef CONFIG_KVM_HYPERV
6283 case KVM_GET_SUPPORTED_HV_CPUID:
6284 r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
6285 break;
6286 #endif
6287 #ifdef CONFIG_KVM_XEN
6288 case KVM_XEN_VCPU_GET_ATTR: {
6289 struct kvm_xen_vcpu_attr xva;
6290
6291 r = -EFAULT;
6292 if (copy_from_user(&xva, argp, sizeof(xva)))
6293 goto out;
6294 r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6295 if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6296 r = -EFAULT;
6297 break;
6298 }
6299 case KVM_XEN_VCPU_SET_ATTR: {
6300 struct kvm_xen_vcpu_attr xva;
6301
6302 r = -EFAULT;
6303 if (copy_from_user(&xva, argp, sizeof(xva)))
6304 goto out;
6305 r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6306 break;
6307 }
6308 #endif
6309 case KVM_GET_SREGS2: {
6310 r = -EINVAL;
6311 if (vcpu->kvm->arch.has_protected_state &&
6312 vcpu->arch.guest_state_protected)
6313 goto out;
6314
6315 u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
6316 r = -ENOMEM;
6317 if (!u.sregs2)
6318 goto out;
6319 __get_sregs2(vcpu, u.sregs2);
6320 r = -EFAULT;
6321 if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6322 goto out;
6323 r = 0;
6324 break;
6325 }
6326 case KVM_SET_SREGS2: {
6327 r = -EINVAL;
6328 if (vcpu->kvm->arch.has_protected_state &&
6329 vcpu->arch.guest_state_protected)
6330 goto out;
6331
6332 u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6333 if (IS_ERR(u.sregs2)) {
6334 r = PTR_ERR(u.sregs2);
6335 u.sregs2 = NULL;
6336 goto out;
6337 }
6338 r = __set_sregs2(vcpu, u.sregs2);
6339 break;
6340 }
6341 case KVM_HAS_DEVICE_ATTR:
6342 case KVM_GET_DEVICE_ATTR:
6343 case KVM_SET_DEVICE_ATTR:
6344 r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6345 break;
6346 case KVM_MEMORY_ENCRYPT_OP:
6347 r = -ENOTTY;
6348 if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
6349 goto out;
6350 r = kvm_x86_ops.vcpu_mem_enc_ioctl(vcpu, argp);
6351 break;
6352 default:
6353 r = -EINVAL;
6354 }
6355 out:
6356 kfree(u.buffer);
6357 out_nofree:
6358 vcpu_put(vcpu);
6359 return r;
6360 }
6361
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)6362 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6363 {
6364 return VM_FAULT_SIGBUS;
6365 }
6366
kvm_vm_ioctl_set_tss_addr(struct kvm * kvm,unsigned long addr)6367 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6368 {
6369 int ret;
6370
6371 if (addr > (unsigned int)(-3 * PAGE_SIZE))
6372 return -EINVAL;
6373 ret = kvm_x86_call(set_tss_addr)(kvm, addr);
6374 return ret;
6375 }
6376
kvm_vm_ioctl_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)6377 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6378 u64 ident_addr)
6379 {
6380 return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
6381 }
6382
kvm_vm_ioctl_set_nr_mmu_pages(struct kvm * kvm,unsigned long kvm_nr_mmu_pages)6383 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6384 unsigned long kvm_nr_mmu_pages)
6385 {
6386 if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6387 return -EINVAL;
6388
6389 mutex_lock(&kvm->slots_lock);
6390
6391 kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6392 kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6393
6394 mutex_unlock(&kvm->slots_lock);
6395 return 0;
6396 }
6397
kvm_vm_ioctl_get_irqchip(struct kvm * kvm,struct kvm_irqchip * chip)6398 static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6399 {
6400 struct kvm_pic *pic = kvm->arch.vpic;
6401 int r;
6402
6403 r = 0;
6404 switch (chip->chip_id) {
6405 case KVM_IRQCHIP_PIC_MASTER:
6406 memcpy(&chip->chip.pic, &pic->pics[0],
6407 sizeof(struct kvm_pic_state));
6408 break;
6409 case KVM_IRQCHIP_PIC_SLAVE:
6410 memcpy(&chip->chip.pic, &pic->pics[1],
6411 sizeof(struct kvm_pic_state));
6412 break;
6413 case KVM_IRQCHIP_IOAPIC:
6414 kvm_get_ioapic(kvm, &chip->chip.ioapic);
6415 break;
6416 default:
6417 r = -EINVAL;
6418 break;
6419 }
6420 return r;
6421 }
6422
kvm_vm_ioctl_set_irqchip(struct kvm * kvm,struct kvm_irqchip * chip)6423 static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
6424 {
6425 struct kvm_pic *pic = kvm->arch.vpic;
6426 int r;
6427
6428 r = 0;
6429 switch (chip->chip_id) {
6430 case KVM_IRQCHIP_PIC_MASTER:
6431 spin_lock(&pic->lock);
6432 memcpy(&pic->pics[0], &chip->chip.pic,
6433 sizeof(struct kvm_pic_state));
6434 spin_unlock(&pic->lock);
6435 break;
6436 case KVM_IRQCHIP_PIC_SLAVE:
6437 spin_lock(&pic->lock);
6438 memcpy(&pic->pics[1], &chip->chip.pic,
6439 sizeof(struct kvm_pic_state));
6440 spin_unlock(&pic->lock);
6441 break;
6442 case KVM_IRQCHIP_IOAPIC:
6443 kvm_set_ioapic(kvm, &chip->chip.ioapic);
6444 break;
6445 default:
6446 r = -EINVAL;
6447 break;
6448 }
6449 kvm_pic_update_irq(pic);
6450 return r;
6451 }
6452
kvm_vm_ioctl_get_pit(struct kvm * kvm,struct kvm_pit_state * ps)6453 static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6454 {
6455 struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
6456
6457 BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
6458
6459 mutex_lock(&kps->lock);
6460 memcpy(ps, &kps->channels, sizeof(*ps));
6461 mutex_unlock(&kps->lock);
6462 return 0;
6463 }
6464
kvm_vm_ioctl_set_pit(struct kvm * kvm,struct kvm_pit_state * ps)6465 static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
6466 {
6467 int i;
6468 struct kvm_pit *pit = kvm->arch.vpit;
6469
6470 mutex_lock(&pit->pit_state.lock);
6471 memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
6472 for (i = 0; i < 3; i++)
6473 kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
6474 mutex_unlock(&pit->pit_state.lock);
6475 return 0;
6476 }
6477
kvm_vm_ioctl_get_pit2(struct kvm * kvm,struct kvm_pit_state2 * ps)6478 static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6479 {
6480 mutex_lock(&kvm->arch.vpit->pit_state.lock);
6481 memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
6482 sizeof(ps->channels));
6483 ps->flags = kvm->arch.vpit->pit_state.flags;
6484 mutex_unlock(&kvm->arch.vpit->pit_state.lock);
6485 memset(&ps->reserved, 0, sizeof(ps->reserved));
6486 return 0;
6487 }
6488
kvm_vm_ioctl_set_pit2(struct kvm * kvm,struct kvm_pit_state2 * ps)6489 static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
6490 {
6491 int start = 0;
6492 int i;
6493 u32 prev_legacy, cur_legacy;
6494 struct kvm_pit *pit = kvm->arch.vpit;
6495
6496 mutex_lock(&pit->pit_state.lock);
6497 prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
6498 cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
6499 if (!prev_legacy && cur_legacy)
6500 start = 1;
6501 memcpy(&pit->pit_state.channels, &ps->channels,
6502 sizeof(pit->pit_state.channels));
6503 pit->pit_state.flags = ps->flags;
6504 for (i = 0; i < 3; i++)
6505 kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
6506 start && i == 0);
6507 mutex_unlock(&pit->pit_state.lock);
6508 return 0;
6509 }
6510
kvm_vm_ioctl_reinject(struct kvm * kvm,struct kvm_reinject_control * control)6511 static int kvm_vm_ioctl_reinject(struct kvm *kvm,
6512 struct kvm_reinject_control *control)
6513 {
6514 struct kvm_pit *pit = kvm->arch.vpit;
6515
6516 /* pit->pit_state.lock was overloaded to prevent userspace from getting
6517 * an inconsistent state after running multiple KVM_REINJECT_CONTROL
6518 * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
6519 */
6520 mutex_lock(&pit->pit_state.lock);
6521 kvm_pit_set_reinject(pit, control->pit_reinject);
6522 mutex_unlock(&pit->pit_state.lock);
6523
6524 return 0;
6525 }
6526
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)6527 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6528 {
6529
6530 /*
6531 * Flush all CPUs' dirty log buffers to the dirty_bitmap. Called
6532 * before reporting dirty_bitmap to userspace. KVM flushes the buffers
6533 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6534 * VM-Exit.
6535 */
6536 struct kvm_vcpu *vcpu;
6537 unsigned long i;
6538
6539 if (!kvm->arch.cpu_dirty_log_size)
6540 return;
6541
6542 kvm_for_each_vcpu(i, vcpu, kvm)
6543 kvm_vcpu_kick(vcpu);
6544 }
6545
kvm_vm_ioctl_irq_line(struct kvm * kvm,struct kvm_irq_level * irq_event,bool line_status)6546 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
6547 bool line_status)
6548 {
6549 if (!irqchip_in_kernel(kvm))
6550 return -ENXIO;
6551
6552 irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
6553 irq_event->irq, irq_event->level,
6554 line_status);
6555 return 0;
6556 }
6557
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)6558 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6559 struct kvm_enable_cap *cap)
6560 {
6561 int r;
6562
6563 if (cap->flags)
6564 return -EINVAL;
6565
6566 switch (cap->cap) {
6567 case KVM_CAP_DISABLE_QUIRKS2:
6568 r = -EINVAL;
6569 if (cap->args[0] & ~kvm_caps.supported_quirks)
6570 break;
6571 fallthrough;
6572 case KVM_CAP_DISABLE_QUIRKS:
6573 kvm->arch.disabled_quirks |= cap->args[0] & kvm_caps.supported_quirks;
6574 r = 0;
6575 break;
6576 case KVM_CAP_SPLIT_IRQCHIP: {
6577 mutex_lock(&kvm->lock);
6578 r = -EINVAL;
6579 if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6580 goto split_irqchip_unlock;
6581 r = -EEXIST;
6582 if (irqchip_in_kernel(kvm))
6583 goto split_irqchip_unlock;
6584 if (kvm->created_vcpus)
6585 goto split_irqchip_unlock;
6586 /* Pairs with irqchip_in_kernel. */
6587 smp_wmb();
6588 kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6589 kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6590 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6591 r = 0;
6592 split_irqchip_unlock:
6593 mutex_unlock(&kvm->lock);
6594 break;
6595 }
6596 case KVM_CAP_X2APIC_API:
6597 r = -EINVAL;
6598 if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6599 break;
6600
6601 if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6602 kvm->arch.x2apic_format = true;
6603 if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6604 kvm->arch.x2apic_broadcast_quirk_disabled = true;
6605
6606 r = 0;
6607 break;
6608 case KVM_CAP_X86_DISABLE_EXITS:
6609 r = -EINVAL;
6610 if (cap->args[0] & ~kvm_get_allowed_disable_exits())
6611 break;
6612
6613 mutex_lock(&kvm->lock);
6614 if (kvm->created_vcpus)
6615 goto disable_exits_unlock;
6616
6617 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6618 "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6619
6620 if (!mitigate_smt_rsb && boot_cpu_has_bug(X86_BUG_SMT_RSB) &&
6621 cpu_smt_possible() &&
6622 (cap->args[0] & ~KVM_X86_DISABLE_EXITS_PAUSE))
6623 pr_warn_once(SMT_RSB_MSG);
6624
6625 if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
6626 kvm->arch.pause_in_guest = true;
6627 if (cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT)
6628 kvm->arch.mwait_in_guest = true;
6629 if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
6630 kvm->arch.hlt_in_guest = true;
6631 if (cap->args[0] & KVM_X86_DISABLE_EXITS_CSTATE)
6632 kvm->arch.cstate_in_guest = true;
6633 r = 0;
6634 disable_exits_unlock:
6635 mutex_unlock(&kvm->lock);
6636 break;
6637 case KVM_CAP_MSR_PLATFORM_INFO:
6638 kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6639 r = 0;
6640 break;
6641 case KVM_CAP_EXCEPTION_PAYLOAD:
6642 kvm->arch.exception_payload_enabled = cap->args[0];
6643 r = 0;
6644 break;
6645 case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6646 kvm->arch.triple_fault_event = cap->args[0];
6647 r = 0;
6648 break;
6649 case KVM_CAP_X86_USER_SPACE_MSR:
6650 r = -EINVAL;
6651 if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
6652 break;
6653 kvm->arch.user_space_msr_mask = cap->args[0];
6654 r = 0;
6655 break;
6656 case KVM_CAP_X86_BUS_LOCK_EXIT:
6657 r = -EINVAL;
6658 if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6659 break;
6660
6661 if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6662 (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6663 break;
6664
6665 if (kvm_caps.has_bus_lock_exit &&
6666 cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6667 kvm->arch.bus_lock_detection_enabled = true;
6668 r = 0;
6669 break;
6670 #ifdef CONFIG_X86_SGX_KVM
6671 case KVM_CAP_SGX_ATTRIBUTE: {
6672 unsigned long allowed_attributes = 0;
6673
6674 r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6675 if (r)
6676 break;
6677
6678 /* KVM only supports the PROVISIONKEY privileged attribute. */
6679 if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6680 !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6681 kvm->arch.sgx_provisioning_allowed = true;
6682 else
6683 r = -EINVAL;
6684 break;
6685 }
6686 #endif
6687 case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6688 r = -EINVAL;
6689 if (!kvm_x86_ops.vm_copy_enc_context_from)
6690 break;
6691
6692 r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
6693 break;
6694 case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6695 r = -EINVAL;
6696 if (!kvm_x86_ops.vm_move_enc_context_from)
6697 break;
6698
6699 r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
6700 break;
6701 case KVM_CAP_EXIT_HYPERCALL:
6702 if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6703 r = -EINVAL;
6704 break;
6705 }
6706 kvm->arch.hypercall_exit_enabled = cap->args[0];
6707 r = 0;
6708 break;
6709 case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6710 r = -EINVAL;
6711 if (cap->args[0] & ~1)
6712 break;
6713 kvm->arch.exit_on_emulation_error = cap->args[0];
6714 r = 0;
6715 break;
6716 case KVM_CAP_PMU_CAPABILITY:
6717 r = -EINVAL;
6718 if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6719 break;
6720
6721 mutex_lock(&kvm->lock);
6722 if (!kvm->created_vcpus) {
6723 kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6724 r = 0;
6725 }
6726 mutex_unlock(&kvm->lock);
6727 break;
6728 case KVM_CAP_MAX_VCPU_ID:
6729 r = -EINVAL;
6730 if (cap->args[0] > KVM_MAX_VCPU_IDS)
6731 break;
6732
6733 mutex_lock(&kvm->lock);
6734 if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
6735 ;
6736 } else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6737 r = 0;
6738 } else if (!kvm->arch.max_vcpu_ids) {
6739 kvm->arch.max_vcpu_ids = cap->args[0];
6740 r = 0;
6741 }
6742 mutex_unlock(&kvm->lock);
6743 break;
6744 case KVM_CAP_X86_NOTIFY_VMEXIT:
6745 r = -EINVAL;
6746 if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6747 break;
6748 if (!kvm_caps.has_notify_vmexit)
6749 break;
6750 if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6751 break;
6752 mutex_lock(&kvm->lock);
6753 if (!kvm->created_vcpus) {
6754 kvm->arch.notify_window = cap->args[0] >> 32;
6755 kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6756 r = 0;
6757 }
6758 mutex_unlock(&kvm->lock);
6759 break;
6760 case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6761 r = -EINVAL;
6762
6763 /*
6764 * Since the risk of disabling NX hugepages is a guest crashing
6765 * the system, ensure the userspace process has permission to
6766 * reboot the system.
6767 *
6768 * Note that unlike the reboot() syscall, the process must have
6769 * this capability in the root namespace because exposing
6770 * /dev/kvm into a container does not limit the scope of the
6771 * iTLB multihit bug to that container. In other words,
6772 * this must use capable(), not ns_capable().
6773 */
6774 if (!capable(CAP_SYS_BOOT)) {
6775 r = -EPERM;
6776 break;
6777 }
6778
6779 if (cap->args[0])
6780 break;
6781
6782 mutex_lock(&kvm->lock);
6783 if (!kvm->created_vcpus) {
6784 kvm->arch.disable_nx_huge_pages = true;
6785 r = 0;
6786 }
6787 mutex_unlock(&kvm->lock);
6788 break;
6789 case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
6790 u64 bus_cycle_ns = cap->args[0];
6791 u64 unused;
6792
6793 /*
6794 * Guard against overflow in tmict_to_ns(). 128 is the highest
6795 * divide value that can be programmed in APIC_TDCR.
6796 */
6797 r = -EINVAL;
6798 if (!bus_cycle_ns ||
6799 check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
6800 break;
6801
6802 r = 0;
6803 mutex_lock(&kvm->lock);
6804 if (!irqchip_in_kernel(kvm))
6805 r = -ENXIO;
6806 else if (kvm->created_vcpus)
6807 r = -EINVAL;
6808 else
6809 kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
6810 mutex_unlock(&kvm->lock);
6811 break;
6812 }
6813 default:
6814 r = -EINVAL;
6815 break;
6816 }
6817 return r;
6818 }
6819
kvm_alloc_msr_filter(bool default_allow)6820 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6821 {
6822 struct kvm_x86_msr_filter *msr_filter;
6823
6824 msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6825 if (!msr_filter)
6826 return NULL;
6827
6828 msr_filter->default_allow = default_allow;
6829 return msr_filter;
6830 }
6831
kvm_free_msr_filter(struct kvm_x86_msr_filter * msr_filter)6832 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
6833 {
6834 u32 i;
6835
6836 if (!msr_filter)
6837 return;
6838
6839 for (i = 0; i < msr_filter->count; i++)
6840 kfree(msr_filter->ranges[i].bitmap);
6841
6842 kfree(msr_filter);
6843 }
6844
kvm_add_msr_filter(struct kvm_x86_msr_filter * msr_filter,struct kvm_msr_filter_range * user_range)6845 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
6846 struct kvm_msr_filter_range *user_range)
6847 {
6848 unsigned long *bitmap;
6849 size_t bitmap_size;
6850
6851 if (!user_range->nmsrs)
6852 return 0;
6853
6854 if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
6855 return -EINVAL;
6856
6857 if (!user_range->flags)
6858 return -EINVAL;
6859
6860 bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
6861 if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
6862 return -EINVAL;
6863
6864 bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
6865 if (IS_ERR(bitmap))
6866 return PTR_ERR(bitmap);
6867
6868 msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
6869 .flags = user_range->flags,
6870 .base = user_range->base,
6871 .nmsrs = user_range->nmsrs,
6872 .bitmap = bitmap,
6873 };
6874
6875 msr_filter->count++;
6876 return 0;
6877 }
6878
kvm_vm_ioctl_set_msr_filter(struct kvm * kvm,struct kvm_msr_filter * filter)6879 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
6880 struct kvm_msr_filter *filter)
6881 {
6882 struct kvm_x86_msr_filter *new_filter, *old_filter;
6883 bool default_allow;
6884 bool empty = true;
6885 int r;
6886 u32 i;
6887
6888 if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
6889 return -EINVAL;
6890
6891 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
6892 empty &= !filter->ranges[i].nmsrs;
6893
6894 default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
6895 if (empty && !default_allow)
6896 return -EINVAL;
6897
6898 new_filter = kvm_alloc_msr_filter(default_allow);
6899 if (!new_filter)
6900 return -ENOMEM;
6901
6902 for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
6903 r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
6904 if (r) {
6905 kvm_free_msr_filter(new_filter);
6906 return r;
6907 }
6908 }
6909
6910 mutex_lock(&kvm->lock);
6911 old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
6912 mutex_is_locked(&kvm->lock));
6913 mutex_unlock(&kvm->lock);
6914 synchronize_srcu(&kvm->srcu);
6915
6916 kvm_free_msr_filter(old_filter);
6917
6918 kvm_make_all_cpus_request(kvm, KVM_REQ_MSR_FILTER_CHANGED);
6919
6920 return 0;
6921 }
6922
6923 #ifdef CONFIG_KVM_COMPAT
6924 /* for KVM_X86_SET_MSR_FILTER */
6925 struct kvm_msr_filter_range_compat {
6926 __u32 flags;
6927 __u32 nmsrs;
6928 __u32 base;
6929 __u32 bitmap;
6930 };
6931
6932 struct kvm_msr_filter_compat {
6933 __u32 flags;
6934 struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
6935 };
6936
6937 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
6938
kvm_arch_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)6939 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
6940 unsigned long arg)
6941 {
6942 void __user *argp = (void __user *)arg;
6943 struct kvm *kvm = filp->private_data;
6944 long r = -ENOTTY;
6945
6946 switch (ioctl) {
6947 case KVM_X86_SET_MSR_FILTER_COMPAT: {
6948 struct kvm_msr_filter __user *user_msr_filter = argp;
6949 struct kvm_msr_filter_compat filter_compat;
6950 struct kvm_msr_filter filter;
6951 int i;
6952
6953 if (copy_from_user(&filter_compat, user_msr_filter,
6954 sizeof(filter_compat)))
6955 return -EFAULT;
6956
6957 filter.flags = filter_compat.flags;
6958 for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
6959 struct kvm_msr_filter_range_compat *cr;
6960
6961 cr = &filter_compat.ranges[i];
6962 filter.ranges[i] = (struct kvm_msr_filter_range) {
6963 .flags = cr->flags,
6964 .nmsrs = cr->nmsrs,
6965 .base = cr->base,
6966 .bitmap = (__u8 *)(ulong)cr->bitmap,
6967 };
6968 }
6969
6970 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
6971 break;
6972 }
6973 }
6974
6975 return r;
6976 }
6977 #endif
6978
6979 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_arch_suspend_notifier(struct kvm * kvm)6980 static int kvm_arch_suspend_notifier(struct kvm *kvm)
6981 {
6982 struct kvm_vcpu *vcpu;
6983 unsigned long i;
6984
6985 /*
6986 * Ignore the return, marking the guest paused only "fails" if the vCPU
6987 * isn't using kvmclock; continuing on is correct and desirable.
6988 */
6989 kvm_for_each_vcpu(i, vcpu, kvm)
6990 (void)kvm_set_guest_paused(vcpu);
6991
6992 return NOTIFY_DONE;
6993 }
6994
kvm_arch_pm_notifier(struct kvm * kvm,unsigned long state)6995 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
6996 {
6997 switch (state) {
6998 case PM_HIBERNATION_PREPARE:
6999 case PM_SUSPEND_PREPARE:
7000 return kvm_arch_suspend_notifier(kvm);
7001 }
7002
7003 return NOTIFY_DONE;
7004 }
7005 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
7006
kvm_vm_ioctl_get_clock(struct kvm * kvm,void __user * argp)7007 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
7008 {
7009 struct kvm_clock_data data = { 0 };
7010
7011 get_kvmclock(kvm, &data);
7012 if (copy_to_user(argp, &data, sizeof(data)))
7013 return -EFAULT;
7014
7015 return 0;
7016 }
7017
kvm_vm_ioctl_set_clock(struct kvm * kvm,void __user * argp)7018 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
7019 {
7020 struct kvm_arch *ka = &kvm->arch;
7021 struct kvm_clock_data data;
7022 u64 now_raw_ns;
7023
7024 if (copy_from_user(&data, argp, sizeof(data)))
7025 return -EFAULT;
7026
7027 /*
7028 * Only KVM_CLOCK_REALTIME is used, but allow passing the
7029 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
7030 */
7031 if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
7032 return -EINVAL;
7033
7034 kvm_hv_request_tsc_page_update(kvm);
7035 kvm_start_pvclock_update(kvm);
7036 pvclock_update_vm_gtod_copy(kvm);
7037
7038 /*
7039 * This pairs with kvm_guest_time_update(): when masterclock is
7040 * in use, we use master_kernel_ns + kvmclock_offset to set
7041 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
7042 * is slightly ahead) here we risk going negative on unsigned
7043 * 'system_time' when 'data.clock' is very small.
7044 */
7045 if (data.flags & KVM_CLOCK_REALTIME) {
7046 u64 now_real_ns = ktime_get_real_ns();
7047
7048 /*
7049 * Avoid stepping the kvmclock backwards.
7050 */
7051 if (now_real_ns > data.realtime)
7052 data.clock += now_real_ns - data.realtime;
7053 }
7054
7055 if (ka->use_master_clock)
7056 now_raw_ns = ka->master_kernel_ns;
7057 else
7058 now_raw_ns = get_kvmclock_base_ns();
7059 ka->kvmclock_offset = data.clock - now_raw_ns;
7060 kvm_end_pvclock_update(kvm);
7061 return 0;
7062 }
7063
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7064 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
7065 {
7066 struct kvm *kvm = filp->private_data;
7067 void __user *argp = (void __user *)arg;
7068 int r = -ENOTTY;
7069 /*
7070 * This union makes it completely explicit to gcc-3.x
7071 * that these two variables' stack usage should be
7072 * combined, not added together.
7073 */
7074 union {
7075 struct kvm_pit_state ps;
7076 struct kvm_pit_state2 ps2;
7077 struct kvm_pit_config pit_config;
7078 } u;
7079
7080 switch (ioctl) {
7081 case KVM_SET_TSS_ADDR:
7082 r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
7083 break;
7084 case KVM_SET_IDENTITY_MAP_ADDR: {
7085 u64 ident_addr;
7086
7087 mutex_lock(&kvm->lock);
7088 r = -EINVAL;
7089 if (kvm->created_vcpus)
7090 goto set_identity_unlock;
7091 r = -EFAULT;
7092 if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
7093 goto set_identity_unlock;
7094 r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
7095 set_identity_unlock:
7096 mutex_unlock(&kvm->lock);
7097 break;
7098 }
7099 case KVM_SET_NR_MMU_PAGES:
7100 r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
7101 break;
7102 case KVM_CREATE_IRQCHIP: {
7103 mutex_lock(&kvm->lock);
7104
7105 r = -EEXIST;
7106 if (irqchip_in_kernel(kvm))
7107 goto create_irqchip_unlock;
7108
7109 r = -EINVAL;
7110 if (kvm->created_vcpus)
7111 goto create_irqchip_unlock;
7112
7113 r = kvm_pic_init(kvm);
7114 if (r)
7115 goto create_irqchip_unlock;
7116
7117 r = kvm_ioapic_init(kvm);
7118 if (r) {
7119 kvm_pic_destroy(kvm);
7120 goto create_irqchip_unlock;
7121 }
7122
7123 r = kvm_setup_default_irq_routing(kvm);
7124 if (r) {
7125 kvm_ioapic_destroy(kvm);
7126 kvm_pic_destroy(kvm);
7127 goto create_irqchip_unlock;
7128 }
7129 /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
7130 smp_wmb();
7131 kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
7132 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
7133 create_irqchip_unlock:
7134 mutex_unlock(&kvm->lock);
7135 break;
7136 }
7137 case KVM_CREATE_PIT:
7138 u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7139 goto create_pit;
7140 case KVM_CREATE_PIT2:
7141 r = -EFAULT;
7142 if (copy_from_user(&u.pit_config, argp,
7143 sizeof(struct kvm_pit_config)))
7144 goto out;
7145 create_pit:
7146 mutex_lock(&kvm->lock);
7147 r = -EEXIST;
7148 if (kvm->arch.vpit)
7149 goto create_pit_unlock;
7150 r = -ENOENT;
7151 if (!pic_in_kernel(kvm))
7152 goto create_pit_unlock;
7153 r = -ENOMEM;
7154 kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7155 if (kvm->arch.vpit)
7156 r = 0;
7157 create_pit_unlock:
7158 mutex_unlock(&kvm->lock);
7159 break;
7160 case KVM_GET_IRQCHIP: {
7161 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7162 struct kvm_irqchip *chip;
7163
7164 chip = memdup_user(argp, sizeof(*chip));
7165 if (IS_ERR(chip)) {
7166 r = PTR_ERR(chip);
7167 goto out;
7168 }
7169
7170 r = -ENXIO;
7171 if (!irqchip_kernel(kvm))
7172 goto get_irqchip_out;
7173 r = kvm_vm_ioctl_get_irqchip(kvm, chip);
7174 if (r)
7175 goto get_irqchip_out;
7176 r = -EFAULT;
7177 if (copy_to_user(argp, chip, sizeof(*chip)))
7178 goto get_irqchip_out;
7179 r = 0;
7180 get_irqchip_out:
7181 kfree(chip);
7182 break;
7183 }
7184 case KVM_SET_IRQCHIP: {
7185 /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7186 struct kvm_irqchip *chip;
7187
7188 chip = memdup_user(argp, sizeof(*chip));
7189 if (IS_ERR(chip)) {
7190 r = PTR_ERR(chip);
7191 goto out;
7192 }
7193
7194 r = -ENXIO;
7195 if (!irqchip_kernel(kvm))
7196 goto set_irqchip_out;
7197 r = kvm_vm_ioctl_set_irqchip(kvm, chip);
7198 set_irqchip_out:
7199 kfree(chip);
7200 break;
7201 }
7202 case KVM_GET_PIT: {
7203 r = -EFAULT;
7204 if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
7205 goto out;
7206 r = -ENXIO;
7207 if (!kvm->arch.vpit)
7208 goto out;
7209 r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
7210 if (r)
7211 goto out;
7212 r = -EFAULT;
7213 if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
7214 goto out;
7215 r = 0;
7216 break;
7217 }
7218 case KVM_SET_PIT: {
7219 r = -EFAULT;
7220 if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
7221 goto out;
7222 mutex_lock(&kvm->lock);
7223 r = -ENXIO;
7224 if (!kvm->arch.vpit)
7225 goto set_pit_out;
7226 r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7227 set_pit_out:
7228 mutex_unlock(&kvm->lock);
7229 break;
7230 }
7231 case KVM_GET_PIT2: {
7232 r = -ENXIO;
7233 if (!kvm->arch.vpit)
7234 goto out;
7235 r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7236 if (r)
7237 goto out;
7238 r = -EFAULT;
7239 if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7240 goto out;
7241 r = 0;
7242 break;
7243 }
7244 case KVM_SET_PIT2: {
7245 r = -EFAULT;
7246 if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7247 goto out;
7248 mutex_lock(&kvm->lock);
7249 r = -ENXIO;
7250 if (!kvm->arch.vpit)
7251 goto set_pit2_out;
7252 r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7253 set_pit2_out:
7254 mutex_unlock(&kvm->lock);
7255 break;
7256 }
7257 case KVM_REINJECT_CONTROL: {
7258 struct kvm_reinject_control control;
7259 r = -EFAULT;
7260 if (copy_from_user(&control, argp, sizeof(control)))
7261 goto out;
7262 r = -ENXIO;
7263 if (!kvm->arch.vpit)
7264 goto out;
7265 r = kvm_vm_ioctl_reinject(kvm, &control);
7266 break;
7267 }
7268 case KVM_SET_BOOT_CPU_ID:
7269 r = 0;
7270 mutex_lock(&kvm->lock);
7271 if (kvm->created_vcpus)
7272 r = -EBUSY;
7273 else if (arg > KVM_MAX_VCPU_IDS ||
7274 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
7275 r = -EINVAL;
7276 else
7277 kvm->arch.bsp_vcpu_id = arg;
7278 mutex_unlock(&kvm->lock);
7279 break;
7280 #ifdef CONFIG_KVM_XEN
7281 case KVM_XEN_HVM_CONFIG: {
7282 struct kvm_xen_hvm_config xhc;
7283 r = -EFAULT;
7284 if (copy_from_user(&xhc, argp, sizeof(xhc)))
7285 goto out;
7286 r = kvm_xen_hvm_config(kvm, &xhc);
7287 break;
7288 }
7289 case KVM_XEN_HVM_GET_ATTR: {
7290 struct kvm_xen_hvm_attr xha;
7291
7292 r = -EFAULT;
7293 if (copy_from_user(&xha, argp, sizeof(xha)))
7294 goto out;
7295 r = kvm_xen_hvm_get_attr(kvm, &xha);
7296 if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7297 r = -EFAULT;
7298 break;
7299 }
7300 case KVM_XEN_HVM_SET_ATTR: {
7301 struct kvm_xen_hvm_attr xha;
7302
7303 r = -EFAULT;
7304 if (copy_from_user(&xha, argp, sizeof(xha)))
7305 goto out;
7306 r = kvm_xen_hvm_set_attr(kvm, &xha);
7307 break;
7308 }
7309 case KVM_XEN_HVM_EVTCHN_SEND: {
7310 struct kvm_irq_routing_xen_evtchn uxe;
7311
7312 r = -EFAULT;
7313 if (copy_from_user(&uxe, argp, sizeof(uxe)))
7314 goto out;
7315 r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7316 break;
7317 }
7318 #endif
7319 case KVM_SET_CLOCK:
7320 r = kvm_vm_ioctl_set_clock(kvm, argp);
7321 break;
7322 case KVM_GET_CLOCK:
7323 r = kvm_vm_ioctl_get_clock(kvm, argp);
7324 break;
7325 case KVM_SET_TSC_KHZ: {
7326 u32 user_tsc_khz;
7327
7328 r = -EINVAL;
7329 user_tsc_khz = (u32)arg;
7330
7331 if (kvm_caps.has_tsc_control &&
7332 user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
7333 goto out;
7334
7335 if (user_tsc_khz == 0)
7336 user_tsc_khz = tsc_khz;
7337
7338 WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7339 r = 0;
7340
7341 goto out;
7342 }
7343 case KVM_GET_TSC_KHZ: {
7344 r = READ_ONCE(kvm->arch.default_tsc_khz);
7345 goto out;
7346 }
7347 case KVM_MEMORY_ENCRYPT_OP:
7348 r = -ENOTTY;
7349 if (!kvm_x86_ops.mem_enc_ioctl)
7350 goto out;
7351
7352 r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
7353 break;
7354 case KVM_MEMORY_ENCRYPT_REG_REGION: {
7355 struct kvm_enc_region region;
7356
7357 r = -EFAULT;
7358 if (copy_from_user(®ion, argp, sizeof(region)))
7359 goto out;
7360
7361 r = -ENOTTY;
7362 if (!kvm_x86_ops.mem_enc_register_region)
7363 goto out;
7364
7365 r = kvm_x86_call(mem_enc_register_region)(kvm, ®ion);
7366 break;
7367 }
7368 case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7369 struct kvm_enc_region region;
7370
7371 r = -EFAULT;
7372 if (copy_from_user(®ion, argp, sizeof(region)))
7373 goto out;
7374
7375 r = -ENOTTY;
7376 if (!kvm_x86_ops.mem_enc_unregister_region)
7377 goto out;
7378
7379 r = kvm_x86_call(mem_enc_unregister_region)(kvm, ®ion);
7380 break;
7381 }
7382 #ifdef CONFIG_KVM_HYPERV
7383 case KVM_HYPERV_EVENTFD: {
7384 struct kvm_hyperv_eventfd hvevfd;
7385
7386 r = -EFAULT;
7387 if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7388 goto out;
7389 r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7390 break;
7391 }
7392 #endif
7393 case KVM_SET_PMU_EVENT_FILTER:
7394 r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7395 break;
7396 case KVM_X86_SET_MSR_FILTER: {
7397 struct kvm_msr_filter __user *user_msr_filter = argp;
7398 struct kvm_msr_filter filter;
7399
7400 if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7401 return -EFAULT;
7402
7403 r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7404 break;
7405 }
7406 default:
7407 r = -ENOTTY;
7408 }
7409 out:
7410 return r;
7411 }
7412
kvm_probe_feature_msr(u32 msr_index)7413 static void kvm_probe_feature_msr(u32 msr_index)
7414 {
7415 u64 data;
7416
7417 if (kvm_get_feature_msr(NULL, msr_index, &data, true))
7418 return;
7419
7420 msr_based_features[num_msr_based_features++] = msr_index;
7421 }
7422
kvm_probe_msr_to_save(u32 msr_index)7423 static void kvm_probe_msr_to_save(u32 msr_index)
7424 {
7425 u32 dummy[2];
7426
7427 if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7428 return;
7429
7430 /*
7431 * Even MSRs that are valid in the host may not be exposed to guests in
7432 * some cases.
7433 */
7434 switch (msr_index) {
7435 case MSR_IA32_BNDCFGS:
7436 if (!kvm_mpx_supported())
7437 return;
7438 break;
7439 case MSR_TSC_AUX:
7440 if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7441 !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7442 return;
7443 break;
7444 case MSR_IA32_UMWAIT_CONTROL:
7445 if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7446 return;
7447 break;
7448 case MSR_IA32_RTIT_CTL:
7449 case MSR_IA32_RTIT_STATUS:
7450 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7451 return;
7452 break;
7453 case MSR_IA32_RTIT_CR3_MATCH:
7454 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7455 !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7456 return;
7457 break;
7458 case MSR_IA32_RTIT_OUTPUT_BASE:
7459 case MSR_IA32_RTIT_OUTPUT_MASK:
7460 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7461 (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7462 !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7463 return;
7464 break;
7465 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7466 if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7467 (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7468 intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7469 return;
7470 break;
7471 case MSR_ARCH_PERFMON_PERFCTR0 ...
7472 MSR_ARCH_PERFMON_PERFCTR0 + KVM_MAX_NR_GP_COUNTERS - 1:
7473 if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7474 kvm_pmu_cap.num_counters_gp)
7475 return;
7476 break;
7477 case MSR_ARCH_PERFMON_EVENTSEL0 ...
7478 MSR_ARCH_PERFMON_EVENTSEL0 + KVM_MAX_NR_GP_COUNTERS - 1:
7479 if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7480 kvm_pmu_cap.num_counters_gp)
7481 return;
7482 break;
7483 case MSR_ARCH_PERFMON_FIXED_CTR0 ...
7484 MSR_ARCH_PERFMON_FIXED_CTR0 + KVM_MAX_NR_FIXED_COUNTERS - 1:
7485 if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7486 kvm_pmu_cap.num_counters_fixed)
7487 return;
7488 break;
7489 case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7490 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7491 case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7492 if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7493 return;
7494 break;
7495 case MSR_IA32_XFD:
7496 case MSR_IA32_XFD_ERR:
7497 if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7498 return;
7499 break;
7500 case MSR_IA32_TSX_CTRL:
7501 if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7502 return;
7503 break;
7504 default:
7505 break;
7506 }
7507
7508 msrs_to_save[num_msrs_to_save++] = msr_index;
7509 }
7510
kvm_init_msr_lists(void)7511 static void kvm_init_msr_lists(void)
7512 {
7513 unsigned i;
7514
7515 BUILD_BUG_ON_MSG(KVM_MAX_NR_FIXED_COUNTERS != 3,
7516 "Please update the fixed PMCs in msrs_to_save_pmu[]");
7517
7518 num_msrs_to_save = 0;
7519 num_emulated_msrs = 0;
7520 num_msr_based_features = 0;
7521
7522 for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7523 kvm_probe_msr_to_save(msrs_to_save_base[i]);
7524
7525 if (enable_pmu) {
7526 for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7527 kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
7528 }
7529
7530 for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7531 if (!kvm_x86_call(has_emulated_msr)(NULL,
7532 emulated_msrs_all[i]))
7533 continue;
7534
7535 emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7536 }
7537
7538 for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7539 kvm_probe_feature_msr(i);
7540
7541 for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7542 kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
7543 }
7544
vcpu_mmio_write(struct kvm_vcpu * vcpu,gpa_t addr,int len,const void * v)7545 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7546 const void *v)
7547 {
7548 int handled = 0;
7549 int n;
7550
7551 do {
7552 n = min(len, 8);
7553 if (!(lapic_in_kernel(vcpu) &&
7554 !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7555 && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7556 break;
7557 handled += n;
7558 addr += n;
7559 len -= n;
7560 v += n;
7561 } while (len);
7562
7563 return handled;
7564 }
7565
vcpu_mmio_read(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * v)7566 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7567 {
7568 int handled = 0;
7569 int n;
7570
7571 do {
7572 n = min(len, 8);
7573 if (!(lapic_in_kernel(vcpu) &&
7574 !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7575 addr, n, v))
7576 && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7577 break;
7578 trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7579 handled += n;
7580 addr += n;
7581 len -= n;
7582 v += n;
7583 } while (len);
7584
7585 return handled;
7586 }
7587
kvm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7588 void kvm_set_segment(struct kvm_vcpu *vcpu,
7589 struct kvm_segment *var, int seg)
7590 {
7591 kvm_x86_call(set_segment)(vcpu, var, seg);
7592 }
7593
kvm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7594 void kvm_get_segment(struct kvm_vcpu *vcpu,
7595 struct kvm_segment *var, int seg)
7596 {
7597 kvm_x86_call(get_segment)(vcpu, var, seg);
7598 }
7599
translate_nested_gpa(struct kvm_vcpu * vcpu,gpa_t gpa,u64 access,struct x86_exception * exception)7600 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7601 struct x86_exception *exception)
7602 {
7603 struct kvm_mmu *mmu = vcpu->arch.mmu;
7604 gpa_t t_gpa;
7605
7606 BUG_ON(!mmu_is_nested(vcpu));
7607
7608 /* NPT walks are always user-walks */
7609 access |= PFERR_USER_MASK;
7610 t_gpa = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7611
7612 return t_gpa;
7613 }
7614
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7615 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7616 struct x86_exception *exception)
7617 {
7618 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7619
7620 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7621 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7622 }
7623 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_read);
7624
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7625 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7626 struct x86_exception *exception)
7627 {
7628 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7629
7630 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7631 access |= PFERR_WRITE_MASK;
7632 return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7633 }
7634 EXPORT_SYMBOL_GPL(kvm_mmu_gva_to_gpa_write);
7635
7636 /* 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)7637 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7638 struct x86_exception *exception)
7639 {
7640 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7641
7642 return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7643 }
7644
kvm_read_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7645 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7646 struct kvm_vcpu *vcpu, u64 access,
7647 struct x86_exception *exception)
7648 {
7649 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7650 void *data = val;
7651 int r = X86EMUL_CONTINUE;
7652
7653 while (bytes) {
7654 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7655 unsigned offset = addr & (PAGE_SIZE-1);
7656 unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7657 int ret;
7658
7659 if (gpa == INVALID_GPA)
7660 return X86EMUL_PROPAGATE_FAULT;
7661 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7662 offset, toread);
7663 if (ret < 0) {
7664 r = X86EMUL_IO_NEEDED;
7665 goto out;
7666 }
7667
7668 bytes -= toread;
7669 data += toread;
7670 addr += toread;
7671 }
7672 out:
7673 return r;
7674 }
7675
7676 /* 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)7677 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7678 gva_t addr, void *val, unsigned int bytes,
7679 struct x86_exception *exception)
7680 {
7681 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7682 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7683 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7684 unsigned offset;
7685 int ret;
7686
7687 /* Inline kvm_read_guest_virt_helper for speed. */
7688 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7689 exception);
7690 if (unlikely(gpa == INVALID_GPA))
7691 return X86EMUL_PROPAGATE_FAULT;
7692
7693 offset = addr & (PAGE_SIZE-1);
7694 if (WARN_ON(offset + bytes > PAGE_SIZE))
7695 bytes = (unsigned)PAGE_SIZE - offset;
7696 ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7697 offset, bytes);
7698 if (unlikely(ret < 0))
7699 return X86EMUL_IO_NEEDED;
7700
7701 return X86EMUL_CONTINUE;
7702 }
7703
kvm_read_guest_virt(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7704 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7705 gva_t addr, void *val, unsigned int bytes,
7706 struct x86_exception *exception)
7707 {
7708 u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7709
7710 /*
7711 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7712 * is returned, but our callers are not ready for that and they blindly
7713 * call kvm_inject_page_fault. Ensure that they at least do not leak
7714 * uninitialized kernel stack memory into cr2 and error code.
7715 */
7716 memset(exception, 0, sizeof(*exception));
7717 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7718 exception);
7719 }
7720 EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
7721
emulator_read_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7722 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7723 gva_t addr, void *val, unsigned int bytes,
7724 struct x86_exception *exception, bool system)
7725 {
7726 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7727 u64 access = 0;
7728
7729 if (system)
7730 access |= PFERR_IMPLICIT_ACCESS;
7731 else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7732 access |= PFERR_USER_MASK;
7733
7734 return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7735 }
7736
kvm_write_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7737 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7738 struct kvm_vcpu *vcpu, u64 access,
7739 struct x86_exception *exception)
7740 {
7741 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7742 void *data = val;
7743 int r = X86EMUL_CONTINUE;
7744
7745 while (bytes) {
7746 gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7747 unsigned offset = addr & (PAGE_SIZE-1);
7748 unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7749 int ret;
7750
7751 if (gpa == INVALID_GPA)
7752 return X86EMUL_PROPAGATE_FAULT;
7753 ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7754 if (ret < 0) {
7755 r = X86EMUL_IO_NEEDED;
7756 goto out;
7757 }
7758
7759 bytes -= towrite;
7760 data += towrite;
7761 addr += towrite;
7762 }
7763 out:
7764 return r;
7765 }
7766
emulator_write_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7767 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7768 unsigned int bytes, struct x86_exception *exception,
7769 bool system)
7770 {
7771 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7772 u64 access = PFERR_WRITE_MASK;
7773
7774 if (system)
7775 access |= PFERR_IMPLICIT_ACCESS;
7776 else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7777 access |= PFERR_USER_MASK;
7778
7779 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7780 access, exception);
7781 }
7782
kvm_write_guest_virt_system(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7783 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7784 unsigned int bytes, struct x86_exception *exception)
7785 {
7786 /* kvm_write_guest_virt_system can pull in tons of pages. */
7787 vcpu->arch.l1tf_flush_l1d = true;
7788
7789 return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7790 PFERR_WRITE_MASK, exception);
7791 }
7792 EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
7793
kvm_check_emulate_insn(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)7794 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
7795 void *insn, int insn_len)
7796 {
7797 return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
7798 insn, insn_len);
7799 }
7800
handle_ud(struct kvm_vcpu * vcpu)7801 int handle_ud(struct kvm_vcpu *vcpu)
7802 {
7803 static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
7804 int fep_flags = READ_ONCE(force_emulation_prefix);
7805 int emul_type = EMULTYPE_TRAP_UD;
7806 char sig[5]; /* ud2; .ascii "kvm" */
7807 struct x86_exception e;
7808 int r;
7809
7810 r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
7811 if (r != X86EMUL_CONTINUE)
7812 return 1;
7813
7814 if (fep_flags &&
7815 kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
7816 sig, sizeof(sig), &e) == 0 &&
7817 memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
7818 if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
7819 kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
7820 kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
7821 emul_type = EMULTYPE_TRAP_UD_FORCED;
7822 }
7823
7824 return kvm_emulate_instruction(vcpu, emul_type);
7825 }
7826 EXPORT_SYMBOL_GPL(handle_ud);
7827
vcpu_is_mmio_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t gpa,bool write)7828 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7829 gpa_t gpa, bool write)
7830 {
7831 /* For APIC access vmexit */
7832 if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
7833 return 1;
7834
7835 if (vcpu_match_mmio_gpa(vcpu, gpa)) {
7836 trace_vcpu_match_mmio(gva, gpa, write, true);
7837 return 1;
7838 }
7839
7840 return 0;
7841 }
7842
vcpu_mmio_gva_to_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t * gpa,struct x86_exception * exception,bool write)7843 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
7844 gpa_t *gpa, struct x86_exception *exception,
7845 bool write)
7846 {
7847 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7848 u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
7849 | (write ? PFERR_WRITE_MASK : 0);
7850
7851 /*
7852 * currently PKRU is only applied to ept enabled guest so
7853 * there is no pkey in EPT page table for L1 guest or EPT
7854 * shadow page table for L2 guest.
7855 */
7856 if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
7857 !permission_fault(vcpu, vcpu->arch.walk_mmu,
7858 vcpu->arch.mmio_access, 0, access))) {
7859 *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
7860 (gva & (PAGE_SIZE - 1));
7861 trace_vcpu_match_mmio(gva, *gpa, write, false);
7862 return 1;
7863 }
7864
7865 *gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7866
7867 if (*gpa == INVALID_GPA)
7868 return -1;
7869
7870 return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
7871 }
7872
emulator_write_phys(struct kvm_vcpu * vcpu,gpa_t gpa,const void * val,int bytes)7873 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
7874 const void *val, int bytes)
7875 {
7876 int ret;
7877
7878 ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
7879 if (ret < 0)
7880 return 0;
7881 kvm_page_track_write(vcpu, gpa, val, bytes);
7882 return 1;
7883 }
7884
7885 struct read_write_emulator_ops {
7886 int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
7887 int bytes);
7888 int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
7889 void *val, int bytes);
7890 int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7891 int bytes, void *val);
7892 int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
7893 void *val, int bytes);
7894 bool write;
7895 };
7896
read_prepare(struct kvm_vcpu * vcpu,void * val,int bytes)7897 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
7898 {
7899 if (vcpu->mmio_read_completed) {
7900 trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
7901 vcpu->mmio_fragments[0].gpa, val);
7902 vcpu->mmio_read_completed = 0;
7903 return 1;
7904 }
7905
7906 return 0;
7907 }
7908
read_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7909 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7910 void *val, int bytes)
7911 {
7912 return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
7913 }
7914
write_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7915 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
7916 void *val, int bytes)
7917 {
7918 return emulator_write_phys(vcpu, gpa, val, bytes);
7919 }
7920
write_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,int bytes,void * val)7921 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
7922 {
7923 trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
7924 return vcpu_mmio_write(vcpu, gpa, bytes, val);
7925 }
7926
read_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7927 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7928 void *val, int bytes)
7929 {
7930 trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
7931 return X86EMUL_IO_NEEDED;
7932 }
7933
write_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)7934 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
7935 void *val, int bytes)
7936 {
7937 struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
7938
7939 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
7940 return X86EMUL_CONTINUE;
7941 }
7942
7943 static const struct read_write_emulator_ops read_emultor = {
7944 .read_write_prepare = read_prepare,
7945 .read_write_emulate = read_emulate,
7946 .read_write_mmio = vcpu_mmio_read,
7947 .read_write_exit_mmio = read_exit_mmio,
7948 };
7949
7950 static const struct read_write_emulator_ops write_emultor = {
7951 .read_write_emulate = write_emulate,
7952 .read_write_mmio = write_mmio,
7953 .read_write_exit_mmio = write_exit_mmio,
7954 .write = true,
7955 };
7956
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)7957 static int emulator_read_write_onepage(unsigned long addr, void *val,
7958 unsigned int bytes,
7959 struct x86_exception *exception,
7960 struct kvm_vcpu *vcpu,
7961 const struct read_write_emulator_ops *ops)
7962 {
7963 gpa_t gpa;
7964 int handled, ret;
7965 bool write = ops->write;
7966 struct kvm_mmio_fragment *frag;
7967 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
7968
7969 /*
7970 * If the exit was due to a NPF we may already have a GPA.
7971 * If the GPA is present, use it to avoid the GVA to GPA table walk.
7972 * Note, this cannot be used on string operations since string
7973 * operation using rep will only have the initial GPA from the NPF
7974 * occurred.
7975 */
7976 if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
7977 (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
7978 gpa = ctxt->gpa_val;
7979 ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
7980 } else {
7981 ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
7982 if (ret < 0)
7983 return X86EMUL_PROPAGATE_FAULT;
7984 }
7985
7986 if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
7987 return X86EMUL_CONTINUE;
7988
7989 /*
7990 * Is this MMIO handled locally?
7991 */
7992 handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
7993 if (handled == bytes)
7994 return X86EMUL_CONTINUE;
7995
7996 gpa += handled;
7997 bytes -= handled;
7998 val += handled;
7999
8000 WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
8001 frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
8002 frag->gpa = gpa;
8003 frag->data = val;
8004 frag->len = bytes;
8005 return X86EMUL_CONTINUE;
8006 }
8007
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)8008 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
8009 unsigned long addr,
8010 void *val, unsigned int bytes,
8011 struct x86_exception *exception,
8012 const struct read_write_emulator_ops *ops)
8013 {
8014 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8015 gpa_t gpa;
8016 int rc;
8017
8018 if (ops->read_write_prepare &&
8019 ops->read_write_prepare(vcpu, val, bytes))
8020 return X86EMUL_CONTINUE;
8021
8022 vcpu->mmio_nr_fragments = 0;
8023
8024 /* Crossing a page boundary? */
8025 if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
8026 int now;
8027
8028 now = -addr & ~PAGE_MASK;
8029 rc = emulator_read_write_onepage(addr, val, now, exception,
8030 vcpu, ops);
8031
8032 if (rc != X86EMUL_CONTINUE)
8033 return rc;
8034 addr += now;
8035 if (ctxt->mode != X86EMUL_MODE_PROT64)
8036 addr = (u32)addr;
8037 val += now;
8038 bytes -= now;
8039 }
8040
8041 rc = emulator_read_write_onepage(addr, val, bytes, exception,
8042 vcpu, ops);
8043 if (rc != X86EMUL_CONTINUE)
8044 return rc;
8045
8046 if (!vcpu->mmio_nr_fragments)
8047 return X86EMUL_CONTINUE;
8048
8049 gpa = vcpu->mmio_fragments[0].gpa;
8050
8051 vcpu->mmio_needed = 1;
8052 vcpu->mmio_cur_fragment = 0;
8053
8054 vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
8055 vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
8056 vcpu->run->exit_reason = KVM_EXIT_MMIO;
8057 vcpu->run->mmio.phys_addr = gpa;
8058
8059 return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
8060 }
8061
emulator_read_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception)8062 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8063 unsigned long addr,
8064 void *val,
8065 unsigned int bytes,
8066 struct x86_exception *exception)
8067 {
8068 return emulator_read_write(ctxt, addr, val, bytes,
8069 exception, &read_emultor);
8070 }
8071
emulator_write_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * val,unsigned int bytes,struct x86_exception * exception)8072 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
8073 unsigned long addr,
8074 const void *val,
8075 unsigned int bytes,
8076 struct x86_exception *exception)
8077 {
8078 return emulator_read_write(ctxt, addr, (void *)val, bytes,
8079 exception, &write_emultor);
8080 }
8081
8082 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
8083 (__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
8084
emulator_cmpxchg_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * old,const void * new,unsigned int bytes,struct x86_exception * exception)8085 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8086 unsigned long addr,
8087 const void *old,
8088 const void *new,
8089 unsigned int bytes,
8090 struct x86_exception *exception)
8091 {
8092 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8093 u64 page_line_mask;
8094 unsigned long hva;
8095 gpa_t gpa;
8096 int r;
8097
8098 /* guests cmpxchg8b have to be emulated atomically */
8099 if (bytes > 8 || (bytes & (bytes - 1)))
8100 goto emul_write;
8101
8102 gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
8103
8104 if (gpa == INVALID_GPA ||
8105 (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8106 goto emul_write;
8107
8108 /*
8109 * Emulate the atomic as a straight write to avoid #AC if SLD is
8110 * enabled in the host and the access splits a cache line.
8111 */
8112 if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8113 page_line_mask = ~(cache_line_size() - 1);
8114 else
8115 page_line_mask = PAGE_MASK;
8116
8117 if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
8118 goto emul_write;
8119
8120 hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
8121 if (kvm_is_error_hva(hva))
8122 goto emul_write;
8123
8124 hva += offset_in_page(gpa);
8125
8126 switch (bytes) {
8127 case 1:
8128 r = emulator_try_cmpxchg_user(u8, hva, old, new);
8129 break;
8130 case 2:
8131 r = emulator_try_cmpxchg_user(u16, hva, old, new);
8132 break;
8133 case 4:
8134 r = emulator_try_cmpxchg_user(u32, hva, old, new);
8135 break;
8136 case 8:
8137 r = emulator_try_cmpxchg_user(u64, hva, old, new);
8138 break;
8139 default:
8140 BUG();
8141 }
8142
8143 if (r < 0)
8144 return X86EMUL_UNHANDLEABLE;
8145
8146 /*
8147 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8148 * successful, as the old value is written back on failure. Note, for
8149 * live migration, this is unnecessarily conservative as CMPXCHG writes
8150 * back the original value and the access is atomic, but KVM's ABI is
8151 * that all writes are dirty logged, regardless of the value written.
8152 */
8153 kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8154
8155 if (r)
8156 return X86EMUL_CMPXCHG_FAILED;
8157
8158 kvm_page_track_write(vcpu, gpa, new, bytes);
8159
8160 return X86EMUL_CONTINUE;
8161
8162 emul_write:
8163 pr_warn_once("emulating exchange as write\n");
8164
8165 return emulator_write_emulated(ctxt, addr, new, bytes, exception);
8166 }
8167
emulator_pio_in_out(struct kvm_vcpu * vcpu,int size,unsigned short port,void * data,unsigned int count,bool in)8168 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
8169 unsigned short port, void *data,
8170 unsigned int count, bool in)
8171 {
8172 unsigned i;
8173 int r;
8174
8175 WARN_ON_ONCE(vcpu->arch.pio.count);
8176 for (i = 0; i < count; i++) {
8177 if (in)
8178 r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
8179 else
8180 r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
8181
8182 if (r) {
8183 if (i == 0)
8184 goto userspace_io;
8185
8186 /*
8187 * Userspace must have unregistered the device while PIO
8188 * was running. Drop writes / read as 0.
8189 */
8190 if (in)
8191 memset(data, 0, size * (count - i));
8192 break;
8193 }
8194
8195 data += size;
8196 }
8197 return 1;
8198
8199 userspace_io:
8200 vcpu->arch.pio.port = port;
8201 vcpu->arch.pio.in = in;
8202 vcpu->arch.pio.count = count;
8203 vcpu->arch.pio.size = size;
8204
8205 if (in)
8206 memset(vcpu->arch.pio_data, 0, size * count);
8207 else
8208 memcpy(vcpu->arch.pio_data, data, size * count);
8209
8210 vcpu->run->exit_reason = KVM_EXIT_IO;
8211 vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
8212 vcpu->run->io.size = size;
8213 vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8214 vcpu->run->io.count = count;
8215 vcpu->run->io.port = port;
8216 return 0;
8217 }
8218
emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,void * val,unsigned int count)8219 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8220 unsigned short port, void *val, unsigned int count)
8221 {
8222 int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8223 if (r)
8224 trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8225
8226 return r;
8227 }
8228
complete_emulator_pio_in(struct kvm_vcpu * vcpu,void * val)8229 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
8230 {
8231 int size = vcpu->arch.pio.size;
8232 unsigned int count = vcpu->arch.pio.count;
8233 memcpy(val, vcpu->arch.pio_data, size * count);
8234 trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
8235 vcpu->arch.pio.count = 0;
8236 }
8237
emulator_pio_in_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,void * val,unsigned int count)8238 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8239 int size, unsigned short port, void *val,
8240 unsigned int count)
8241 {
8242 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8243 if (vcpu->arch.pio.count) {
8244 /*
8245 * Complete a previous iteration that required userspace I/O.
8246 * Note, @count isn't guaranteed to match pio.count as userspace
8247 * can modify ECX before rerunning the vCPU. Ignore any such
8248 * shenanigans as KVM doesn't support modifying the rep count,
8249 * and the emulator ensures @count doesn't overflow the buffer.
8250 */
8251 complete_emulator_pio_in(vcpu, val);
8252 return 1;
8253 }
8254
8255 return emulator_pio_in(vcpu, size, port, val, count);
8256 }
8257
emulator_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port,const void * val,unsigned int count)8258 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8259 unsigned short port, const void *val,
8260 unsigned int count)
8261 {
8262 trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
8263 return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
8264 }
8265
emulator_pio_out_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,const void * val,unsigned int count)8266 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8267 int size, unsigned short port,
8268 const void *val, unsigned int count)
8269 {
8270 return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8271 }
8272
get_segment_base(struct kvm_vcpu * vcpu,int seg)8273 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8274 {
8275 return kvm_x86_call(get_segment_base)(vcpu, seg);
8276 }
8277
emulator_invlpg(struct x86_emulate_ctxt * ctxt,ulong address)8278 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
8279 {
8280 kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
8281 }
8282
kvm_emulate_wbinvd_noskip(struct kvm_vcpu * vcpu)8283 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
8284 {
8285 if (!need_emulate_wbinvd(vcpu))
8286 return X86EMUL_CONTINUE;
8287
8288 if (kvm_x86_call(has_wbinvd_exit)()) {
8289 int cpu = get_cpu();
8290
8291 cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
8292 on_each_cpu_mask(vcpu->arch.wbinvd_dirty_mask,
8293 wbinvd_ipi, NULL, 1);
8294 put_cpu();
8295 cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
8296 } else
8297 wbinvd();
8298 return X86EMUL_CONTINUE;
8299 }
8300
kvm_emulate_wbinvd(struct kvm_vcpu * vcpu)8301 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8302 {
8303 kvm_emulate_wbinvd_noskip(vcpu);
8304 return kvm_skip_emulated_instruction(vcpu);
8305 }
8306 EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
8307
8308
8309
emulator_wbinvd(struct x86_emulate_ctxt * ctxt)8310 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8311 {
8312 kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
8313 }
8314
emulator_get_dr(struct x86_emulate_ctxt * ctxt,int dr)8315 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
8316 {
8317 return kvm_get_dr(emul_to_vcpu(ctxt), dr);
8318 }
8319
emulator_set_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long value)8320 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8321 unsigned long value)
8322 {
8323
8324 return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
8325 }
8326
mk_cr_64(u64 curr_cr,u32 new_val)8327 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
8328 {
8329 return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
8330 }
8331
emulator_get_cr(struct x86_emulate_ctxt * ctxt,int cr)8332 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
8333 {
8334 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8335 unsigned long value;
8336
8337 switch (cr) {
8338 case 0:
8339 value = kvm_read_cr0(vcpu);
8340 break;
8341 case 2:
8342 value = vcpu->arch.cr2;
8343 break;
8344 case 3:
8345 value = kvm_read_cr3(vcpu);
8346 break;
8347 case 4:
8348 value = kvm_read_cr4(vcpu);
8349 break;
8350 case 8:
8351 value = kvm_get_cr8(vcpu);
8352 break;
8353 default:
8354 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8355 return 0;
8356 }
8357
8358 return value;
8359 }
8360
emulator_set_cr(struct x86_emulate_ctxt * ctxt,int cr,ulong val)8361 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
8362 {
8363 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8364 int res = 0;
8365
8366 switch (cr) {
8367 case 0:
8368 res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
8369 break;
8370 case 2:
8371 vcpu->arch.cr2 = val;
8372 break;
8373 case 3:
8374 res = kvm_set_cr3(vcpu, val);
8375 break;
8376 case 4:
8377 res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
8378 break;
8379 case 8:
8380 res = kvm_set_cr8(vcpu, val);
8381 break;
8382 default:
8383 kvm_err("%s: unexpected cr %u\n", __func__, cr);
8384 res = -1;
8385 }
8386
8387 return res;
8388 }
8389
emulator_get_cpl(struct x86_emulate_ctxt * ctxt)8390 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8391 {
8392 return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
8393 }
8394
emulator_get_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8395 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8396 {
8397 kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
8398 }
8399
emulator_get_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8400 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8401 {
8402 kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
8403 }
8404
emulator_set_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8405 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8406 {
8407 kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
8408 }
8409
emulator_set_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8410 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8411 {
8412 kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
8413 }
8414
emulator_get_cached_segment_base(struct x86_emulate_ctxt * ctxt,int seg)8415 static unsigned long emulator_get_cached_segment_base(
8416 struct x86_emulate_ctxt *ctxt, int seg)
8417 {
8418 return get_segment_base(emul_to_vcpu(ctxt), seg);
8419 }
8420
emulator_get_segment(struct x86_emulate_ctxt * ctxt,u16 * selector,struct desc_struct * desc,u32 * base3,int seg)8421 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8422 struct desc_struct *desc, u32 *base3,
8423 int seg)
8424 {
8425 struct kvm_segment var;
8426
8427 kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8428 *selector = var.selector;
8429
8430 if (var.unusable) {
8431 memset(desc, 0, sizeof(*desc));
8432 if (base3)
8433 *base3 = 0;
8434 return false;
8435 }
8436
8437 if (var.g)
8438 var.limit >>= 12;
8439 set_desc_limit(desc, var.limit);
8440 set_desc_base(desc, (unsigned long)var.base);
8441 #ifdef CONFIG_X86_64
8442 if (base3)
8443 *base3 = var.base >> 32;
8444 #endif
8445 desc->type = var.type;
8446 desc->s = var.s;
8447 desc->dpl = var.dpl;
8448 desc->p = var.present;
8449 desc->avl = var.avl;
8450 desc->l = var.l;
8451 desc->d = var.db;
8452 desc->g = var.g;
8453
8454 return true;
8455 }
8456
emulator_set_segment(struct x86_emulate_ctxt * ctxt,u16 selector,struct desc_struct * desc,u32 base3,int seg)8457 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8458 struct desc_struct *desc, u32 base3,
8459 int seg)
8460 {
8461 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8462 struct kvm_segment var;
8463
8464 var.selector = selector;
8465 var.base = get_desc_base(desc);
8466 #ifdef CONFIG_X86_64
8467 var.base |= ((u64)base3) << 32;
8468 #endif
8469 var.limit = get_desc_limit(desc);
8470 if (desc->g)
8471 var.limit = (var.limit << 12) | 0xfff;
8472 var.type = desc->type;
8473 var.dpl = desc->dpl;
8474 var.db = desc->d;
8475 var.s = desc->s;
8476 var.l = desc->l;
8477 var.g = desc->g;
8478 var.avl = desc->avl;
8479 var.present = desc->p;
8480 var.unusable = !var.present;
8481 var.padding = 0;
8482
8483 kvm_set_segment(vcpu, &var, seg);
8484 return;
8485 }
8486
emulator_get_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8487 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8488 u32 msr_index, u64 *pdata)
8489 {
8490 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8491 int r;
8492
8493 r = kvm_get_msr_with_filter(vcpu, msr_index, pdata);
8494 if (r < 0)
8495 return X86EMUL_UNHANDLEABLE;
8496
8497 if (r) {
8498 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8499 complete_emulated_rdmsr, r))
8500 return X86EMUL_IO_NEEDED;
8501
8502 trace_kvm_msr_read_ex(msr_index);
8503 return X86EMUL_PROPAGATE_FAULT;
8504 }
8505
8506 trace_kvm_msr_read(msr_index, *pdata);
8507 return X86EMUL_CONTINUE;
8508 }
8509
emulator_set_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)8510 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8511 u32 msr_index, u64 data)
8512 {
8513 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8514 int r;
8515
8516 r = kvm_set_msr_with_filter(vcpu, msr_index, data);
8517 if (r < 0)
8518 return X86EMUL_UNHANDLEABLE;
8519
8520 if (r) {
8521 if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8522 complete_emulated_msr_access, r))
8523 return X86EMUL_IO_NEEDED;
8524
8525 trace_kvm_msr_write_ex(msr_index, data);
8526 return X86EMUL_PROPAGATE_FAULT;
8527 }
8528
8529 trace_kvm_msr_write(msr_index, data);
8530 return X86EMUL_CONTINUE;
8531 }
8532
emulator_get_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8533 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8534 u32 msr_index, u64 *pdata)
8535 {
8536 return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
8537 }
8538
emulator_check_rdpmc_early(struct x86_emulate_ctxt * ctxt,u32 pmc)8539 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
8540 {
8541 return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
8542 }
8543
emulator_read_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc,u64 * pdata)8544 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8545 u32 pmc, u64 *pdata)
8546 {
8547 return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8548 }
8549
emulator_halt(struct x86_emulate_ctxt * ctxt)8550 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8551 {
8552 emul_to_vcpu(ctxt)->arch.halt_request = 1;
8553 }
8554
emulator_intercept(struct x86_emulate_ctxt * ctxt,struct x86_instruction_info * info,enum x86_intercept_stage stage)8555 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8556 struct x86_instruction_info *info,
8557 enum x86_intercept_stage stage)
8558 {
8559 return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
8560 &ctxt->exception);
8561 }
8562
emulator_get_cpuid(struct x86_emulate_ctxt * ctxt,u32 * eax,u32 * ebx,u32 * ecx,u32 * edx,bool exact_only)8563 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8564 u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8565 bool exact_only)
8566 {
8567 return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8568 }
8569
emulator_guest_has_movbe(struct x86_emulate_ctxt * ctxt)8570 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8571 {
8572 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8573 }
8574
emulator_guest_has_fxsr(struct x86_emulate_ctxt * ctxt)8575 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8576 {
8577 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8578 }
8579
emulator_guest_has_rdpid(struct x86_emulate_ctxt * ctxt)8580 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8581 {
8582 return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8583 }
8584
emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt * ctxt)8585 static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
8586 {
8587 return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
8588 }
8589
emulator_read_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg)8590 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8591 {
8592 return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8593 }
8594
emulator_write_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg,ulong val)8595 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8596 {
8597 kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8598 }
8599
emulator_set_nmi_mask(struct x86_emulate_ctxt * ctxt,bool masked)8600 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8601 {
8602 kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8603 }
8604
emulator_is_smm(struct x86_emulate_ctxt * ctxt)8605 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
8606 {
8607 return is_smm(emul_to_vcpu(ctxt));
8608 }
8609
emulator_is_guest_mode(struct x86_emulate_ctxt * ctxt)8610 static bool emulator_is_guest_mode(struct x86_emulate_ctxt *ctxt)
8611 {
8612 return is_guest_mode(emul_to_vcpu(ctxt));
8613 }
8614
8615 #ifndef CONFIG_KVM_SMM
emulator_leave_smm(struct x86_emulate_ctxt * ctxt)8616 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8617 {
8618 WARN_ON_ONCE(1);
8619 return X86EMUL_UNHANDLEABLE;
8620 }
8621 #endif
8622
emulator_triple_fault(struct x86_emulate_ctxt * ctxt)8623 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8624 {
8625 kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8626 }
8627
emulator_set_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 xcr)8628 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8629 {
8630 return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8631 }
8632
emulator_vm_bugged(struct x86_emulate_ctxt * ctxt)8633 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8634 {
8635 struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8636
8637 if (!kvm->vm_bugged)
8638 kvm_vm_bugged(kvm);
8639 }
8640
emulator_get_untagged_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8641 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8642 gva_t addr, unsigned int flags)
8643 {
8644 if (!kvm_x86_ops.get_untagged_addr)
8645 return addr;
8646
8647 return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
8648 addr, flags);
8649 }
8650
emulator_is_canonical_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8651 static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
8652 gva_t addr, unsigned int flags)
8653 {
8654 return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
8655 }
8656
8657 static const struct x86_emulate_ops emulate_ops = {
8658 .vm_bugged = emulator_vm_bugged,
8659 .read_gpr = emulator_read_gpr,
8660 .write_gpr = emulator_write_gpr,
8661 .read_std = emulator_read_std,
8662 .write_std = emulator_write_std,
8663 .fetch = kvm_fetch_guest_virt,
8664 .read_emulated = emulator_read_emulated,
8665 .write_emulated = emulator_write_emulated,
8666 .cmpxchg_emulated = emulator_cmpxchg_emulated,
8667 .invlpg = emulator_invlpg,
8668 .pio_in_emulated = emulator_pio_in_emulated,
8669 .pio_out_emulated = emulator_pio_out_emulated,
8670 .get_segment = emulator_get_segment,
8671 .set_segment = emulator_set_segment,
8672 .get_cached_segment_base = emulator_get_cached_segment_base,
8673 .get_gdt = emulator_get_gdt,
8674 .get_idt = emulator_get_idt,
8675 .set_gdt = emulator_set_gdt,
8676 .set_idt = emulator_set_idt,
8677 .get_cr = emulator_get_cr,
8678 .set_cr = emulator_set_cr,
8679 .cpl = emulator_get_cpl,
8680 .get_dr = emulator_get_dr,
8681 .set_dr = emulator_set_dr,
8682 .set_msr_with_filter = emulator_set_msr_with_filter,
8683 .get_msr_with_filter = emulator_get_msr_with_filter,
8684 .get_msr = emulator_get_msr,
8685 .check_rdpmc_early = emulator_check_rdpmc_early,
8686 .read_pmc = emulator_read_pmc,
8687 .halt = emulator_halt,
8688 .wbinvd = emulator_wbinvd,
8689 .fix_hypercall = emulator_fix_hypercall,
8690 .intercept = emulator_intercept,
8691 .get_cpuid = emulator_get_cpuid,
8692 .guest_has_movbe = emulator_guest_has_movbe,
8693 .guest_has_fxsr = emulator_guest_has_fxsr,
8694 .guest_has_rdpid = emulator_guest_has_rdpid,
8695 .guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
8696 .set_nmi_mask = emulator_set_nmi_mask,
8697 .is_smm = emulator_is_smm,
8698 .is_guest_mode = emulator_is_guest_mode,
8699 .leave_smm = emulator_leave_smm,
8700 .triple_fault = emulator_triple_fault,
8701 .set_xcr = emulator_set_xcr,
8702 .get_untagged_addr = emulator_get_untagged_addr,
8703 .is_canonical_addr = emulator_is_canonical_addr,
8704 };
8705
toggle_interruptibility(struct kvm_vcpu * vcpu,u32 mask)8706 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8707 {
8708 u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
8709 /*
8710 * an sti; sti; sequence only disable interrupts for the first
8711 * instruction. So, if the last instruction, be it emulated or
8712 * not, left the system with the INT_STI flag enabled, it
8713 * means that the last instruction is an sti. We should not
8714 * leave the flag on in this case. The same goes for mov ss
8715 */
8716 if (int_shadow & mask)
8717 mask = 0;
8718 if (unlikely(int_shadow || mask)) {
8719 kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
8720 if (!mask)
8721 kvm_make_request(KVM_REQ_EVENT, vcpu);
8722 }
8723 }
8724
inject_emulated_exception(struct kvm_vcpu * vcpu)8725 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8726 {
8727 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8728
8729 if (ctxt->exception.vector == PF_VECTOR)
8730 kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8731 else if (ctxt->exception.error_code_valid)
8732 kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8733 ctxt->exception.error_code);
8734 else
8735 kvm_queue_exception(vcpu, ctxt->exception.vector);
8736 }
8737
alloc_emulate_ctxt(struct kvm_vcpu * vcpu)8738 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8739 {
8740 struct x86_emulate_ctxt *ctxt;
8741
8742 ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8743 if (!ctxt) {
8744 pr_err("failed to allocate vcpu's emulator\n");
8745 return NULL;
8746 }
8747
8748 ctxt->vcpu = vcpu;
8749 ctxt->ops = &emulate_ops;
8750 vcpu->arch.emulate_ctxt = ctxt;
8751
8752 return ctxt;
8753 }
8754
init_emulate_ctxt(struct kvm_vcpu * vcpu)8755 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8756 {
8757 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8758 int cs_db, cs_l;
8759
8760 kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8761
8762 ctxt->gpa_available = false;
8763 ctxt->eflags = kvm_get_rflags(vcpu);
8764 ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8765
8766 ctxt->eip = kvm_rip_read(vcpu);
8767 ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
8768 (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
8769 (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
8770 cs_db ? X86EMUL_MODE_PROT32 :
8771 X86EMUL_MODE_PROT16;
8772 ctxt->interruptibility = 0;
8773 ctxt->have_exception = false;
8774 ctxt->exception.vector = -1;
8775 ctxt->perm_ok = false;
8776
8777 init_decode_cache(ctxt);
8778 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8779 }
8780
kvm_inject_realmode_interrupt(struct kvm_vcpu * vcpu,int irq,int inc_eip)8781 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8782 {
8783 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8784 int ret;
8785
8786 init_emulate_ctxt(vcpu);
8787
8788 ctxt->op_bytes = 2;
8789 ctxt->ad_bytes = 2;
8790 ctxt->_eip = ctxt->eip + inc_eip;
8791 ret = emulate_int_real(ctxt, irq);
8792
8793 if (ret != X86EMUL_CONTINUE) {
8794 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8795 } else {
8796 ctxt->eip = ctxt->_eip;
8797 kvm_rip_write(vcpu, ctxt->eip);
8798 kvm_set_rflags(vcpu, ctxt->eflags);
8799 }
8800 }
8801 EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
8802
prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata,u8 * insn_bytes,u8 insn_size)8803 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8804 u8 ndata, u8 *insn_bytes, u8 insn_size)
8805 {
8806 struct kvm_run *run = vcpu->run;
8807 u64 info[5];
8808 u8 info_start;
8809
8810 /*
8811 * Zero the whole array used to retrieve the exit info, as casting to
8812 * u32 for select entries will leave some chunks uninitialized.
8813 */
8814 memset(&info, 0, sizeof(info));
8815
8816 kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
8817 (u32 *)&info[3], (u32 *)&info[4]);
8818
8819 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8820 run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
8821
8822 /*
8823 * There's currently space for 13 entries, but 5 are used for the exit
8824 * reason and info. Restrict to 4 to reduce the maintenance burden
8825 * when expanding kvm_run.emulation_failure in the future.
8826 */
8827 if (WARN_ON_ONCE(ndata > 4))
8828 ndata = 4;
8829
8830 /* Always include the flags as a 'data' entry. */
8831 info_start = 1;
8832 run->emulation_failure.flags = 0;
8833
8834 if (insn_size) {
8835 BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
8836 sizeof(run->emulation_failure.insn_bytes) != 16));
8837 info_start += 2;
8838 run->emulation_failure.flags |=
8839 KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
8840 run->emulation_failure.insn_size = insn_size;
8841 memset(run->emulation_failure.insn_bytes, 0x90,
8842 sizeof(run->emulation_failure.insn_bytes));
8843 memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
8844 }
8845
8846 memcpy(&run->internal.data[info_start], info, sizeof(info));
8847 memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
8848 ndata * sizeof(data[0]));
8849
8850 run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
8851 }
8852
prepare_emulation_ctxt_failure_exit(struct kvm_vcpu * vcpu)8853 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
8854 {
8855 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8856
8857 prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
8858 ctxt->fetch.end - ctxt->fetch.data);
8859 }
8860
__kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata)8861 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
8862 u8 ndata)
8863 {
8864 prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
8865 }
8866 EXPORT_SYMBOL_GPL(__kvm_prepare_emulation_failure_exit);
8867
kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu)8868 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
8869 {
8870 __kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
8871 }
8872 EXPORT_SYMBOL_GPL(kvm_prepare_emulation_failure_exit);
8873
kvm_prepare_event_vectoring_exit(struct kvm_vcpu * vcpu,gpa_t gpa)8874 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa)
8875 {
8876 u32 reason, intr_info, error_code;
8877 struct kvm_run *run = vcpu->run;
8878 u64 info1, info2;
8879 int ndata = 0;
8880
8881 kvm_x86_call(get_exit_info)(vcpu, &reason, &info1, &info2,
8882 &intr_info, &error_code);
8883
8884 run->internal.data[ndata++] = info2;
8885 run->internal.data[ndata++] = reason;
8886 run->internal.data[ndata++] = info1;
8887 run->internal.data[ndata++] = gpa;
8888 run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
8889
8890 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8891 run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8892 run->internal.ndata = ndata;
8893 }
8894 EXPORT_SYMBOL_GPL(kvm_prepare_event_vectoring_exit);
8895
handle_emulation_failure(struct kvm_vcpu * vcpu,int emulation_type)8896 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
8897 {
8898 struct kvm *kvm = vcpu->kvm;
8899
8900 ++vcpu->stat.insn_emulation_fail;
8901 trace_kvm_emulate_insn_failed(vcpu);
8902
8903 if (emulation_type & EMULTYPE_VMWARE_GP) {
8904 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8905 return 1;
8906 }
8907
8908 if (kvm->arch.exit_on_emulation_error ||
8909 (emulation_type & EMULTYPE_SKIP)) {
8910 prepare_emulation_ctxt_failure_exit(vcpu);
8911 return 0;
8912 }
8913
8914 kvm_queue_exception(vcpu, UD_VECTOR);
8915
8916 if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
8917 prepare_emulation_ctxt_failure_exit(vcpu);
8918 return 0;
8919 }
8920
8921 return 1;
8922 }
8923
kvm_unprotect_and_retry_on_failure(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type)8924 static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
8925 gpa_t cr2_or_gpa,
8926 int emulation_type)
8927 {
8928 if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
8929 return false;
8930
8931 /*
8932 * If the failed instruction faulted on an access to page tables that
8933 * are used to translate any part of the instruction, KVM can't resolve
8934 * the issue by unprotecting the gfn, as zapping the shadow page will
8935 * result in the instruction taking a !PRESENT page fault and thus put
8936 * the vCPU into an infinite loop of page faults. E.g. KVM will create
8937 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
8938 * then zap the SPTE to unprotect the gfn, and then do it all over
8939 * again. Report the error to userspace.
8940 */
8941 if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
8942 return false;
8943
8944 /*
8945 * If emulation may have been triggered by a write to a shadowed page
8946 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
8947 * guest to let the CPU re-execute the instruction in the hope that the
8948 * CPU can cleanly execute the instruction that KVM failed to emulate.
8949 */
8950 __kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
8951
8952 /*
8953 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
8954 * all SPTEs were already zapped by a different task. The alternative
8955 * is to report the error to userspace and likely terminate the guest,
8956 * and the last_retry_{eip,addr} checks will prevent retrying the page
8957 * fault indefinitely, i.e. there's nothing to lose by retrying.
8958 */
8959 return true;
8960 }
8961
8962 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
8963 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
8964
kvm_vcpu_check_hw_bp(unsigned long addr,u32 type,u32 dr7,unsigned long * db)8965 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
8966 unsigned long *db)
8967 {
8968 u32 dr6 = 0;
8969 int i;
8970 u32 enable, rwlen;
8971
8972 enable = dr7;
8973 rwlen = dr7 >> 16;
8974 for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
8975 if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
8976 dr6 |= (1 << i);
8977 return dr6;
8978 }
8979
kvm_vcpu_do_singlestep(struct kvm_vcpu * vcpu)8980 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
8981 {
8982 struct kvm_run *kvm_run = vcpu->run;
8983
8984 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
8985 kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
8986 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
8987 kvm_run->debug.arch.exception = DB_VECTOR;
8988 kvm_run->exit_reason = KVM_EXIT_DEBUG;
8989 return 0;
8990 }
8991 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
8992 return 1;
8993 }
8994
kvm_skip_emulated_instruction(struct kvm_vcpu * vcpu)8995 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
8996 {
8997 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
8998 int r;
8999
9000 r = kvm_x86_call(skip_emulated_instruction)(vcpu);
9001 if (unlikely(!r))
9002 return 0;
9003
9004 kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
9005
9006 /*
9007 * rflags is the old, "raw" value of the flags. The new value has
9008 * not been saved yet.
9009 *
9010 * This is correct even for TF set by the guest, because "the
9011 * processor will not generate this exception after the instruction
9012 * that sets the TF flag".
9013 */
9014 if (unlikely(rflags & X86_EFLAGS_TF))
9015 r = kvm_vcpu_do_singlestep(vcpu);
9016 return r;
9017 }
9018 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
9019
kvm_is_code_breakpoint_inhibited(struct kvm_vcpu * vcpu)9020 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
9021 {
9022 if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
9023 return true;
9024
9025 /*
9026 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
9027 * active, but AMD compatible CPUs do not.
9028 */
9029 if (!guest_cpuid_is_intel_compatible(vcpu))
9030 return false;
9031
9032 return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
9033 }
9034
kvm_vcpu_check_code_breakpoint(struct kvm_vcpu * vcpu,int emulation_type,int * r)9035 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
9036 int emulation_type, int *r)
9037 {
9038 WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
9039
9040 /*
9041 * Do not check for code breakpoints if hardware has already done the
9042 * checks, as inferred from the emulation type. On NO_DECODE and SKIP,
9043 * the instruction has passed all exception checks, and all intercepted
9044 * exceptions that trigger emulation have lower priority than code
9045 * breakpoints, i.e. the fact that the intercepted exception occurred
9046 * means any code breakpoints have already been serviced.
9047 *
9048 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
9049 * hardware has checked the RIP of the magic prefix, but not the RIP of
9050 * the instruction being emulated. The intent of forced emulation is
9051 * to behave as if KVM intercepted the instruction without an exception
9052 * and without a prefix.
9053 */
9054 if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
9055 EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
9056 return false;
9057
9058 if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
9059 (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
9060 struct kvm_run *kvm_run = vcpu->run;
9061 unsigned long eip = kvm_get_linear_rip(vcpu);
9062 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9063 vcpu->arch.guest_debug_dr7,
9064 vcpu->arch.eff_db);
9065
9066 if (dr6 != 0) {
9067 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
9068 kvm_run->debug.arch.pc = eip;
9069 kvm_run->debug.arch.exception = DB_VECTOR;
9070 kvm_run->exit_reason = KVM_EXIT_DEBUG;
9071 *r = 0;
9072 return true;
9073 }
9074 }
9075
9076 if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
9077 !kvm_is_code_breakpoint_inhibited(vcpu)) {
9078 unsigned long eip = kvm_get_linear_rip(vcpu);
9079 u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9080 vcpu->arch.dr7,
9081 vcpu->arch.db);
9082
9083 if (dr6 != 0) {
9084 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
9085 *r = 1;
9086 return true;
9087 }
9088 }
9089
9090 return false;
9091 }
9092
is_vmware_backdoor_opcode(struct x86_emulate_ctxt * ctxt)9093 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9094 {
9095 switch (ctxt->opcode_len) {
9096 case 1:
9097 switch (ctxt->b) {
9098 case 0xe4: /* IN */
9099 case 0xe5:
9100 case 0xec:
9101 case 0xed:
9102 case 0xe6: /* OUT */
9103 case 0xe7:
9104 case 0xee:
9105 case 0xef:
9106 case 0x6c: /* INS */
9107 case 0x6d:
9108 case 0x6e: /* OUTS */
9109 case 0x6f:
9110 return true;
9111 }
9112 break;
9113 case 2:
9114 switch (ctxt->b) {
9115 case 0x33: /* RDPMC */
9116 return true;
9117 }
9118 break;
9119 }
9120
9121 return false;
9122 }
9123
9124 /*
9125 * Decode an instruction for emulation. The caller is responsible for handling
9126 * code breakpoints. Note, manually detecting code breakpoints is unnecessary
9127 * (and wrong) when emulating on an intercepted fault-like exception[*], as
9128 * code breakpoints have higher priority and thus have already been done by
9129 * hardware.
9130 *
9131 * [*] Except #MC, which is higher priority, but KVM should never emulate in
9132 * response to a machine check.
9133 */
x86_decode_emulated_instruction(struct kvm_vcpu * vcpu,int emulation_type,void * insn,int insn_len)9134 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9135 void *insn, int insn_len)
9136 {
9137 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9138 int r;
9139
9140 init_emulate_ctxt(vcpu);
9141
9142 r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
9143
9144 trace_kvm_emulate_insn_start(vcpu);
9145 ++vcpu->stat.insn_emulation;
9146
9147 return r;
9148 }
9149 EXPORT_SYMBOL_GPL(x86_decode_emulated_instruction);
9150
x86_emulate_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type,void * insn,int insn_len)9151 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9152 int emulation_type, void *insn, int insn_len)
9153 {
9154 int r;
9155 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9156 bool writeback = true;
9157
9158 if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9159 (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
9160 WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
9161 emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
9162
9163 r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
9164 if (r != X86EMUL_CONTINUE) {
9165 if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9166 return 1;
9167
9168 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9169 emulation_type))
9170 return 1;
9171
9172 if (r == X86EMUL_UNHANDLEABLE_VECTORING) {
9173 kvm_prepare_event_vectoring_exit(vcpu, cr2_or_gpa);
9174 return 0;
9175 }
9176
9177 WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9178 return handle_emulation_failure(vcpu, emulation_type);
9179 }
9180
9181 vcpu->arch.l1tf_flush_l1d = true;
9182
9183 if (!(emulation_type & EMULTYPE_NO_DECODE)) {
9184 kvm_clear_exception_queue(vcpu);
9185
9186 /*
9187 * Return immediately if RIP hits a code breakpoint, such #DBs
9188 * are fault-like and are higher priority than any faults on
9189 * the code fetch itself.
9190 */
9191 if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
9192 return r;
9193
9194 r = x86_decode_emulated_instruction(vcpu, emulation_type,
9195 insn, insn_len);
9196 if (r != EMULATION_OK) {
9197 if ((emulation_type & EMULTYPE_TRAP_UD) ||
9198 (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9199 kvm_queue_exception(vcpu, UD_VECTOR);
9200 return 1;
9201 }
9202 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9203 emulation_type))
9204 return 1;
9205
9206 if (ctxt->have_exception &&
9207 !(emulation_type & EMULTYPE_SKIP)) {
9208 /*
9209 * #UD should result in just EMULATION_FAILED, and trap-like
9210 * exception should not be encountered during decode.
9211 */
9212 WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9213 exception_type(ctxt->exception.vector) == EXCPT_TRAP);
9214 inject_emulated_exception(vcpu);
9215 return 1;
9216 }
9217 return handle_emulation_failure(vcpu, emulation_type);
9218 }
9219 }
9220
9221 if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9222 !is_vmware_backdoor_opcode(ctxt)) {
9223 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9224 return 1;
9225 }
9226
9227 /*
9228 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9229 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9230 * The caller is responsible for updating interruptibility state and
9231 * injecting single-step #DBs.
9232 */
9233 if (emulation_type & EMULTYPE_SKIP) {
9234 if (ctxt->mode != X86EMUL_MODE_PROT64)
9235 ctxt->eip = (u32)ctxt->_eip;
9236 else
9237 ctxt->eip = ctxt->_eip;
9238
9239 if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9240 r = 1;
9241 goto writeback;
9242 }
9243
9244 kvm_rip_write(vcpu, ctxt->eip);
9245 if (ctxt->eflags & X86_EFLAGS_RF)
9246 kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
9247 return 1;
9248 }
9249
9250 /*
9251 * If emulation was caused by a write-protection #PF on a non-page_table
9252 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
9253 * and retry the instruction, as the vCPU is likely no longer using the
9254 * gfn as a page table.
9255 */
9256 if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9257 !x86_page_table_writing_insn(ctxt) &&
9258 kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
9259 return 1;
9260
9261 /* this is needed for vmware backdoor interface to work since it
9262 changes registers values during IO operation */
9263 if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9264 vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9265 emulator_invalidate_register_cache(ctxt);
9266 }
9267
9268 restart:
9269 if (emulation_type & EMULTYPE_PF) {
9270 /* Save the faulting GPA (cr2) in the address field */
9271 ctxt->exception.address = cr2_or_gpa;
9272
9273 /* With shadow page tables, cr2 contains a GVA or nGPA. */
9274 if (vcpu->arch.mmu->root_role.direct) {
9275 ctxt->gpa_available = true;
9276 ctxt->gpa_val = cr2_or_gpa;
9277 }
9278 } else {
9279 /* Sanitize the address out of an abundance of paranoia. */
9280 ctxt->exception.address = 0;
9281 }
9282
9283 r = x86_emulate_insn(ctxt);
9284
9285 if (r == EMULATION_INTERCEPTED)
9286 return 1;
9287
9288 if (r == EMULATION_FAILED) {
9289 if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9290 emulation_type))
9291 return 1;
9292
9293 return handle_emulation_failure(vcpu, emulation_type);
9294 }
9295
9296 if (ctxt->have_exception) {
9297 WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9298 vcpu->mmio_needed = false;
9299 r = 1;
9300 inject_emulated_exception(vcpu);
9301 } else if (vcpu->arch.pio.count) {
9302 if (!vcpu->arch.pio.in) {
9303 /* FIXME: return into emulator if single-stepping. */
9304 vcpu->arch.pio.count = 0;
9305 } else {
9306 writeback = false;
9307 vcpu->arch.complete_userspace_io = complete_emulated_pio;
9308 }
9309 r = 0;
9310 } else if (vcpu->mmio_needed) {
9311 ++vcpu->stat.mmio_exits;
9312
9313 if (!vcpu->mmio_is_write)
9314 writeback = false;
9315 r = 0;
9316 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9317 } else if (vcpu->arch.complete_userspace_io) {
9318 writeback = false;
9319 r = 0;
9320 } else if (r == EMULATION_RESTART)
9321 goto restart;
9322 else
9323 r = 1;
9324
9325 writeback:
9326 if (writeback) {
9327 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9328 toggle_interruptibility(vcpu, ctxt->interruptibility);
9329 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9330
9331 /*
9332 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9333 * only supports code breakpoints and general detect #DB, both
9334 * of which are fault-like.
9335 */
9336 if (!ctxt->have_exception ||
9337 exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9338 kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.INSTRUCTIONS_RETIRED);
9339 if (ctxt->is_branch)
9340 kvm_pmu_trigger_event(vcpu, kvm_pmu_eventsel.BRANCH_INSTRUCTIONS_RETIRED);
9341 kvm_rip_write(vcpu, ctxt->eip);
9342 if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9343 r = kvm_vcpu_do_singlestep(vcpu);
9344 kvm_x86_call(update_emulated_instruction)(vcpu);
9345 __kvm_set_rflags(vcpu, ctxt->eflags);
9346 }
9347
9348 /*
9349 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9350 * do nothing, and it will be requested again as soon as
9351 * the shadow expires. But we still need to check here,
9352 * because POPF has no interrupt shadow.
9353 */
9354 if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9355 kvm_make_request(KVM_REQ_EVENT, vcpu);
9356 } else
9357 vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9358
9359 return r;
9360 }
9361
kvm_emulate_instruction(struct kvm_vcpu * vcpu,int emulation_type)9362 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9363 {
9364 return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9365 }
9366 EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
9367
kvm_emulate_instruction_from_buffer(struct kvm_vcpu * vcpu,void * insn,int insn_len)9368 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9369 void *insn, int insn_len)
9370 {
9371 return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9372 }
9373 EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
9374
complete_fast_pio_out_port_0x7e(struct kvm_vcpu * vcpu)9375 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9376 {
9377 vcpu->arch.pio.count = 0;
9378 return 1;
9379 }
9380
complete_fast_pio_out(struct kvm_vcpu * vcpu)9381 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9382 {
9383 vcpu->arch.pio.count = 0;
9384
9385 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip)))
9386 return 1;
9387
9388 return kvm_skip_emulated_instruction(vcpu);
9389 }
9390
kvm_fast_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port)9391 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9392 unsigned short port)
9393 {
9394 unsigned long val = kvm_rax_read(vcpu);
9395 int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9396
9397 if (ret)
9398 return ret;
9399
9400 /*
9401 * Workaround userspace that relies on old KVM behavior of %rip being
9402 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9403 */
9404 if (port == 0x7e &&
9405 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9406 vcpu->arch.complete_userspace_io =
9407 complete_fast_pio_out_port_0x7e;
9408 kvm_skip_emulated_instruction(vcpu);
9409 } else {
9410 vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9411 vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9412 }
9413 return 0;
9414 }
9415
complete_fast_pio_in(struct kvm_vcpu * vcpu)9416 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9417 {
9418 unsigned long val;
9419
9420 /* We should only ever be called with arch.pio.count equal to 1 */
9421 BUG_ON(vcpu->arch.pio.count != 1);
9422
9423 if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip))) {
9424 vcpu->arch.pio.count = 0;
9425 return 1;
9426 }
9427
9428 /* For size less than 4 we merge, else we zero extend */
9429 val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9430
9431 complete_emulator_pio_in(vcpu, &val);
9432 kvm_rax_write(vcpu, val);
9433
9434 return kvm_skip_emulated_instruction(vcpu);
9435 }
9436
kvm_fast_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port)9437 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9438 unsigned short port)
9439 {
9440 unsigned long val;
9441 int ret;
9442
9443 /* For size less than 4 we merge, else we zero extend */
9444 val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9445
9446 ret = emulator_pio_in(vcpu, size, port, &val, 1);
9447 if (ret) {
9448 kvm_rax_write(vcpu, val);
9449 return ret;
9450 }
9451
9452 vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9453 vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9454
9455 return 0;
9456 }
9457
kvm_fast_pio(struct kvm_vcpu * vcpu,int size,unsigned short port,int in)9458 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9459 {
9460 int ret;
9461
9462 if (in)
9463 ret = kvm_fast_pio_in(vcpu, size, port);
9464 else
9465 ret = kvm_fast_pio_out(vcpu, size, port);
9466 return ret && kvm_skip_emulated_instruction(vcpu);
9467 }
9468 EXPORT_SYMBOL_GPL(kvm_fast_pio);
9469
kvmclock_cpu_down_prep(unsigned int cpu)9470 static int kvmclock_cpu_down_prep(unsigned int cpu)
9471 {
9472 __this_cpu_write(cpu_tsc_khz, 0);
9473 return 0;
9474 }
9475
tsc_khz_changed(void * data)9476 static void tsc_khz_changed(void *data)
9477 {
9478 struct cpufreq_freqs *freq = data;
9479 unsigned long khz;
9480
9481 WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9482
9483 if (data)
9484 khz = freq->new;
9485 else
9486 khz = cpufreq_quick_get(raw_smp_processor_id());
9487 if (!khz)
9488 khz = tsc_khz;
9489 __this_cpu_write(cpu_tsc_khz, khz);
9490 }
9491
9492 #ifdef CONFIG_X86_64
kvm_hyperv_tsc_notifier(void)9493 static void kvm_hyperv_tsc_notifier(void)
9494 {
9495 struct kvm *kvm;
9496 int cpu;
9497
9498 mutex_lock(&kvm_lock);
9499 list_for_each_entry(kvm, &vm_list, vm_list)
9500 kvm_make_mclock_inprogress_request(kvm);
9501
9502 /* no guest entries from this point */
9503 hyperv_stop_tsc_emulation();
9504
9505 /* TSC frequency always matches when on Hyper-V */
9506 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9507 for_each_present_cpu(cpu)
9508 per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9509 }
9510 kvm_caps.max_guest_tsc_khz = tsc_khz;
9511
9512 list_for_each_entry(kvm, &vm_list, vm_list) {
9513 __kvm_start_pvclock_update(kvm);
9514 pvclock_update_vm_gtod_copy(kvm);
9515 kvm_end_pvclock_update(kvm);
9516 }
9517
9518 mutex_unlock(&kvm_lock);
9519 }
9520 #endif
9521
__kvmclock_cpufreq_notifier(struct cpufreq_freqs * freq,int cpu)9522 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9523 {
9524 struct kvm *kvm;
9525 struct kvm_vcpu *vcpu;
9526 int send_ipi = 0;
9527 unsigned long i;
9528
9529 /*
9530 * We allow guests to temporarily run on slowing clocks,
9531 * provided we notify them after, or to run on accelerating
9532 * clocks, provided we notify them before. Thus time never
9533 * goes backwards.
9534 *
9535 * However, we have a problem. We can't atomically update
9536 * the frequency of a given CPU from this function; it is
9537 * merely a notifier, which can be called from any CPU.
9538 * Changing the TSC frequency at arbitrary points in time
9539 * requires a recomputation of local variables related to
9540 * the TSC for each VCPU. We must flag these local variables
9541 * to be updated and be sure the update takes place with the
9542 * new frequency before any guests proceed.
9543 *
9544 * Unfortunately, the combination of hotplug CPU and frequency
9545 * change creates an intractable locking scenario; the order
9546 * of when these callouts happen is undefined with respect to
9547 * CPU hotplug, and they can race with each other. As such,
9548 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9549 * undefined; you can actually have a CPU frequency change take
9550 * place in between the computation of X and the setting of the
9551 * variable. To protect against this problem, all updates of
9552 * the per_cpu tsc_khz variable are done in an interrupt
9553 * protected IPI, and all callers wishing to update the value
9554 * must wait for a synchronous IPI to complete (which is trivial
9555 * if the caller is on the CPU already). This establishes the
9556 * necessary total order on variable updates.
9557 *
9558 * Note that because a guest time update may take place
9559 * anytime after the setting of the VCPU's request bit, the
9560 * correct TSC value must be set before the request. However,
9561 * to ensure the update actually makes it to any guest which
9562 * starts running in hardware virtualization between the set
9563 * and the acquisition of the spinlock, we must also ping the
9564 * CPU after setting the request bit.
9565 *
9566 */
9567
9568 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9569
9570 mutex_lock(&kvm_lock);
9571 list_for_each_entry(kvm, &vm_list, vm_list) {
9572 kvm_for_each_vcpu(i, vcpu, kvm) {
9573 if (vcpu->cpu != cpu)
9574 continue;
9575 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9576 if (vcpu->cpu != raw_smp_processor_id())
9577 send_ipi = 1;
9578 }
9579 }
9580 mutex_unlock(&kvm_lock);
9581
9582 if (freq->old < freq->new && send_ipi) {
9583 /*
9584 * We upscale the frequency. Must make the guest
9585 * doesn't see old kvmclock values while running with
9586 * the new frequency, otherwise we risk the guest sees
9587 * time go backwards.
9588 *
9589 * In case we update the frequency for another cpu
9590 * (which might be in guest context) send an interrupt
9591 * to kick the cpu out of guest context. Next time
9592 * guest context is entered kvmclock will be updated,
9593 * so the guest will not see stale values.
9594 */
9595 smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9596 }
9597 }
9598
kvmclock_cpufreq_notifier(struct notifier_block * nb,unsigned long val,void * data)9599 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9600 void *data)
9601 {
9602 struct cpufreq_freqs *freq = data;
9603 int cpu;
9604
9605 if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9606 return 0;
9607 if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9608 return 0;
9609
9610 for_each_cpu(cpu, freq->policy->cpus)
9611 __kvmclock_cpufreq_notifier(freq, cpu);
9612
9613 return 0;
9614 }
9615
9616 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9617 .notifier_call = kvmclock_cpufreq_notifier
9618 };
9619
kvmclock_cpu_online(unsigned int cpu)9620 static int kvmclock_cpu_online(unsigned int cpu)
9621 {
9622 tsc_khz_changed(NULL);
9623 return 0;
9624 }
9625
kvm_timer_init(void)9626 static void kvm_timer_init(void)
9627 {
9628 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9629 max_tsc_khz = tsc_khz;
9630
9631 if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9632 struct cpufreq_policy *policy;
9633 int cpu;
9634
9635 cpu = get_cpu();
9636 policy = cpufreq_cpu_get(cpu);
9637 if (policy) {
9638 if (policy->cpuinfo.max_freq)
9639 max_tsc_khz = policy->cpuinfo.max_freq;
9640 cpufreq_cpu_put(policy);
9641 }
9642 put_cpu();
9643 }
9644 cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9645 CPUFREQ_TRANSITION_NOTIFIER);
9646
9647 cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9648 kvmclock_cpu_online, kvmclock_cpu_down_prep);
9649 }
9650 }
9651
9652 #ifdef CONFIG_X86_64
pvclock_gtod_update_fn(struct work_struct * work)9653 static void pvclock_gtod_update_fn(struct work_struct *work)
9654 {
9655 struct kvm *kvm;
9656 struct kvm_vcpu *vcpu;
9657 unsigned long i;
9658
9659 mutex_lock(&kvm_lock);
9660 list_for_each_entry(kvm, &vm_list, vm_list)
9661 kvm_for_each_vcpu(i, vcpu, kvm)
9662 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9663 atomic_set(&kvm_guest_has_master_clock, 0);
9664 mutex_unlock(&kvm_lock);
9665 }
9666
9667 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9668
9669 /*
9670 * Indirection to move queue_work() out of the tk_core.seq write held
9671 * region to prevent possible deadlocks against time accessors which
9672 * are invoked with work related locks held.
9673 */
pvclock_irq_work_fn(struct irq_work * w)9674 static void pvclock_irq_work_fn(struct irq_work *w)
9675 {
9676 queue_work(system_long_wq, &pvclock_gtod_work);
9677 }
9678
9679 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9680
9681 /*
9682 * Notification about pvclock gtod data update.
9683 */
pvclock_gtod_notify(struct notifier_block * nb,unsigned long unused,void * priv)9684 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9685 void *priv)
9686 {
9687 struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9688 struct timekeeper *tk = priv;
9689
9690 update_pvclock_gtod(tk);
9691
9692 /*
9693 * Disable master clock if host does not trust, or does not use,
9694 * TSC based clocksource. Delegate queue_work() to irq_work as
9695 * this is invoked with tk_core.seq write held.
9696 */
9697 if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9698 atomic_read(&kvm_guest_has_master_clock) != 0)
9699 irq_work_queue(&pvclock_irq_work);
9700 return 0;
9701 }
9702
9703 static struct notifier_block pvclock_gtod_notifier = {
9704 .notifier_call = pvclock_gtod_notify,
9705 };
9706 #endif
9707
kvm_ops_update(struct kvm_x86_init_ops * ops)9708 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
9709 {
9710 memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9711
9712 #define __KVM_X86_OP(func) \
9713 static_call_update(kvm_x86_##func, kvm_x86_ops.func);
9714 #define KVM_X86_OP(func) \
9715 WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
9716 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
9717 #define KVM_X86_OP_OPTIONAL_RET0(func) \
9718 static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
9719 (void *)__static_call_return0);
9720 #include <asm/kvm-x86-ops.h>
9721 #undef __KVM_X86_OP
9722
9723 kvm_pmu_ops_update(ops->pmu_ops);
9724 }
9725
kvm_x86_check_processor_compatibility(void)9726 static int kvm_x86_check_processor_compatibility(void)
9727 {
9728 int cpu = smp_processor_id();
9729 struct cpuinfo_x86 *c = &cpu_data(cpu);
9730
9731 /*
9732 * Compatibility checks are done when loading KVM and when enabling
9733 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
9734 * compatible, i.e. KVM should never perform a compatibility check on
9735 * an offline CPU.
9736 */
9737 WARN_ON(!cpu_online(cpu));
9738
9739 if (__cr4_reserved_bits(cpu_has, c) !=
9740 __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9741 return -EIO;
9742
9743 return kvm_x86_call(check_processor_compatibility)();
9744 }
9745
kvm_x86_check_cpu_compat(void * ret)9746 static void kvm_x86_check_cpu_compat(void *ret)
9747 {
9748 *(int *)ret = kvm_x86_check_processor_compatibility();
9749 }
9750
kvm_x86_vendor_init(struct kvm_x86_init_ops * ops)9751 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
9752 {
9753 u64 host_pat;
9754 int r, cpu;
9755
9756 guard(mutex)(&vendor_module_lock);
9757
9758 if (kvm_x86_ops.enable_virtualization_cpu) {
9759 pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
9760 return -EEXIST;
9761 }
9762
9763 /*
9764 * KVM explicitly assumes that the guest has an FPU and
9765 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9766 * vCPU's FPU state as a fxregs_state struct.
9767 */
9768 if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9769 pr_err("inadequate fpu\n");
9770 return -EOPNOTSUPP;
9771 }
9772
9773 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9774 pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
9775 return -EOPNOTSUPP;
9776 }
9777
9778 /*
9779 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
9780 * the PAT bits in SPTEs. Bail if PAT[0] is programmed to something
9781 * other than WB. Note, EPT doesn't utilize the PAT, but don't bother
9782 * with an exception. PAT[0] is set to WB on RESET and also by the
9783 * kernel, i.e. failure indicates a kernel bug or broken firmware.
9784 */
9785 if (rdmsrq_safe(MSR_IA32_CR_PAT, &host_pat) ||
9786 (host_pat & GENMASK(2, 0)) != 6) {
9787 pr_err("host PAT[0] is not WB\n");
9788 return -EIO;
9789 }
9790
9791 memset(&kvm_caps, 0, sizeof(kvm_caps));
9792
9793 x86_emulator_cache = kvm_alloc_emulator_cache();
9794 if (!x86_emulator_cache) {
9795 pr_err("failed to allocate cache for x86 emulator\n");
9796 return -ENOMEM;
9797 }
9798
9799 user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
9800 if (!user_return_msrs) {
9801 pr_err("failed to allocate percpu kvm_user_return_msrs\n");
9802 r = -ENOMEM;
9803 goto out_free_x86_emulator_cache;
9804 }
9805 kvm_nr_uret_msrs = 0;
9806
9807 r = kvm_mmu_vendor_module_init();
9808 if (r)
9809 goto out_free_percpu;
9810
9811 kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
9812 kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
9813
9814 if (boot_cpu_has(X86_FEATURE_XSAVE)) {
9815 kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
9816 kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
9817 }
9818 kvm_caps.supported_quirks = KVM_X86_VALID_QUIRKS;
9819 kvm_caps.inapplicable_quirks = KVM_X86_CONDITIONAL_QUIRKS;
9820
9821 rdmsrq_safe(MSR_EFER, &kvm_host.efer);
9822
9823 if (boot_cpu_has(X86_FEATURE_XSAVES))
9824 rdmsrq(MSR_IA32_XSS, kvm_host.xss);
9825
9826 kvm_init_pmu_capability(ops->pmu_ops);
9827
9828 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
9829 rdmsrq(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
9830
9831 r = ops->hardware_setup();
9832 if (r != 0)
9833 goto out_mmu_exit;
9834
9835 enable_device_posted_irqs &= enable_apicv &&
9836 irq_remapping_cap(IRQ_POSTING_CAP);
9837
9838 kvm_ops_update(ops);
9839
9840 for_each_online_cpu(cpu) {
9841 smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
9842 if (r < 0)
9843 goto out_unwind_ops;
9844 }
9845
9846 /*
9847 * Point of no return! DO NOT add error paths below this point unless
9848 * absolutely necessary, as most operations from this point forward
9849 * require unwinding.
9850 */
9851 kvm_timer_init();
9852
9853 if (pi_inject_timer == -1)
9854 pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
9855 #ifdef CONFIG_X86_64
9856 pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
9857
9858 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9859 set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
9860 #endif
9861
9862 kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
9863
9864 if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
9865 kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
9866
9867 /* KVM always ignores guest PAT for shadow paging. */
9868 if (!tdp_enabled)
9869 kvm_caps.supported_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT;
9870
9871 if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
9872 kvm_caps.supported_xss = 0;
9873
9874 if (kvm_caps.has_tsc_control) {
9875 /*
9876 * Make sure the user can only configure tsc_khz values that
9877 * fit into a signed integer.
9878 * A min value is not calculated because it will always
9879 * be 1 on all machines.
9880 */
9881 u64 max = min(0x7fffffffULL,
9882 __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
9883 kvm_caps.max_guest_tsc_khz = max;
9884 }
9885 kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
9886 kvm_init_msr_lists();
9887 return 0;
9888
9889 out_unwind_ops:
9890 kvm_x86_ops.enable_virtualization_cpu = NULL;
9891 kvm_x86_call(hardware_unsetup)();
9892 out_mmu_exit:
9893 kvm_mmu_vendor_module_exit();
9894 out_free_percpu:
9895 free_percpu(user_return_msrs);
9896 out_free_x86_emulator_cache:
9897 kmem_cache_destroy(x86_emulator_cache);
9898 return r;
9899 }
9900 EXPORT_SYMBOL_GPL(kvm_x86_vendor_init);
9901
kvm_x86_vendor_exit(void)9902 void kvm_x86_vendor_exit(void)
9903 {
9904 kvm_unregister_perf_callbacks();
9905
9906 #ifdef CONFIG_X86_64
9907 if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
9908 clear_hv_tscchange_cb();
9909 #endif
9910 kvm_lapic_exit();
9911
9912 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9913 cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
9914 CPUFREQ_TRANSITION_NOTIFIER);
9915 cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
9916 }
9917 #ifdef CONFIG_X86_64
9918 pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
9919 irq_work_sync(&pvclock_irq_work);
9920 cancel_work_sync(&pvclock_gtod_work);
9921 #endif
9922 kvm_x86_call(hardware_unsetup)();
9923 kvm_mmu_vendor_module_exit();
9924 free_percpu(user_return_msrs);
9925 kmem_cache_destroy(x86_emulator_cache);
9926 #ifdef CONFIG_KVM_XEN
9927 static_key_deferred_flush(&kvm_xen_enabled);
9928 WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
9929 #endif
9930 mutex_lock(&vendor_module_lock);
9931 kvm_x86_ops.enable_virtualization_cpu = NULL;
9932 mutex_unlock(&vendor_module_lock);
9933 }
9934 EXPORT_SYMBOL_GPL(kvm_x86_vendor_exit);
9935
9936 #ifdef CONFIG_X86_64
kvm_pv_clock_pairing(struct kvm_vcpu * vcpu,gpa_t paddr,unsigned long clock_type)9937 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
9938 unsigned long clock_type)
9939 {
9940 struct kvm_clock_pairing clock_pairing;
9941 struct timespec64 ts;
9942 u64 cycle;
9943 int ret;
9944
9945 if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
9946 return -KVM_EOPNOTSUPP;
9947
9948 /*
9949 * When tsc is in permanent catchup mode guests won't be able to use
9950 * pvclock_read_retry loop to get consistent view of pvclock
9951 */
9952 if (vcpu->arch.tsc_always_catchup)
9953 return -KVM_EOPNOTSUPP;
9954
9955 if (!kvm_get_walltime_and_clockread(&ts, &cycle))
9956 return -KVM_EOPNOTSUPP;
9957
9958 clock_pairing.sec = ts.tv_sec;
9959 clock_pairing.nsec = ts.tv_nsec;
9960 clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
9961 clock_pairing.flags = 0;
9962 memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
9963
9964 ret = 0;
9965 if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
9966 sizeof(struct kvm_clock_pairing)))
9967 ret = -KVM_EFAULT;
9968
9969 return ret;
9970 }
9971 #endif
9972
9973 /*
9974 * kvm_pv_kick_cpu_op: Kick a vcpu.
9975 *
9976 * @apicid - apicid of vcpu to be kicked.
9977 */
kvm_pv_kick_cpu_op(struct kvm * kvm,int apicid)9978 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
9979 {
9980 /*
9981 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
9982 * common code, e.g. for tracing. Defer initialization to the compiler.
9983 */
9984 struct kvm_lapic_irq lapic_irq = {
9985 .delivery_mode = APIC_DM_REMRD,
9986 .dest_mode = APIC_DEST_PHYSICAL,
9987 .shorthand = APIC_DEST_NOSHORT,
9988 .dest_id = apicid,
9989 };
9990
9991 kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
9992 }
9993
kvm_apicv_activated(struct kvm * kvm)9994 bool kvm_apicv_activated(struct kvm *kvm)
9995 {
9996 return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
9997 }
9998 EXPORT_SYMBOL_GPL(kvm_apicv_activated);
9999
kvm_vcpu_apicv_activated(struct kvm_vcpu * vcpu)10000 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
10001 {
10002 ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
10003 ulong vcpu_reasons =
10004 kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
10005
10006 return (vm_reasons | vcpu_reasons) == 0;
10007 }
10008 EXPORT_SYMBOL_GPL(kvm_vcpu_apicv_activated);
10009
set_or_clear_apicv_inhibit(unsigned long * inhibits,enum kvm_apicv_inhibit reason,bool set)10010 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
10011 enum kvm_apicv_inhibit reason, bool set)
10012 {
10013 const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
10014
10015 BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
10016
10017 if (set)
10018 __set_bit(reason, inhibits);
10019 else
10020 __clear_bit(reason, inhibits);
10021
10022 trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
10023 }
10024
kvm_apicv_init(struct kvm * kvm)10025 static void kvm_apicv_init(struct kvm *kvm)
10026 {
10027 enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
10028 APICV_INHIBIT_REASON_DISABLED;
10029
10030 set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
10031
10032 init_rwsem(&kvm->arch.apicv_update_lock);
10033 }
10034
kvm_sched_yield(struct kvm_vcpu * vcpu,unsigned long dest_id)10035 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
10036 {
10037 struct kvm_vcpu *target = NULL;
10038 struct kvm_apic_map *map;
10039
10040 vcpu->stat.directed_yield_attempted++;
10041
10042 if (single_task_running())
10043 goto no_yield;
10044
10045 rcu_read_lock();
10046 map = rcu_dereference(vcpu->kvm->arch.apic_map);
10047
10048 if (likely(map) && dest_id <= map->max_apic_id && map->phys_map[dest_id])
10049 target = map->phys_map[dest_id]->vcpu;
10050
10051 rcu_read_unlock();
10052
10053 if (!target || !READ_ONCE(target->ready))
10054 goto no_yield;
10055
10056 /* Ignore requests to yield to self */
10057 if (vcpu == target)
10058 goto no_yield;
10059
10060 if (kvm_vcpu_yield_to(target) <= 0)
10061 goto no_yield;
10062
10063 vcpu->stat.directed_yield_successful++;
10064
10065 no_yield:
10066 return;
10067 }
10068
complete_hypercall_exit(struct kvm_vcpu * vcpu)10069 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
10070 {
10071 u64 ret = vcpu->run->hypercall.ret;
10072
10073 if (!is_64_bit_hypercall(vcpu))
10074 ret = (u32)ret;
10075 kvm_rax_write(vcpu, ret);
10076 return kvm_skip_emulated_instruction(vcpu);
10077 }
10078
____kvm_emulate_hypercall(struct kvm_vcpu * vcpu,int cpl,int (* complete_hypercall)(struct kvm_vcpu *))10079 int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
10080 int (*complete_hypercall)(struct kvm_vcpu *))
10081 {
10082 unsigned long ret;
10083 unsigned long nr = kvm_rax_read(vcpu);
10084 unsigned long a0 = kvm_rbx_read(vcpu);
10085 unsigned long a1 = kvm_rcx_read(vcpu);
10086 unsigned long a2 = kvm_rdx_read(vcpu);
10087 unsigned long a3 = kvm_rsi_read(vcpu);
10088 int op_64_bit = is_64_bit_hypercall(vcpu);
10089
10090 ++vcpu->stat.hypercalls;
10091
10092 trace_kvm_hypercall(nr, a0, a1, a2, a3);
10093
10094 if (!op_64_bit) {
10095 nr &= 0xFFFFFFFF;
10096 a0 &= 0xFFFFFFFF;
10097 a1 &= 0xFFFFFFFF;
10098 a2 &= 0xFFFFFFFF;
10099 a3 &= 0xFFFFFFFF;
10100 }
10101
10102 if (cpl) {
10103 ret = -KVM_EPERM;
10104 goto out;
10105 }
10106
10107 ret = -KVM_ENOSYS;
10108
10109 switch (nr) {
10110 case KVM_HC_VAPIC_POLL_IRQ:
10111 ret = 0;
10112 break;
10113 case KVM_HC_KICK_CPU:
10114 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10115 break;
10116
10117 kvm_pv_kick_cpu_op(vcpu->kvm, a1);
10118 kvm_sched_yield(vcpu, a1);
10119 ret = 0;
10120 break;
10121 #ifdef CONFIG_X86_64
10122 case KVM_HC_CLOCK_PAIRING:
10123 ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10124 break;
10125 #endif
10126 case KVM_HC_SEND_IPI:
10127 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10128 break;
10129
10130 ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10131 break;
10132 case KVM_HC_SCHED_YIELD:
10133 if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10134 break;
10135
10136 kvm_sched_yield(vcpu, a0);
10137 ret = 0;
10138 break;
10139 case KVM_HC_MAP_GPA_RANGE: {
10140 u64 gpa = a0, npages = a1, attrs = a2;
10141
10142 ret = -KVM_ENOSYS;
10143 if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE))
10144 break;
10145
10146 if (!PAGE_ALIGNED(gpa) || !npages ||
10147 gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10148 ret = -KVM_EINVAL;
10149 break;
10150 }
10151
10152 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
10153 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
10154 /*
10155 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
10156 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
10157 * it was always zero on KVM_EXIT_HYPERCALL. Since KVM is now overwriting
10158 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
10159 */
10160 vcpu->run->hypercall.ret = 0;
10161 vcpu->run->hypercall.args[0] = gpa;
10162 vcpu->run->hypercall.args[1] = npages;
10163 vcpu->run->hypercall.args[2] = attrs;
10164 vcpu->run->hypercall.flags = 0;
10165 if (op_64_bit)
10166 vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10167
10168 WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
10169 vcpu->arch.complete_userspace_io = complete_hypercall;
10170 return 0;
10171 }
10172 default:
10173 ret = -KVM_ENOSYS;
10174 break;
10175 }
10176
10177 out:
10178 vcpu->run->hypercall.ret = ret;
10179 return 1;
10180 }
10181 EXPORT_SYMBOL_GPL(____kvm_emulate_hypercall);
10182
kvm_emulate_hypercall(struct kvm_vcpu * vcpu)10183 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10184 {
10185 if (kvm_xen_hypercall_enabled(vcpu->kvm))
10186 return kvm_xen_hypercall(vcpu);
10187
10188 if (kvm_hv_hypercall_enabled(vcpu))
10189 return kvm_hv_hypercall(vcpu);
10190
10191 return __kvm_emulate_hypercall(vcpu, kvm_x86_call(get_cpl)(vcpu),
10192 complete_hypercall_exit);
10193 }
10194 EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
10195
emulator_fix_hypercall(struct x86_emulate_ctxt * ctxt)10196 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
10197 {
10198 struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
10199 char instruction[3];
10200 unsigned long rip = kvm_rip_read(vcpu);
10201
10202 /*
10203 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10204 * the pieces.
10205 */
10206 if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10207 ctxt->exception.error_code_valid = false;
10208 ctxt->exception.vector = UD_VECTOR;
10209 ctxt->have_exception = true;
10210 return X86EMUL_PROPAGATE_FAULT;
10211 }
10212
10213 kvm_x86_call(patch_hypercall)(vcpu, instruction);
10214
10215 return emulator_write_emulated(ctxt, rip, instruction, 3,
10216 &ctxt->exception);
10217 }
10218
dm_request_for_irq_injection(struct kvm_vcpu * vcpu)10219 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
10220 {
10221 return vcpu->run->request_interrupt_window &&
10222 likely(!pic_in_kernel(vcpu->kvm));
10223 }
10224
10225 /* Called within kvm->srcu read side. */
post_kvm_run_save(struct kvm_vcpu * vcpu)10226 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
10227 {
10228 struct kvm_run *kvm_run = vcpu->run;
10229
10230 kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
10231 kvm_run->cr8 = kvm_get_cr8(vcpu);
10232 kvm_run->apic_base = vcpu->arch.apic_base;
10233
10234 kvm_run->ready_for_interrupt_injection =
10235 pic_in_kernel(vcpu->kvm) ||
10236 kvm_vcpu_ready_for_interrupt_injection(vcpu);
10237
10238 if (is_smm(vcpu))
10239 kvm_run->flags |= KVM_RUN_X86_SMM;
10240 if (is_guest_mode(vcpu))
10241 kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
10242 }
10243
update_cr8_intercept(struct kvm_vcpu * vcpu)10244 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10245 {
10246 int max_irr, tpr;
10247
10248 if (!kvm_x86_ops.update_cr8_intercept)
10249 return;
10250
10251 if (!lapic_in_kernel(vcpu))
10252 return;
10253
10254 if (vcpu->arch.apic->apicv_active)
10255 return;
10256
10257 if (!vcpu->arch.apic->vapic_addr)
10258 max_irr = kvm_lapic_find_highest_irr(vcpu);
10259 else
10260 max_irr = -1;
10261
10262 if (max_irr != -1)
10263 max_irr >>= 4;
10264
10265 tpr = kvm_lapic_get_cr8(vcpu);
10266
10267 kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
10268 }
10269
10270
kvm_check_nested_events(struct kvm_vcpu * vcpu)10271 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10272 {
10273 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10274 kvm_x86_ops.nested_ops->triple_fault(vcpu);
10275 return 1;
10276 }
10277
10278 return kvm_x86_ops.nested_ops->check_events(vcpu);
10279 }
10280
kvm_inject_exception(struct kvm_vcpu * vcpu)10281 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10282 {
10283 /*
10284 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10285 * exceptions don't report error codes. The presence of an error code
10286 * is carried with the exception and only stripped when the exception
10287 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10288 * report an error code despite the CPU being in Real Mode.
10289 */
10290 vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10291
10292 trace_kvm_inj_exception(vcpu->arch.exception.vector,
10293 vcpu->arch.exception.has_error_code,
10294 vcpu->arch.exception.error_code,
10295 vcpu->arch.exception.injected);
10296
10297 kvm_x86_call(inject_exception)(vcpu);
10298 }
10299
10300 /*
10301 * Check for any event (interrupt or exception) that is ready to be injected,
10302 * and if there is at least one event, inject the event with the highest
10303 * priority. This handles both "pending" events, i.e. events that have never
10304 * been injected into the guest, and "injected" events, i.e. events that were
10305 * injected as part of a previous VM-Enter, but weren't successfully delivered
10306 * and need to be re-injected.
10307 *
10308 * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10309 * i.e. doesn't guarantee that there's an event window in the guest. KVM must
10310 * be able to inject exceptions in the "middle" of an instruction, and so must
10311 * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10312 * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10313 * boundaries is necessary and correct.
10314 *
10315 * For simplicity, KVM uses a single path to inject all events (except events
10316 * that are injected directly from L1 to L2) and doesn't explicitly track
10317 * instruction boundaries for asynchronous events. However, because VM-Exits
10318 * that can occur during instruction execution typically result in KVM skipping
10319 * the instruction or injecting an exception, e.g. instruction and exception
10320 * intercepts, and because pending exceptions have higher priority than pending
10321 * interrupts, KVM still honors instruction boundaries in most scenarios.
10322 *
10323 * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10324 * the instruction or inject an exception, then KVM can incorrecty inject a new
10325 * asynchronous event if the event became pending after the CPU fetched the
10326 * instruction (in the guest). E.g. if a page fault (#PF, #NPF, EPT violation)
10327 * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10328 * injected on the restarted instruction instead of being deferred until the
10329 * instruction completes.
10330 *
10331 * In practice, this virtualization hole is unlikely to be observed by the
10332 * guest, and even less likely to cause functional problems. To detect the
10333 * hole, the guest would have to trigger an event on a side effect of an early
10334 * phase of instruction execution, e.g. on the instruction fetch from memory.
10335 * And for it to be a functional problem, the guest would need to depend on the
10336 * ordering between that side effect, the instruction completing, _and_ the
10337 * delivery of the asynchronous event.
10338 */
kvm_check_and_inject_events(struct kvm_vcpu * vcpu,bool * req_immediate_exit)10339 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10340 bool *req_immediate_exit)
10341 {
10342 bool can_inject;
10343 int r;
10344
10345 /*
10346 * Process nested events first, as nested VM-Exit supersedes event
10347 * re-injection. If there's an event queued for re-injection, it will
10348 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10349 */
10350 if (is_guest_mode(vcpu))
10351 r = kvm_check_nested_events(vcpu);
10352 else
10353 r = 0;
10354
10355 /*
10356 * Re-inject exceptions and events *especially* if immediate entry+exit
10357 * to/from L2 is needed, as any event that has already been injected
10358 * into L2 needs to complete its lifecycle before injecting a new event.
10359 *
10360 * Don't re-inject an NMI or interrupt if there is a pending exception.
10361 * This collision arises if an exception occurred while vectoring the
10362 * injected event, KVM intercepted said exception, and KVM ultimately
10363 * determined the fault belongs to the guest and queues the exception
10364 * for injection back into the guest.
10365 *
10366 * "Injected" interrupts can also collide with pending exceptions if
10367 * userspace ignores the "ready for injection" flag and blindly queues
10368 * an interrupt. In that case, prioritizing the exception is correct,
10369 * as the exception "occurred" before the exit to userspace. Trap-like
10370 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10371 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10372 * priority, they're only generated (pended) during instruction
10373 * execution, and interrupts are recognized at instruction boundaries.
10374 * Thus a pending fault-like exception means the fault occurred on the
10375 * *previous* instruction and must be serviced prior to recognizing any
10376 * new events in order to fully complete the previous instruction.
10377 */
10378 if (vcpu->arch.exception.injected)
10379 kvm_inject_exception(vcpu);
10380 else if (kvm_is_exception_pending(vcpu))
10381 ; /* see above */
10382 else if (vcpu->arch.nmi_injected)
10383 kvm_x86_call(inject_nmi)(vcpu);
10384 else if (vcpu->arch.interrupt.injected)
10385 kvm_x86_call(inject_irq)(vcpu, true);
10386
10387 /*
10388 * Exceptions that morph to VM-Exits are handled above, and pending
10389 * exceptions on top of injected exceptions that do not VM-Exit should
10390 * either morph to #DF or, sadly, override the injected exception.
10391 */
10392 WARN_ON_ONCE(vcpu->arch.exception.injected &&
10393 vcpu->arch.exception.pending);
10394
10395 /*
10396 * Bail if immediate entry+exit to/from the guest is needed to complete
10397 * nested VM-Enter or event re-injection so that a different pending
10398 * event can be serviced (or if KVM needs to exit to userspace).
10399 *
10400 * Otherwise, continue processing events even if VM-Exit occurred. The
10401 * VM-Exit will have cleared exceptions that were meant for L2, but
10402 * there may now be events that can be injected into L1.
10403 */
10404 if (r < 0)
10405 goto out;
10406
10407 /*
10408 * A pending exception VM-Exit should either result in nested VM-Exit
10409 * or force an immediate re-entry and exit to/from L2, and exception
10410 * VM-Exits cannot be injected (flag should _never_ be set).
10411 */
10412 WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10413 vcpu->arch.exception_vmexit.pending);
10414
10415 /*
10416 * New events, other than exceptions, cannot be injected if KVM needs
10417 * to re-inject a previous event. See above comments on re-injecting
10418 * for why pending exceptions get priority.
10419 */
10420 can_inject = !kvm_event_needs_reinjection(vcpu);
10421
10422 if (vcpu->arch.exception.pending) {
10423 /*
10424 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10425 * value pushed on the stack. Trap-like exception and all #DBs
10426 * leave RF as-is (KVM follows Intel's behavior in this regard;
10427 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10428 *
10429 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10430 * describe the behavior of General Detect #DBs, which are
10431 * fault-like. They do _not_ set RF, a la code breakpoints.
10432 */
10433 if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10434 __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10435 X86_EFLAGS_RF);
10436
10437 if (vcpu->arch.exception.vector == DB_VECTOR) {
10438 kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
10439 if (vcpu->arch.dr7 & DR7_GD) {
10440 vcpu->arch.dr7 &= ~DR7_GD;
10441 kvm_update_dr7(vcpu);
10442 }
10443 }
10444
10445 kvm_inject_exception(vcpu);
10446
10447 vcpu->arch.exception.pending = false;
10448 vcpu->arch.exception.injected = true;
10449
10450 can_inject = false;
10451 }
10452
10453 /* Don't inject interrupts if the user asked to avoid doing so */
10454 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10455 return 0;
10456
10457 /*
10458 * Finally, inject interrupt events. If an event cannot be injected
10459 * due to architectural conditions (e.g. IF=0) a window-open exit
10460 * will re-request KVM_REQ_EVENT. Sometimes however an event is pending
10461 * and can architecturally be injected, but we cannot do it right now:
10462 * an interrupt could have arrived just now and we have to inject it
10463 * as a vmexit, or there could already an event in the queue, which is
10464 * indicated by can_inject. In that case we request an immediate exit
10465 * in order to make progress and get back here for another iteration.
10466 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10467 */
10468 #ifdef CONFIG_KVM_SMM
10469 if (vcpu->arch.smi_pending) {
10470 r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
10471 -EBUSY;
10472 if (r < 0)
10473 goto out;
10474 if (r) {
10475 vcpu->arch.smi_pending = false;
10476 ++vcpu->arch.smi_count;
10477 enter_smm(vcpu);
10478 can_inject = false;
10479 } else
10480 kvm_x86_call(enable_smi_window)(vcpu);
10481 }
10482 #endif
10483
10484 if (vcpu->arch.nmi_pending) {
10485 r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
10486 -EBUSY;
10487 if (r < 0)
10488 goto out;
10489 if (r) {
10490 --vcpu->arch.nmi_pending;
10491 vcpu->arch.nmi_injected = true;
10492 kvm_x86_call(inject_nmi)(vcpu);
10493 can_inject = false;
10494 WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
10495 }
10496 if (vcpu->arch.nmi_pending)
10497 kvm_x86_call(enable_nmi_window)(vcpu);
10498 }
10499
10500 if (kvm_cpu_has_injectable_intr(vcpu)) {
10501 r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
10502 -EBUSY;
10503 if (r < 0)
10504 goto out;
10505 if (r) {
10506 int irq = kvm_cpu_get_interrupt(vcpu);
10507
10508 if (!WARN_ON_ONCE(irq == -1)) {
10509 kvm_queue_interrupt(vcpu, irq, false);
10510 kvm_x86_call(inject_irq)(vcpu, false);
10511 WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
10512 }
10513 }
10514 if (kvm_cpu_has_injectable_intr(vcpu))
10515 kvm_x86_call(enable_irq_window)(vcpu);
10516 }
10517
10518 if (is_guest_mode(vcpu) &&
10519 kvm_x86_ops.nested_ops->has_events &&
10520 kvm_x86_ops.nested_ops->has_events(vcpu, true))
10521 *req_immediate_exit = true;
10522
10523 /*
10524 * KVM must never queue a new exception while injecting an event; KVM
10525 * is done emulating and should only propagate the to-be-injected event
10526 * to the VMCS/VMCB. Queueing a new exception can put the vCPU into an
10527 * infinite loop as KVM will bail from VM-Enter to inject the pending
10528 * exception and start the cycle all over.
10529 *
10530 * Exempt triple faults as they have special handling and won't put the
10531 * vCPU into an infinite loop. Triple fault can be queued when running
10532 * VMX without unrestricted guest, as that requires KVM to emulate Real
10533 * Mode events (see kvm_inject_realmode_interrupt()).
10534 */
10535 WARN_ON_ONCE(vcpu->arch.exception.pending ||
10536 vcpu->arch.exception_vmexit.pending);
10537 return 0;
10538
10539 out:
10540 if (r == -EBUSY) {
10541 *req_immediate_exit = true;
10542 r = 0;
10543 }
10544 return r;
10545 }
10546
process_nmi(struct kvm_vcpu * vcpu)10547 static void process_nmi(struct kvm_vcpu *vcpu)
10548 {
10549 unsigned int limit;
10550
10551 /*
10552 * x86 is limited to one NMI pending, but because KVM can't react to
10553 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10554 * scheduled out, KVM needs to play nice with two queued NMIs showing
10555 * up at the same time. To handle this scenario, allow two NMIs to be
10556 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10557 * waiting for a previous NMI injection to complete (which effectively
10558 * blocks NMIs). KVM will immediately inject one of the two NMIs, and
10559 * will request an NMI window to handle the second NMI.
10560 */
10561 if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10562 limit = 1;
10563 else
10564 limit = 2;
10565
10566 /*
10567 * Adjust the limit to account for pending virtual NMIs, which aren't
10568 * tracked in vcpu->arch.nmi_pending.
10569 */
10570 if (kvm_x86_call(is_vnmi_pending)(vcpu))
10571 limit--;
10572
10573 vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10574 vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10575
10576 if (vcpu->arch.nmi_pending &&
10577 (kvm_x86_call(set_vnmi_pending)(vcpu)))
10578 vcpu->arch.nmi_pending--;
10579
10580 if (vcpu->arch.nmi_pending)
10581 kvm_make_request(KVM_REQ_EVENT, vcpu);
10582 }
10583
10584 /* Return total number of NMIs pending injection to the VM */
kvm_get_nr_pending_nmis(struct kvm_vcpu * vcpu)10585 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10586 {
10587 return vcpu->arch.nmi_pending +
10588 kvm_x86_call(is_vnmi_pending)(vcpu);
10589 }
10590
kvm_make_scan_ioapic_request_mask(struct kvm * kvm,unsigned long * vcpu_bitmap)10591 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10592 unsigned long *vcpu_bitmap)
10593 {
10594 kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10595 }
10596
kvm_make_scan_ioapic_request(struct kvm * kvm)10597 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10598 {
10599 kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10600 }
10601
__kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10602 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10603 {
10604 struct kvm_lapic *apic = vcpu->arch.apic;
10605 bool activate;
10606
10607 if (!lapic_in_kernel(vcpu))
10608 return;
10609
10610 down_read(&vcpu->kvm->arch.apicv_update_lock);
10611 preempt_disable();
10612
10613 /* Do not activate APICV when APIC is disabled */
10614 activate = kvm_vcpu_apicv_activated(vcpu) &&
10615 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10616
10617 if (apic->apicv_active == activate)
10618 goto out;
10619
10620 apic->apicv_active = activate;
10621 kvm_apic_update_apicv(vcpu);
10622 kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
10623
10624 /*
10625 * When APICv gets disabled, we may still have injected interrupts
10626 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10627 * still active when the interrupt got accepted. Make sure
10628 * kvm_check_and_inject_events() is called to check for that.
10629 */
10630 if (!apic->apicv_active)
10631 kvm_make_request(KVM_REQ_EVENT, vcpu);
10632
10633 out:
10634 preempt_enable();
10635 up_read(&vcpu->kvm->arch.apicv_update_lock);
10636 }
10637 EXPORT_SYMBOL_GPL(__kvm_vcpu_update_apicv);
10638
kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10639 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10640 {
10641 if (!lapic_in_kernel(vcpu))
10642 return;
10643
10644 /*
10645 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10646 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10647 * and hardware doesn't support x2APIC virtualization. E.g. some AMD
10648 * CPUs support AVIC but not x2APIC. KVM still allows enabling AVIC in
10649 * this case so that KVM can use the AVIC doorbell to inject interrupts
10650 * to running vCPUs, but KVM must not create SPTEs for the APIC base as
10651 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
10652 * despite being in x2APIC mode. For simplicity, inhibiting the APIC
10653 * access page is sticky.
10654 */
10655 if (apic_x2apic_mode(vcpu->arch.apic) &&
10656 kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
10657 kvm_inhibit_apic_access_page(vcpu);
10658
10659 __kvm_vcpu_update_apicv(vcpu);
10660 }
10661
__kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10662 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10663 enum kvm_apicv_inhibit reason, bool set)
10664 {
10665 unsigned long old, new;
10666
10667 lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10668
10669 if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
10670 return;
10671
10672 old = new = kvm->arch.apicv_inhibit_reasons;
10673
10674 set_or_clear_apicv_inhibit(&new, reason, set);
10675
10676 if (!!old != !!new) {
10677 /*
10678 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10679 * false positives in the sanity check WARN in vcpu_enter_guest().
10680 * This task will wait for all vCPUs to ack the kick IRQ before
10681 * updating apicv_inhibit_reasons, and all other vCPUs will
10682 * block on acquiring apicv_update_lock so that vCPUs can't
10683 * redo vcpu_enter_guest() without seeing the new inhibit state.
10684 *
10685 * Note, holding apicv_update_lock and taking it in the read
10686 * side (handling the request) also prevents other vCPUs from
10687 * servicing the request with a stale apicv_inhibit_reasons.
10688 */
10689 kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10690 kvm->arch.apicv_inhibit_reasons = new;
10691 if (new) {
10692 unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10693 int idx = srcu_read_lock(&kvm->srcu);
10694
10695 kvm_zap_gfn_range(kvm, gfn, gfn+1);
10696 srcu_read_unlock(&kvm->srcu, idx);
10697 }
10698 } else {
10699 kvm->arch.apicv_inhibit_reasons = new;
10700 }
10701 }
10702
kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10703 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10704 enum kvm_apicv_inhibit reason, bool set)
10705 {
10706 if (!enable_apicv)
10707 return;
10708
10709 down_write(&kvm->arch.apicv_update_lock);
10710 __kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10711 up_write(&kvm->arch.apicv_update_lock);
10712 }
10713 EXPORT_SYMBOL_GPL(kvm_set_or_clear_apicv_inhibit);
10714
vcpu_scan_ioapic(struct kvm_vcpu * vcpu)10715 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10716 {
10717 if (!kvm_apic_present(vcpu))
10718 return;
10719
10720 bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10721 vcpu->arch.highest_stale_pending_ioapic_eoi = -1;
10722
10723 kvm_x86_call(sync_pir_to_irr)(vcpu);
10724
10725 if (irqchip_split(vcpu->kvm))
10726 kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
10727 else if (ioapic_in_kernel(vcpu->kvm))
10728 kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
10729
10730 if (is_guest_mode(vcpu))
10731 vcpu->arch.load_eoi_exitmap_pending = true;
10732 else
10733 kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10734 }
10735
vcpu_load_eoi_exitmap(struct kvm_vcpu * vcpu)10736 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10737 {
10738 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10739 return;
10740
10741 #ifdef CONFIG_KVM_HYPERV
10742 if (to_hv_vcpu(vcpu)) {
10743 u64 eoi_exit_bitmap[4];
10744
10745 bitmap_or((ulong *)eoi_exit_bitmap,
10746 vcpu->arch.ioapic_handled_vectors,
10747 to_hv_synic(vcpu)->vec_bitmap, 256);
10748 kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
10749 return;
10750 }
10751 #endif
10752 kvm_x86_call(load_eoi_exitmap)(
10753 vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
10754 }
10755
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)10756 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
10757 {
10758 kvm_x86_call(guest_memory_reclaimed)(kvm);
10759 }
10760
kvm_vcpu_reload_apic_access_page(struct kvm_vcpu * vcpu)10761 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
10762 {
10763 if (!lapic_in_kernel(vcpu))
10764 return;
10765
10766 kvm_x86_call(set_apic_access_page_addr)(vcpu);
10767 }
10768
10769 /*
10770 * Called within kvm->srcu read side.
10771 * Returns 1 to let vcpu_run() continue the guest execution loop without
10772 * exiting to the userspace. Otherwise, the value will be returned to the
10773 * userspace.
10774 */
vcpu_enter_guest(struct kvm_vcpu * vcpu)10775 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
10776 {
10777 int r;
10778 bool req_int_win =
10779 dm_request_for_irq_injection(vcpu) &&
10780 kvm_cpu_accept_dm_intr(vcpu);
10781 fastpath_t exit_fastpath;
10782
10783 bool req_immediate_exit = false;
10784
10785 if (kvm_request_pending(vcpu)) {
10786 if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
10787 r = -EIO;
10788 goto out;
10789 }
10790
10791 if (kvm_dirty_ring_check_request(vcpu)) {
10792 r = 0;
10793 goto out;
10794 }
10795
10796 if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
10797 if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
10798 r = 0;
10799 goto out;
10800 }
10801 }
10802 if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
10803 kvm_mmu_free_obsolete_roots(vcpu);
10804 if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
10805 __kvm_migrate_timers(vcpu);
10806 if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
10807 kvm_update_masterclock(vcpu->kvm);
10808 if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
10809 kvm_gen_kvmclock_update(vcpu);
10810 if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
10811 r = kvm_guest_time_update(vcpu);
10812 if (unlikely(r))
10813 goto out;
10814 }
10815 if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
10816 kvm_mmu_sync_roots(vcpu);
10817 if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
10818 kvm_mmu_load_pgd(vcpu);
10819
10820 /*
10821 * Note, the order matters here, as flushing "all" TLB entries
10822 * also flushes the "current" TLB entries, i.e. servicing the
10823 * flush "all" will clear any request to flush "current".
10824 */
10825 if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
10826 kvm_vcpu_flush_tlb_all(vcpu);
10827
10828 kvm_service_local_tlb_flush_requests(vcpu);
10829
10830 /*
10831 * Fall back to a "full" guest flush if Hyper-V's precise
10832 * flushing fails. Note, Hyper-V's flushing is per-vCPU, but
10833 * the flushes are considered "remote" and not "local" because
10834 * the requests can be initiated from other vCPUs.
10835 */
10836 #ifdef CONFIG_KVM_HYPERV
10837 if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
10838 kvm_hv_vcpu_flush_tlb(vcpu))
10839 kvm_vcpu_flush_tlb_guest(vcpu);
10840 #endif
10841
10842 if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
10843 vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
10844 r = 0;
10845 goto out;
10846 }
10847 if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10848 if (is_guest_mode(vcpu))
10849 kvm_x86_ops.nested_ops->triple_fault(vcpu);
10850
10851 if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10852 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
10853 vcpu->mmio_needed = 0;
10854 r = 0;
10855 goto out;
10856 }
10857 }
10858 if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
10859 /* Page is swapped out. Do synthetic halt */
10860 vcpu->arch.apf.halted = true;
10861 r = 1;
10862 goto out;
10863 }
10864 if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
10865 record_steal_time(vcpu);
10866 if (kvm_check_request(KVM_REQ_PMU, vcpu))
10867 kvm_pmu_handle_event(vcpu);
10868 if (kvm_check_request(KVM_REQ_PMI, vcpu))
10869 kvm_pmu_deliver_pmi(vcpu);
10870 #ifdef CONFIG_KVM_SMM
10871 if (kvm_check_request(KVM_REQ_SMI, vcpu))
10872 process_smi(vcpu);
10873 #endif
10874 if (kvm_check_request(KVM_REQ_NMI, vcpu))
10875 process_nmi(vcpu);
10876 if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
10877 BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
10878 if (test_bit(vcpu->arch.pending_ioapic_eoi,
10879 vcpu->arch.ioapic_handled_vectors)) {
10880 vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
10881 vcpu->run->eoi.vector =
10882 vcpu->arch.pending_ioapic_eoi;
10883 r = 0;
10884 goto out;
10885 }
10886 }
10887 if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
10888 vcpu_scan_ioapic(vcpu);
10889 if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
10890 vcpu_load_eoi_exitmap(vcpu);
10891 if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
10892 kvm_vcpu_reload_apic_access_page(vcpu);
10893 #ifdef CONFIG_KVM_HYPERV
10894 if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
10895 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10896 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
10897 vcpu->run->system_event.ndata = 0;
10898 r = 0;
10899 goto out;
10900 }
10901 if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
10902 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
10903 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
10904 vcpu->run->system_event.ndata = 0;
10905 r = 0;
10906 goto out;
10907 }
10908 if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
10909 struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
10910
10911 vcpu->run->exit_reason = KVM_EXIT_HYPERV;
10912 vcpu->run->hyperv = hv_vcpu->exit;
10913 r = 0;
10914 goto out;
10915 }
10916
10917 /*
10918 * KVM_REQ_HV_STIMER has to be processed after
10919 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
10920 * depend on the guest clock being up-to-date
10921 */
10922 if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
10923 kvm_hv_process_stimers(vcpu);
10924 #endif
10925 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
10926 kvm_vcpu_update_apicv(vcpu);
10927 if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
10928 kvm_check_async_pf_completion(vcpu);
10929 if (kvm_check_request(KVM_REQ_MSR_FILTER_CHANGED, vcpu))
10930 kvm_x86_call(msr_filter_changed)(vcpu);
10931
10932 if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
10933 kvm_x86_call(update_cpu_dirty_logging)(vcpu);
10934
10935 if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
10936 kvm_vcpu_reset(vcpu, true);
10937 if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
10938 r = 1;
10939 goto out;
10940 }
10941 }
10942 }
10943
10944 if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
10945 kvm_xen_has_interrupt(vcpu)) {
10946 ++vcpu->stat.req_event;
10947 r = kvm_apic_accept_events(vcpu);
10948 if (r < 0) {
10949 r = 0;
10950 goto out;
10951 }
10952 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
10953 r = 1;
10954 goto out;
10955 }
10956
10957 r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
10958 if (r < 0) {
10959 r = 0;
10960 goto out;
10961 }
10962 if (req_int_win)
10963 kvm_x86_call(enable_irq_window)(vcpu);
10964
10965 if (kvm_lapic_enabled(vcpu)) {
10966 update_cr8_intercept(vcpu);
10967 kvm_lapic_sync_to_vapic(vcpu);
10968 }
10969 }
10970
10971 r = kvm_mmu_reload(vcpu);
10972 if (unlikely(r)) {
10973 goto cancel_injection;
10974 }
10975
10976 preempt_disable();
10977
10978 kvm_x86_call(prepare_switch_to_guest)(vcpu);
10979
10980 /*
10981 * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
10982 * IPI are then delayed after guest entry, which ensures that they
10983 * result in virtual interrupt delivery.
10984 */
10985 local_irq_disable();
10986
10987 /* Store vcpu->apicv_active before vcpu->mode. */
10988 smp_store_release(&vcpu->mode, IN_GUEST_MODE);
10989
10990 kvm_vcpu_srcu_read_unlock(vcpu);
10991
10992 /*
10993 * 1) We should set ->mode before checking ->requests. Please see
10994 * the comment in kvm_vcpu_exiting_guest_mode().
10995 *
10996 * 2) For APICv, we should set ->mode before checking PID.ON. This
10997 * pairs with the memory barrier implicit in pi_test_and_set_on
10998 * (see vmx_deliver_posted_interrupt).
10999 *
11000 * 3) This also orders the write to mode from any reads to the page
11001 * tables done while the VCPU is running. Please see the comment
11002 * in kvm_flush_remote_tlbs.
11003 */
11004 smp_mb__after_srcu_read_unlock();
11005
11006 /*
11007 * Process pending posted interrupts to handle the case where the
11008 * notification IRQ arrived in the host, or was never sent (because the
11009 * target vCPU wasn't running). Do this regardless of the vCPU's APICv
11010 * status, KVM doesn't update assigned devices when APICv is inhibited,
11011 * i.e. they can post interrupts even if APICv is temporarily disabled.
11012 */
11013 if (kvm_lapic_enabled(vcpu))
11014 kvm_x86_call(sync_pir_to_irr)(vcpu);
11015
11016 if (kvm_vcpu_exit_request(vcpu)) {
11017 vcpu->mode = OUTSIDE_GUEST_MODE;
11018 smp_wmb();
11019 local_irq_enable();
11020 preempt_enable();
11021 kvm_vcpu_srcu_read_lock(vcpu);
11022 r = 1;
11023 goto cancel_injection;
11024 }
11025
11026 if (req_immediate_exit)
11027 kvm_make_request(KVM_REQ_EVENT, vcpu);
11028
11029 fpregs_assert_state_consistent();
11030 if (test_thread_flag(TIF_NEED_FPU_LOAD))
11031 switch_fpu_return();
11032
11033 if (vcpu->arch.guest_fpu.xfd_err)
11034 wrmsrq(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
11035
11036 if (unlikely(vcpu->arch.switch_db_regs &&
11037 !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
11038 set_debugreg(0, 7);
11039 set_debugreg(vcpu->arch.eff_db[0], 0);
11040 set_debugreg(vcpu->arch.eff_db[1], 1);
11041 set_debugreg(vcpu->arch.eff_db[2], 2);
11042 set_debugreg(vcpu->arch.eff_db[3], 3);
11043 /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
11044 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
11045 kvm_x86_call(set_dr6)(vcpu, vcpu->arch.dr6);
11046 } else if (unlikely(hw_breakpoint_active())) {
11047 set_debugreg(0, 7);
11048 }
11049
11050 vcpu->arch.host_debugctl = get_debugctlmsr();
11051
11052 guest_timing_enter_irqoff();
11053
11054 for (;;) {
11055 /*
11056 * Assert that vCPU vs. VM APICv state is consistent. An APICv
11057 * update must kick and wait for all vCPUs before toggling the
11058 * per-VM state, and responding vCPUs must wait for the update
11059 * to complete before servicing KVM_REQ_APICV_UPDATE.
11060 */
11061 WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11062 (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
11063
11064 exit_fastpath = kvm_x86_call(vcpu_run)(vcpu,
11065 req_immediate_exit);
11066 if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11067 break;
11068
11069 if (kvm_lapic_enabled(vcpu))
11070 kvm_x86_call(sync_pir_to_irr)(vcpu);
11071
11072 if (unlikely(kvm_vcpu_exit_request(vcpu))) {
11073 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11074 break;
11075 }
11076
11077 /* Note, VM-Exits that go down the "slow" path are accounted below. */
11078 ++vcpu->stat.exits;
11079 }
11080
11081 /*
11082 * Do this here before restoring debug registers on the host. And
11083 * since we do this before handling the vmexit, a DR access vmexit
11084 * can (a) read the correct value of the debug registers, (b) set
11085 * KVM_DEBUGREG_WONT_EXIT again.
11086 */
11087 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
11088 WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
11089 WARN_ON(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH);
11090 kvm_x86_call(sync_dirty_debug_regs)(vcpu);
11091 kvm_update_dr0123(vcpu);
11092 kvm_update_dr7(vcpu);
11093 }
11094
11095 /*
11096 * If the guest has used debug registers, at least dr7
11097 * will be disabled while returning to the host.
11098 * If we don't have active breakpoints in the host, we don't
11099 * care about the messed up debug address registers. But if
11100 * we have some of them active, restore the old state.
11101 */
11102 if (hw_breakpoint_active())
11103 hw_breakpoint_restore();
11104
11105 vcpu->arch.last_vmentry_cpu = vcpu->cpu;
11106 vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
11107
11108 vcpu->mode = OUTSIDE_GUEST_MODE;
11109 smp_wmb();
11110
11111 /*
11112 * Sync xfd before calling handle_exit_irqoff() which may
11113 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11114 * in #NM irqoff handler).
11115 */
11116 if (vcpu->arch.xfd_no_write_intercept)
11117 fpu_sync_guest_vmexit_xfd_state();
11118
11119 kvm_x86_call(handle_exit_irqoff)(vcpu);
11120
11121 if (vcpu->arch.guest_fpu.xfd_err)
11122 wrmsrq(MSR_IA32_XFD_ERR, 0);
11123
11124 /*
11125 * Consume any pending interrupts, including the possible source of
11126 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11127 * An instruction is required after local_irq_enable() to fully unblock
11128 * interrupts on processors that implement an interrupt shadow, the
11129 * stat.exits increment will do nicely.
11130 */
11131 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
11132 local_irq_enable();
11133 ++vcpu->stat.exits;
11134 local_irq_disable();
11135 kvm_after_interrupt(vcpu);
11136
11137 /*
11138 * Wait until after servicing IRQs to account guest time so that any
11139 * ticks that occurred while running the guest are properly accounted
11140 * to the guest. Waiting until IRQs are enabled degrades the accuracy
11141 * of accounting via context tracking, but the loss of accuracy is
11142 * acceptable for all known use cases.
11143 */
11144 guest_timing_exit_irqoff();
11145
11146 local_irq_enable();
11147 preempt_enable();
11148
11149 kvm_vcpu_srcu_read_lock(vcpu);
11150
11151 /*
11152 * Call this to ensure WC buffers in guest are evicted after each VM
11153 * Exit, so that the evicted WC writes can be snooped across all cpus
11154 */
11155 smp_mb__after_srcu_read_lock();
11156
11157 /*
11158 * Profile KVM exit RIPs:
11159 */
11160 if (unlikely(prof_on == KVM_PROFILING &&
11161 !vcpu->arch.guest_state_protected)) {
11162 unsigned long rip = kvm_rip_read(vcpu);
11163 profile_hit(KVM_PROFILING, (void *)rip);
11164 }
11165
11166 if (unlikely(vcpu->arch.tsc_always_catchup))
11167 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11168
11169 if (vcpu->arch.apic_attention)
11170 kvm_lapic_sync_from_vapic(vcpu);
11171
11172 if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
11173 return 0;
11174
11175 r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
11176 return r;
11177
11178 cancel_injection:
11179 if (req_immediate_exit)
11180 kvm_make_request(KVM_REQ_EVENT, vcpu);
11181 kvm_x86_call(cancel_injection)(vcpu);
11182 if (unlikely(vcpu->arch.apic_attention))
11183 kvm_lapic_sync_from_vapic(vcpu);
11184 out:
11185 return r;
11186 }
11187
kvm_vcpu_running(struct kvm_vcpu * vcpu)11188 static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11189 {
11190 return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11191 !vcpu->arch.apf.halted);
11192 }
11193
kvm_vcpu_has_events(struct kvm_vcpu * vcpu)11194 bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
11195 {
11196 if (!list_empty_careful(&vcpu->async_pf.done))
11197 return true;
11198
11199 if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
11200 kvm_apic_init_sipi_allowed(vcpu))
11201 return true;
11202
11203 if (kvm_is_exception_pending(vcpu))
11204 return true;
11205
11206 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11207 (vcpu->arch.nmi_pending &&
11208 kvm_x86_call(nmi_allowed)(vcpu, false)))
11209 return true;
11210
11211 #ifdef CONFIG_KVM_SMM
11212 if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11213 (vcpu->arch.smi_pending &&
11214 kvm_x86_call(smi_allowed)(vcpu, false)))
11215 return true;
11216 #endif
11217
11218 if (kvm_test_request(KVM_REQ_PMI, vcpu))
11219 return true;
11220
11221 if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
11222 return true;
11223
11224 if (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
11225 return true;
11226
11227 if (kvm_hv_has_stimer_pending(vcpu))
11228 return true;
11229
11230 if (is_guest_mode(vcpu) &&
11231 kvm_x86_ops.nested_ops->has_events &&
11232 kvm_x86_ops.nested_ops->has_events(vcpu, false))
11233 return true;
11234
11235 if (kvm_xen_has_pending_events(vcpu))
11236 return true;
11237
11238 return false;
11239 }
11240 EXPORT_SYMBOL_GPL(kvm_vcpu_has_events);
11241
kvm_arch_vcpu_runnable(struct kvm_vcpu * vcpu)11242 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11243 {
11244 return kvm_vcpu_running(vcpu) || vcpu->arch.pv.pv_unhalted ||
11245 kvm_vcpu_has_events(vcpu);
11246 }
11247
11248 /* Called within kvm->srcu read side. */
vcpu_block(struct kvm_vcpu * vcpu)11249 static inline int vcpu_block(struct kvm_vcpu *vcpu)
11250 {
11251 bool hv_timer;
11252
11253 if (!kvm_arch_vcpu_runnable(vcpu)) {
11254 /*
11255 * Switch to the software timer before halt-polling/blocking as
11256 * the guest's timer may be a break event for the vCPU, and the
11257 * hypervisor timer runs only when the CPU is in guest mode.
11258 * Switch before halt-polling so that KVM recognizes an expired
11259 * timer before blocking.
11260 */
11261 hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11262 if (hv_timer)
11263 kvm_lapic_switch_to_sw_timer(vcpu);
11264
11265 kvm_vcpu_srcu_read_unlock(vcpu);
11266 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11267 kvm_vcpu_halt(vcpu);
11268 else
11269 kvm_vcpu_block(vcpu);
11270 kvm_vcpu_srcu_read_lock(vcpu);
11271
11272 if (hv_timer)
11273 kvm_lapic_switch_to_hv_timer(vcpu);
11274
11275 /*
11276 * If the vCPU is not runnable, a signal or another host event
11277 * of some kind is pending; service it without changing the
11278 * vCPU's activity state.
11279 */
11280 if (!kvm_arch_vcpu_runnable(vcpu))
11281 return 1;
11282 }
11283
11284 /*
11285 * Evaluate nested events before exiting the halted state. This allows
11286 * the halt state to be recorded properly in the VMCS12's activity
11287 * state field (AMD does not have a similar field and a VM-Exit always
11288 * causes a spurious wakeup from HLT).
11289 */
11290 if (is_guest_mode(vcpu)) {
11291 int r = kvm_check_nested_events(vcpu);
11292
11293 WARN_ON_ONCE(r == -EBUSY);
11294 if (r < 0)
11295 return 0;
11296 }
11297
11298 if (kvm_apic_accept_events(vcpu) < 0)
11299 return 0;
11300 switch(vcpu->arch.mp_state) {
11301 case KVM_MP_STATE_HALTED:
11302 case KVM_MP_STATE_AP_RESET_HOLD:
11303 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
11304 fallthrough;
11305 case KVM_MP_STATE_RUNNABLE:
11306 vcpu->arch.apf.halted = false;
11307 break;
11308 case KVM_MP_STATE_INIT_RECEIVED:
11309 break;
11310 default:
11311 WARN_ON_ONCE(1);
11312 break;
11313 }
11314 return 1;
11315 }
11316
11317 /* Called within kvm->srcu read side. */
vcpu_run(struct kvm_vcpu * vcpu)11318 static int vcpu_run(struct kvm_vcpu *vcpu)
11319 {
11320 int r;
11321
11322 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
11323
11324 for (;;) {
11325 /*
11326 * If another guest vCPU requests a PV TLB flush in the middle
11327 * of instruction emulation, the rest of the emulation could
11328 * use a stale page translation. Assume that any code after
11329 * this point can start executing an instruction.
11330 */
11331 vcpu->arch.at_instruction_boundary = false;
11332 if (kvm_vcpu_running(vcpu)) {
11333 r = vcpu_enter_guest(vcpu);
11334 } else {
11335 r = vcpu_block(vcpu);
11336 }
11337
11338 if (r <= 0)
11339 break;
11340
11341 kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11342 if (kvm_xen_has_pending_events(vcpu))
11343 kvm_xen_inject_pending_events(vcpu);
11344
11345 if (kvm_cpu_has_pending_timer(vcpu))
11346 kvm_inject_pending_timer_irqs(vcpu);
11347
11348 if (dm_request_for_irq_injection(vcpu) &&
11349 kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11350 r = 0;
11351 vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11352 ++vcpu->stat.request_irq_exits;
11353 break;
11354 }
11355
11356 if (__xfer_to_guest_mode_work_pending()) {
11357 kvm_vcpu_srcu_read_unlock(vcpu);
11358 r = xfer_to_guest_mode_handle_work(vcpu);
11359 kvm_vcpu_srcu_read_lock(vcpu);
11360 if (r)
11361 return r;
11362 }
11363 }
11364
11365 return r;
11366 }
11367
__kvm_emulate_halt(struct kvm_vcpu * vcpu,int state,int reason)11368 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
11369 {
11370 /*
11371 * The vCPU has halted, e.g. executed HLT. Update the run state if the
11372 * local APIC is in-kernel, the run loop will detect the non-runnable
11373 * state and halt the vCPU. Exit to userspace if the local APIC is
11374 * managed by userspace, in which case userspace is responsible for
11375 * handling wake events.
11376 */
11377 ++vcpu->stat.halt_exits;
11378 if (lapic_in_kernel(vcpu)) {
11379 if (kvm_vcpu_has_events(vcpu) || vcpu->arch.pv.pv_unhalted)
11380 state = KVM_MP_STATE_RUNNABLE;
11381 kvm_set_mp_state(vcpu, state);
11382 return 1;
11383 } else {
11384 vcpu->run->exit_reason = reason;
11385 return 0;
11386 }
11387 }
11388
kvm_emulate_halt_noskip(struct kvm_vcpu * vcpu)11389 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
11390 {
11391 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
11392 }
11393 EXPORT_SYMBOL_GPL(kvm_emulate_halt_noskip);
11394
kvm_emulate_halt(struct kvm_vcpu * vcpu)11395 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
11396 {
11397 int ret = kvm_skip_emulated_instruction(vcpu);
11398 /*
11399 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
11400 * KVM_EXIT_DEBUG here.
11401 */
11402 return kvm_emulate_halt_noskip(vcpu) && ret;
11403 }
11404 EXPORT_SYMBOL_GPL(kvm_emulate_halt);
11405
handle_fastpath_hlt(struct kvm_vcpu * vcpu)11406 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
11407 {
11408 int ret;
11409
11410 kvm_vcpu_srcu_read_lock(vcpu);
11411 ret = kvm_emulate_halt(vcpu);
11412 kvm_vcpu_srcu_read_unlock(vcpu);
11413
11414 if (!ret)
11415 return EXIT_FASTPATH_EXIT_USERSPACE;
11416
11417 if (kvm_vcpu_running(vcpu))
11418 return EXIT_FASTPATH_REENTER_GUEST;
11419
11420 return EXIT_FASTPATH_EXIT_HANDLED;
11421 }
11422 EXPORT_SYMBOL_GPL(handle_fastpath_hlt);
11423
kvm_emulate_ap_reset_hold(struct kvm_vcpu * vcpu)11424 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
11425 {
11426 int ret = kvm_skip_emulated_instruction(vcpu);
11427
11428 return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
11429 KVM_EXIT_AP_RESET_HOLD) && ret;
11430 }
11431 EXPORT_SYMBOL_GPL(kvm_emulate_ap_reset_hold);
11432
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)11433 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
11434 {
11435 return kvm_vcpu_apicv_active(vcpu) &&
11436 kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
11437 }
11438
kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu * vcpu)11439 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
11440 {
11441 return vcpu->arch.preempted_in_kernel;
11442 }
11443
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)11444 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11445 {
11446 if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11447 return true;
11448
11449 if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11450 #ifdef CONFIG_KVM_SMM
11451 kvm_test_request(KVM_REQ_SMI, vcpu) ||
11452 #endif
11453 kvm_test_request(KVM_REQ_EVENT, vcpu))
11454 return true;
11455
11456 return kvm_arch_dy_has_pending_interrupt(vcpu);
11457 }
11458
complete_emulated_io(struct kvm_vcpu * vcpu)11459 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11460 {
11461 return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11462 }
11463
complete_emulated_pio(struct kvm_vcpu * vcpu)11464 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11465 {
11466 BUG_ON(!vcpu->arch.pio.count);
11467
11468 return complete_emulated_io(vcpu);
11469 }
11470
11471 /*
11472 * Implements the following, as a state machine:
11473 *
11474 * read:
11475 * for each fragment
11476 * for each mmio piece in the fragment
11477 * write gpa, len
11478 * exit
11479 * copy data
11480 * execute insn
11481 *
11482 * write:
11483 * for each fragment
11484 * for each mmio piece in the fragment
11485 * write gpa, len
11486 * copy data
11487 * exit
11488 */
complete_emulated_mmio(struct kvm_vcpu * vcpu)11489 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11490 {
11491 struct kvm_run *run = vcpu->run;
11492 struct kvm_mmio_fragment *frag;
11493 unsigned len;
11494
11495 BUG_ON(!vcpu->mmio_needed);
11496
11497 /* Complete previous fragment */
11498 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11499 len = min(8u, frag->len);
11500 if (!vcpu->mmio_is_write)
11501 memcpy(frag->data, run->mmio.data, len);
11502
11503 if (frag->len <= 8) {
11504 /* Switch to the next fragment. */
11505 frag++;
11506 vcpu->mmio_cur_fragment++;
11507 } else {
11508 /* Go forward to the next mmio piece. */
11509 frag->data += len;
11510 frag->gpa += len;
11511 frag->len -= len;
11512 }
11513
11514 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11515 vcpu->mmio_needed = 0;
11516
11517 /* FIXME: return into emulator if single-stepping. */
11518 if (vcpu->mmio_is_write)
11519 return 1;
11520 vcpu->mmio_read_completed = 1;
11521 return complete_emulated_io(vcpu);
11522 }
11523
11524 run->exit_reason = KVM_EXIT_MMIO;
11525 run->mmio.phys_addr = frag->gpa;
11526 if (vcpu->mmio_is_write)
11527 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11528 run->mmio.len = min(8u, frag->len);
11529 run->mmio.is_write = vcpu->mmio_is_write;
11530 vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11531 return 0;
11532 }
11533
11534 /* Swap (qemu) user FPU context for the guest FPU context. */
kvm_load_guest_fpu(struct kvm_vcpu * vcpu)11535 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11536 {
11537 /* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11538 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11539 trace_kvm_fpu(1);
11540 }
11541
11542 /* When vcpu_run ends, restore user space FPU context. */
kvm_put_guest_fpu(struct kvm_vcpu * vcpu)11543 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11544 {
11545 fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11546 ++vcpu->stat.fpu_reload;
11547 trace_kvm_fpu(0);
11548 }
11549
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)11550 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
11551 {
11552 struct kvm_queued_exception *ex = &vcpu->arch.exception;
11553 struct kvm_run *kvm_run = vcpu->run;
11554 u64 sync_valid_fields;
11555 int r;
11556
11557 r = kvm_mmu_post_init_vm(vcpu->kvm);
11558 if (r)
11559 return r;
11560
11561 vcpu_load(vcpu);
11562 kvm_sigset_activate(vcpu);
11563 kvm_run->flags = 0;
11564 kvm_load_guest_fpu(vcpu);
11565
11566 kvm_vcpu_srcu_read_lock(vcpu);
11567 if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
11568 if (!vcpu->wants_to_run) {
11569 r = -EINTR;
11570 goto out;
11571 }
11572
11573 /*
11574 * Don't bother switching APIC timer emulation from the
11575 * hypervisor timer to the software timer, the only way for the
11576 * APIC timer to be active is if userspace stuffed vCPU state,
11577 * i.e. put the vCPU into a nonsensical state. Only an INIT
11578 * will transition the vCPU out of UNINITIALIZED (without more
11579 * state stuffing from userspace), which will reset the local
11580 * APIC and thus cancel the timer or drop the IRQ (if the timer
11581 * already expired).
11582 */
11583 kvm_vcpu_srcu_read_unlock(vcpu);
11584 kvm_vcpu_block(vcpu);
11585 kvm_vcpu_srcu_read_lock(vcpu);
11586
11587 if (kvm_apic_accept_events(vcpu) < 0) {
11588 r = 0;
11589 goto out;
11590 }
11591 r = -EAGAIN;
11592 if (signal_pending(current)) {
11593 r = -EINTR;
11594 kvm_run->exit_reason = KVM_EXIT_INTR;
11595 ++vcpu->stat.signal_exits;
11596 }
11597 goto out;
11598 }
11599
11600 sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
11601 if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
11602 (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
11603 r = -EINVAL;
11604 goto out;
11605 }
11606
11607 if (kvm_run->kvm_dirty_regs) {
11608 r = sync_regs(vcpu);
11609 if (r != 0)
11610 goto out;
11611 }
11612
11613 /* re-sync apic's tpr */
11614 if (!lapic_in_kernel(vcpu)) {
11615 if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11616 r = -EINVAL;
11617 goto out;
11618 }
11619 }
11620
11621 /*
11622 * If userspace set a pending exception and L2 is active, convert it to
11623 * a pending VM-Exit if L1 wants to intercept the exception.
11624 */
11625 if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11626 kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11627 ex->error_code)) {
11628 kvm_queue_exception_vmexit(vcpu, ex->vector,
11629 ex->has_error_code, ex->error_code,
11630 ex->has_payload, ex->payload);
11631 ex->injected = false;
11632 ex->pending = false;
11633 }
11634 vcpu->arch.exception_from_userspace = false;
11635
11636 if (unlikely(vcpu->arch.complete_userspace_io)) {
11637 int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11638 vcpu->arch.complete_userspace_io = NULL;
11639 r = cui(vcpu);
11640 if (r <= 0)
11641 goto out;
11642 } else {
11643 WARN_ON_ONCE(vcpu->arch.pio.count);
11644 WARN_ON_ONCE(vcpu->mmio_needed);
11645 }
11646
11647 if (!vcpu->wants_to_run) {
11648 r = -EINTR;
11649 goto out;
11650 }
11651
11652 r = kvm_x86_call(vcpu_pre_run)(vcpu);
11653 if (r <= 0)
11654 goto out;
11655
11656 r = vcpu_run(vcpu);
11657
11658 out:
11659 kvm_put_guest_fpu(vcpu);
11660 if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
11661 store_regs(vcpu);
11662 post_kvm_run_save(vcpu);
11663 kvm_vcpu_srcu_read_unlock(vcpu);
11664
11665 kvm_sigset_deactivate(vcpu);
11666 vcpu_put(vcpu);
11667 return r;
11668 }
11669
__get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11670 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11671 {
11672 if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
11673 /*
11674 * We are here if userspace calls get_regs() in the middle of
11675 * instruction emulation. Registers state needs to be copied
11676 * back from emulation context to vcpu. Userspace shouldn't do
11677 * that usually, but some bad designed PV devices (vmware
11678 * backdoor interface) need this to work
11679 */
11680 emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
11681 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11682 }
11683 regs->rax = kvm_rax_read(vcpu);
11684 regs->rbx = kvm_rbx_read(vcpu);
11685 regs->rcx = kvm_rcx_read(vcpu);
11686 regs->rdx = kvm_rdx_read(vcpu);
11687 regs->rsi = kvm_rsi_read(vcpu);
11688 regs->rdi = kvm_rdi_read(vcpu);
11689 regs->rsp = kvm_rsp_read(vcpu);
11690 regs->rbp = kvm_rbp_read(vcpu);
11691 #ifdef CONFIG_X86_64
11692 regs->r8 = kvm_r8_read(vcpu);
11693 regs->r9 = kvm_r9_read(vcpu);
11694 regs->r10 = kvm_r10_read(vcpu);
11695 regs->r11 = kvm_r11_read(vcpu);
11696 regs->r12 = kvm_r12_read(vcpu);
11697 regs->r13 = kvm_r13_read(vcpu);
11698 regs->r14 = kvm_r14_read(vcpu);
11699 regs->r15 = kvm_r15_read(vcpu);
11700 #endif
11701
11702 regs->rip = kvm_rip_read(vcpu);
11703 regs->rflags = kvm_get_rflags(vcpu);
11704 }
11705
kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11706 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11707 {
11708 if (vcpu->kvm->arch.has_protected_state &&
11709 vcpu->arch.guest_state_protected)
11710 return -EINVAL;
11711
11712 vcpu_load(vcpu);
11713 __get_regs(vcpu, regs);
11714 vcpu_put(vcpu);
11715 return 0;
11716 }
11717
__set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11718 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11719 {
11720 vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
11721 vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11722
11723 kvm_rax_write(vcpu, regs->rax);
11724 kvm_rbx_write(vcpu, regs->rbx);
11725 kvm_rcx_write(vcpu, regs->rcx);
11726 kvm_rdx_write(vcpu, regs->rdx);
11727 kvm_rsi_write(vcpu, regs->rsi);
11728 kvm_rdi_write(vcpu, regs->rdi);
11729 kvm_rsp_write(vcpu, regs->rsp);
11730 kvm_rbp_write(vcpu, regs->rbp);
11731 #ifdef CONFIG_X86_64
11732 kvm_r8_write(vcpu, regs->r8);
11733 kvm_r9_write(vcpu, regs->r9);
11734 kvm_r10_write(vcpu, regs->r10);
11735 kvm_r11_write(vcpu, regs->r11);
11736 kvm_r12_write(vcpu, regs->r12);
11737 kvm_r13_write(vcpu, regs->r13);
11738 kvm_r14_write(vcpu, regs->r14);
11739 kvm_r15_write(vcpu, regs->r15);
11740 #endif
11741
11742 kvm_rip_write(vcpu, regs->rip);
11743 kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
11744
11745 vcpu->arch.exception.pending = false;
11746 vcpu->arch.exception_vmexit.pending = false;
11747
11748 kvm_make_request(KVM_REQ_EVENT, vcpu);
11749 }
11750
kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11751 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11752 {
11753 if (vcpu->kvm->arch.has_protected_state &&
11754 vcpu->arch.guest_state_protected)
11755 return -EINVAL;
11756
11757 vcpu_load(vcpu);
11758 __set_regs(vcpu, regs);
11759 vcpu_put(vcpu);
11760 return 0;
11761 }
11762
__get_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11763 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11764 {
11765 struct desc_ptr dt;
11766
11767 if (vcpu->arch.guest_state_protected)
11768 goto skip_protected_regs;
11769
11770 kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
11771 kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
11772 kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
11773 kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
11774 kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
11775 kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
11776
11777 kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
11778 kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
11779
11780 kvm_x86_call(get_idt)(vcpu, &dt);
11781 sregs->idt.limit = dt.size;
11782 sregs->idt.base = dt.address;
11783 kvm_x86_call(get_gdt)(vcpu, &dt);
11784 sregs->gdt.limit = dt.size;
11785 sregs->gdt.base = dt.address;
11786
11787 sregs->cr2 = vcpu->arch.cr2;
11788 sregs->cr3 = kvm_read_cr3(vcpu);
11789
11790 skip_protected_regs:
11791 sregs->cr0 = kvm_read_cr0(vcpu);
11792 sregs->cr4 = kvm_read_cr4(vcpu);
11793 sregs->cr8 = kvm_get_cr8(vcpu);
11794 sregs->efer = vcpu->arch.efer;
11795 sregs->apic_base = vcpu->arch.apic_base;
11796 }
11797
__get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11798 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11799 {
11800 __get_sregs_common(vcpu, sregs);
11801
11802 if (vcpu->arch.guest_state_protected)
11803 return;
11804
11805 if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
11806 set_bit(vcpu->arch.interrupt.nr,
11807 (unsigned long *)sregs->interrupt_bitmap);
11808 }
11809
__get_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)11810 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
11811 {
11812 int i;
11813
11814 __get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
11815
11816 if (vcpu->arch.guest_state_protected)
11817 return;
11818
11819 if (is_pae_paging(vcpu)) {
11820 for (i = 0 ; i < 4 ; i++)
11821 sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
11822 sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
11823 }
11824 }
11825
kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11826 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
11827 struct kvm_sregs *sregs)
11828 {
11829 if (vcpu->kvm->arch.has_protected_state &&
11830 vcpu->arch.guest_state_protected)
11831 return -EINVAL;
11832
11833 vcpu_load(vcpu);
11834 __get_sregs(vcpu, sregs);
11835 vcpu_put(vcpu);
11836 return 0;
11837 }
11838
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)11839 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
11840 struct kvm_mp_state *mp_state)
11841 {
11842 int r;
11843
11844 vcpu_load(vcpu);
11845 if (kvm_mpx_supported())
11846 kvm_load_guest_fpu(vcpu);
11847
11848 kvm_vcpu_srcu_read_lock(vcpu);
11849
11850 r = kvm_apic_accept_events(vcpu);
11851 if (r < 0)
11852 goto out;
11853 r = 0;
11854
11855 if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
11856 vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
11857 vcpu->arch.pv.pv_unhalted)
11858 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
11859 else
11860 mp_state->mp_state = vcpu->arch.mp_state;
11861
11862 out:
11863 kvm_vcpu_srcu_read_unlock(vcpu);
11864
11865 if (kvm_mpx_supported())
11866 kvm_put_guest_fpu(vcpu);
11867 vcpu_put(vcpu);
11868 return r;
11869 }
11870
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)11871 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
11872 struct kvm_mp_state *mp_state)
11873 {
11874 int ret = -EINVAL;
11875
11876 vcpu_load(vcpu);
11877
11878 switch (mp_state->mp_state) {
11879 case KVM_MP_STATE_UNINITIALIZED:
11880 case KVM_MP_STATE_HALTED:
11881 case KVM_MP_STATE_AP_RESET_HOLD:
11882 case KVM_MP_STATE_INIT_RECEIVED:
11883 case KVM_MP_STATE_SIPI_RECEIVED:
11884 if (!lapic_in_kernel(vcpu))
11885 goto out;
11886 break;
11887
11888 case KVM_MP_STATE_RUNNABLE:
11889 break;
11890
11891 default:
11892 goto out;
11893 }
11894
11895 /*
11896 * Pending INITs are reported using KVM_SET_VCPU_EVENTS, disallow
11897 * forcing the guest into INIT/SIPI if those events are supposed to be
11898 * blocked. KVM prioritizes SMI over INIT, so reject INIT/SIPI state
11899 * if an SMI is pending as well.
11900 */
11901 if ((!kvm_apic_init_sipi_allowed(vcpu) || vcpu->arch.smi_pending) &&
11902 (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
11903 mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
11904 goto out;
11905
11906 if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
11907 kvm_set_mp_state(vcpu, KVM_MP_STATE_INIT_RECEIVED);
11908 set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
11909 } else
11910 kvm_set_mp_state(vcpu, mp_state->mp_state);
11911 kvm_make_request(KVM_REQ_EVENT, vcpu);
11912
11913 ret = 0;
11914 out:
11915 vcpu_put(vcpu);
11916 return ret;
11917 }
11918
kvm_task_switch(struct kvm_vcpu * vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code)11919 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
11920 int reason, bool has_error_code, u32 error_code)
11921 {
11922 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
11923 int ret;
11924
11925 init_emulate_ctxt(vcpu);
11926
11927 ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
11928 has_error_code, error_code);
11929
11930 /*
11931 * Report an error userspace if MMIO is needed, as KVM doesn't support
11932 * MMIO during a task switch (or any other complex operation).
11933 */
11934 if (ret || vcpu->mmio_needed) {
11935 vcpu->mmio_needed = false;
11936 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
11937 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
11938 vcpu->run->internal.ndata = 0;
11939 return 0;
11940 }
11941
11942 kvm_rip_write(vcpu, ctxt->eip);
11943 kvm_set_rflags(vcpu, ctxt->eflags);
11944 return 1;
11945 }
11946 EXPORT_SYMBOL_GPL(kvm_task_switch);
11947
kvm_is_valid_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)11948 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
11949 {
11950 if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
11951 /*
11952 * When EFER.LME and CR0.PG are set, the processor is in
11953 * 64-bit mode (though maybe in a 32-bit code segment).
11954 * CR4.PAE and EFER.LMA must be set.
11955 */
11956 if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
11957 return false;
11958 if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
11959 return false;
11960 } else {
11961 /*
11962 * Not in 64-bit mode: EFER.LMA is clear and the code
11963 * segment cannot be 64-bit.
11964 */
11965 if (sregs->efer & EFER_LMA || sregs->cs.l)
11966 return false;
11967 }
11968
11969 return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
11970 kvm_is_valid_cr0(vcpu, sregs->cr0);
11971 }
11972
__set_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs,int * mmu_reset_needed,bool update_pdptrs)11973 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
11974 int *mmu_reset_needed, bool update_pdptrs)
11975 {
11976 int idx;
11977 struct desc_ptr dt;
11978
11979 if (!kvm_is_valid_sregs(vcpu, sregs))
11980 return -EINVAL;
11981
11982 if (kvm_apic_set_base(vcpu, sregs->apic_base, true))
11983 return -EINVAL;
11984
11985 if (vcpu->arch.guest_state_protected)
11986 return 0;
11987
11988 dt.size = sregs->idt.limit;
11989 dt.address = sregs->idt.base;
11990 kvm_x86_call(set_idt)(vcpu, &dt);
11991 dt.size = sregs->gdt.limit;
11992 dt.address = sregs->gdt.base;
11993 kvm_x86_call(set_gdt)(vcpu, &dt);
11994
11995 vcpu->arch.cr2 = sregs->cr2;
11996 *mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
11997 vcpu->arch.cr3 = sregs->cr3;
11998 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
11999 kvm_x86_call(post_set_cr3)(vcpu, sregs->cr3);
12000
12001 kvm_set_cr8(vcpu, sregs->cr8);
12002
12003 *mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
12004 kvm_x86_call(set_efer)(vcpu, sregs->efer);
12005
12006 *mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
12007 kvm_x86_call(set_cr0)(vcpu, sregs->cr0);
12008
12009 *mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
12010 kvm_x86_call(set_cr4)(vcpu, sregs->cr4);
12011
12012 if (update_pdptrs) {
12013 idx = srcu_read_lock(&vcpu->kvm->srcu);
12014 if (is_pae_paging(vcpu)) {
12015 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
12016 *mmu_reset_needed = 1;
12017 }
12018 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12019 }
12020
12021 kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12022 kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12023 kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12024 kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12025 kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12026 kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12027
12028 kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12029 kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12030
12031 update_cr8_intercept(vcpu);
12032
12033 /* Older userspace won't unhalt the vcpu on reset. */
12034 if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
12035 sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
12036 !is_protmode(vcpu))
12037 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12038
12039 return 0;
12040 }
12041
__set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12042 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12043 {
12044 int pending_vec, max_bits;
12045 int mmu_reset_needed = 0;
12046 int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
12047
12048 if (ret)
12049 return ret;
12050
12051 if (mmu_reset_needed) {
12052 kvm_mmu_reset_context(vcpu);
12053 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12054 }
12055
12056 max_bits = KVM_NR_INTERRUPTS;
12057 pending_vec = find_first_bit(
12058 (const unsigned long *)sregs->interrupt_bitmap, max_bits);
12059
12060 if (pending_vec < max_bits) {
12061 kvm_queue_interrupt(vcpu, pending_vec, false);
12062 pr_debug("Set back pending irq %d\n", pending_vec);
12063 kvm_make_request(KVM_REQ_EVENT, vcpu);
12064 }
12065 return 0;
12066 }
12067
__set_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12068 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12069 {
12070 int mmu_reset_needed = 0;
12071 bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
12072 bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
12073 !(sregs2->efer & EFER_LMA);
12074 int i, ret;
12075
12076 if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
12077 return -EINVAL;
12078
12079 if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
12080 return -EINVAL;
12081
12082 ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
12083 &mmu_reset_needed, !valid_pdptrs);
12084 if (ret)
12085 return ret;
12086
12087 if (valid_pdptrs) {
12088 for (i = 0; i < 4 ; i++)
12089 kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
12090
12091 kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
12092 mmu_reset_needed = 1;
12093 vcpu->arch.pdptrs_from_userspace = true;
12094 }
12095 if (mmu_reset_needed) {
12096 kvm_mmu_reset_context(vcpu);
12097 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12098 }
12099 return 0;
12100 }
12101
kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12102 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
12103 struct kvm_sregs *sregs)
12104 {
12105 int ret;
12106
12107 if (vcpu->kvm->arch.has_protected_state &&
12108 vcpu->arch.guest_state_protected)
12109 return -EINVAL;
12110
12111 vcpu_load(vcpu);
12112 ret = __set_sregs(vcpu, sregs);
12113 vcpu_put(vcpu);
12114 return ret;
12115 }
12116
kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm * kvm)12117 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
12118 {
12119 bool set = false;
12120 struct kvm_vcpu *vcpu;
12121 unsigned long i;
12122
12123 if (!enable_apicv)
12124 return;
12125
12126 down_write(&kvm->arch.apicv_update_lock);
12127
12128 kvm_for_each_vcpu(i, vcpu, kvm) {
12129 if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
12130 set = true;
12131 break;
12132 }
12133 }
12134 __kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
12135 up_write(&kvm->arch.apicv_update_lock);
12136 }
12137
kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu * vcpu,struct kvm_guest_debug * dbg)12138 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
12139 struct kvm_guest_debug *dbg)
12140 {
12141 unsigned long rflags;
12142 int i, r;
12143
12144 if (vcpu->arch.guest_state_protected)
12145 return -EINVAL;
12146
12147 vcpu_load(vcpu);
12148
12149 if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
12150 r = -EBUSY;
12151 if (kvm_is_exception_pending(vcpu))
12152 goto out;
12153 if (dbg->control & KVM_GUESTDBG_INJECT_DB)
12154 kvm_queue_exception(vcpu, DB_VECTOR);
12155 else
12156 kvm_queue_exception(vcpu, BP_VECTOR);
12157 }
12158
12159 /*
12160 * Read rflags as long as potentially injected trace flags are still
12161 * filtered out.
12162 */
12163 rflags = kvm_get_rflags(vcpu);
12164
12165 vcpu->guest_debug = dbg->control;
12166 if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
12167 vcpu->guest_debug = 0;
12168
12169 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
12170 for (i = 0; i < KVM_NR_DB_REGS; ++i)
12171 vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
12172 vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
12173 } else {
12174 for (i = 0; i < KVM_NR_DB_REGS; i++)
12175 vcpu->arch.eff_db[i] = vcpu->arch.db[i];
12176 }
12177 kvm_update_dr7(vcpu);
12178
12179 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12180 vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
12181
12182 /*
12183 * Trigger an rflags update that will inject or remove the trace
12184 * flags.
12185 */
12186 kvm_set_rflags(vcpu, rflags);
12187
12188 kvm_x86_call(update_exception_bitmap)(vcpu);
12189
12190 kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12191
12192 r = 0;
12193
12194 out:
12195 vcpu_put(vcpu);
12196 return r;
12197 }
12198
12199 /*
12200 * Translate a guest virtual address to a guest physical address.
12201 */
kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu * vcpu,struct kvm_translation * tr)12202 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12203 struct kvm_translation *tr)
12204 {
12205 unsigned long vaddr = tr->linear_address;
12206 gpa_t gpa;
12207 int idx;
12208
12209 vcpu_load(vcpu);
12210
12211 idx = srcu_read_lock(&vcpu->kvm->srcu);
12212 gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
12213 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12214 tr->physical_address = gpa;
12215 tr->valid = gpa != INVALID_GPA;
12216 tr->writeable = 1;
12217 tr->usermode = 0;
12218
12219 vcpu_put(vcpu);
12220 return 0;
12221 }
12222
kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12223 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12224 {
12225 struct fxregs_state *fxsave;
12226
12227 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12228 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12229
12230 vcpu_load(vcpu);
12231
12232 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12233 memcpy(fpu->fpr, fxsave->st_space, 128);
12234 fpu->fcw = fxsave->cwd;
12235 fpu->fsw = fxsave->swd;
12236 fpu->ftwx = fxsave->twd;
12237 fpu->last_opcode = fxsave->fop;
12238 fpu->last_ip = fxsave->rip;
12239 fpu->last_dp = fxsave->rdp;
12240 memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
12241
12242 vcpu_put(vcpu);
12243 return 0;
12244 }
12245
kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12246 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12247 {
12248 struct fxregs_state *fxsave;
12249
12250 if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12251 return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12252
12253 vcpu_load(vcpu);
12254
12255 fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12256
12257 memcpy(fxsave->st_space, fpu->fpr, 128);
12258 fxsave->cwd = fpu->fcw;
12259 fxsave->swd = fpu->fsw;
12260 fxsave->twd = fpu->ftwx;
12261 fxsave->fop = fpu->last_opcode;
12262 fxsave->rip = fpu->last_ip;
12263 fxsave->rdp = fpu->last_dp;
12264 memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
12265
12266 vcpu_put(vcpu);
12267 return 0;
12268 }
12269
store_regs(struct kvm_vcpu * vcpu)12270 static void store_regs(struct kvm_vcpu *vcpu)
12271 {
12272 BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12273
12274 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12275 __get_regs(vcpu, &vcpu->run->s.regs.regs);
12276
12277 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12278 __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12279
12280 if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12281 kvm_vcpu_ioctl_x86_get_vcpu_events(
12282 vcpu, &vcpu->run->s.regs.events);
12283 }
12284
sync_regs(struct kvm_vcpu * vcpu)12285 static int sync_regs(struct kvm_vcpu *vcpu)
12286 {
12287 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12288 __set_regs(vcpu, &vcpu->run->s.regs.regs);
12289 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12290 }
12291
12292 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
12293 struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12294
12295 if (__set_sregs(vcpu, &sregs))
12296 return -EINVAL;
12297
12298 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12299 }
12300
12301 if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
12302 struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12303
12304 if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
12305 return -EINVAL;
12306
12307 vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12308 }
12309
12310 return 0;
12311 }
12312
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)12313 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
12314 {
12315 if (kvm_check_tsc_unstable() && kvm->created_vcpus)
12316 pr_warn_once("SMP vm created on host with unstable TSC; "
12317 "guest TSC will not be reliable\n");
12318
12319 if (!kvm->arch.max_vcpu_ids)
12320 kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12321
12322 if (id >= kvm->arch.max_vcpu_ids)
12323 return -EINVAL;
12324
12325 return kvm_x86_call(vcpu_precreate)(kvm);
12326 }
12327
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)12328 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
12329 {
12330 struct page *page;
12331 int r;
12332
12333 vcpu->arch.last_vmentry_cpu = -1;
12334 vcpu->arch.regs_avail = ~0;
12335 vcpu->arch.regs_dirty = ~0;
12336
12337 kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
12338
12339 if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
12340 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12341 else
12342 kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);
12343
12344 r = kvm_mmu_create(vcpu);
12345 if (r < 0)
12346 return r;
12347
12348 r = kvm_create_lapic(vcpu);
12349 if (r < 0)
12350 goto fail_mmu_destroy;
12351
12352 r = -ENOMEM;
12353
12354 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
12355 if (!page)
12356 goto fail_free_lapic;
12357 vcpu->arch.pio_data = page_address(page);
12358
12359 vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
12360 GFP_KERNEL_ACCOUNT);
12361 vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12362 GFP_KERNEL_ACCOUNT);
12363 if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
12364 goto fail_free_mce_banks;
12365 vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12366
12367 if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12368 GFP_KERNEL_ACCOUNT))
12369 goto fail_free_mce_banks;
12370
12371 if (!alloc_emulate_ctxt(vcpu))
12372 goto free_wbinvd_dirty_mask;
12373
12374 if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
12375 pr_err("failed to allocate vcpu's fpu\n");
12376 goto free_emulate_ctxt;
12377 }
12378
12379 kvm_async_pf_hash_reset(vcpu);
12380
12381 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) {
12382 vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12383 vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12384 vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12385 }
12386 kvm_pmu_init(vcpu);
12387
12388 vcpu->arch.pending_external_vector = -1;
12389 vcpu->arch.preempted_in_kernel = false;
12390
12391 #if IS_ENABLED(CONFIG_HYPERV)
12392 vcpu->arch.hv_root_tdp = INVALID_PAGE;
12393 #endif
12394
12395 r = kvm_x86_call(vcpu_create)(vcpu);
12396 if (r)
12397 goto free_guest_fpu;
12398
12399 kvm_xen_init_vcpu(vcpu);
12400 vcpu_load(vcpu);
12401 kvm_vcpu_after_set_cpuid(vcpu);
12402 kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12403 kvm_vcpu_reset(vcpu, false);
12404 kvm_init_mmu(vcpu);
12405 vcpu_put(vcpu);
12406 return 0;
12407
12408 free_guest_fpu:
12409 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12410 free_emulate_ctxt:
12411 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12412 free_wbinvd_dirty_mask:
12413 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12414 fail_free_mce_banks:
12415 kfree(vcpu->arch.mce_banks);
12416 kfree(vcpu->arch.mci_ctl2_banks);
12417 free_page((unsigned long)vcpu->arch.pio_data);
12418 fail_free_lapic:
12419 kvm_free_lapic(vcpu);
12420 fail_mmu_destroy:
12421 kvm_mmu_destroy(vcpu);
12422 return r;
12423 }
12424
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)12425 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12426 {
12427 struct kvm *kvm = vcpu->kvm;
12428
12429 if (mutex_lock_killable(&vcpu->mutex))
12430 return;
12431 vcpu_load(vcpu);
12432 kvm_synchronize_tsc(vcpu, NULL);
12433 vcpu_put(vcpu);
12434
12435 /* poll control enabled by default */
12436 vcpu->arch.msr_kvm_poll_control = 1;
12437
12438 mutex_unlock(&vcpu->mutex);
12439
12440 if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
12441 schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
12442 KVMCLOCK_SYNC_PERIOD);
12443 }
12444
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)12445 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12446 {
12447 int idx, cpu;
12448
12449 kvm_clear_async_pf_completion_queue(vcpu);
12450 kvm_mmu_unload(vcpu);
12451
12452 kvmclock_reset(vcpu);
12453
12454 for_each_possible_cpu(cpu)
12455 cmpxchg(per_cpu_ptr(&last_vcpu, cpu), vcpu, NULL);
12456
12457 kvm_x86_call(vcpu_free)(vcpu);
12458
12459 kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12460 free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12461 fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12462
12463 kvm_xen_destroy_vcpu(vcpu);
12464 kvm_hv_vcpu_uninit(vcpu);
12465 kvm_pmu_destroy(vcpu);
12466 kfree(vcpu->arch.mce_banks);
12467 kfree(vcpu->arch.mci_ctl2_banks);
12468 kvm_free_lapic(vcpu);
12469 idx = srcu_read_lock(&vcpu->kvm->srcu);
12470 kvm_mmu_destroy(vcpu);
12471 srcu_read_unlock(&vcpu->kvm->srcu, idx);
12472 free_page((unsigned long)vcpu->arch.pio_data);
12473 kvfree(vcpu->arch.cpuid_entries);
12474 }
12475
kvm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)12476 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
12477 {
12478 struct kvm_cpuid_entry2 *cpuid_0x1;
12479 unsigned long old_cr0 = kvm_read_cr0(vcpu);
12480 unsigned long new_cr0;
12481
12482 /*
12483 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12484 * to handle side effects. RESET emulation hits those flows and relies
12485 * on emulated/virtualized registers, including those that are loaded
12486 * into hardware, to be zeroed at vCPU creation. Use CRs as a sentinel
12487 * to detect improper or missing initialization.
12488 */
12489 WARN_ON_ONCE(!init_event &&
12490 (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
12491
12492 /*
12493 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12494 * possible to INIT the vCPU while L2 is active. Force the vCPU back
12495 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12496 * bits), i.e. virtualization is disabled.
12497 */
12498 if (is_guest_mode(vcpu))
12499 kvm_leave_nested(vcpu);
12500
12501 kvm_lapic_reset(vcpu, init_event);
12502
12503 WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
12504 vcpu->arch.hflags = 0;
12505
12506 vcpu->arch.smi_pending = 0;
12507 vcpu->arch.smi_count = 0;
12508 atomic_set(&vcpu->arch.nmi_queued, 0);
12509 vcpu->arch.nmi_pending = 0;
12510 vcpu->arch.nmi_injected = false;
12511 kvm_clear_interrupt_queue(vcpu);
12512 kvm_clear_exception_queue(vcpu);
12513
12514 memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
12515 kvm_update_dr0123(vcpu);
12516 vcpu->arch.dr6 = DR6_ACTIVE_LOW;
12517 vcpu->arch.dr7 = DR7_FIXED_1;
12518 kvm_update_dr7(vcpu);
12519
12520 vcpu->arch.cr2 = 0;
12521
12522 kvm_make_request(KVM_REQ_EVENT, vcpu);
12523 vcpu->arch.apf.msr_en_val = 0;
12524 vcpu->arch.apf.msr_int_val = 0;
12525 vcpu->arch.st.msr_val = 0;
12526
12527 kvmclock_reset(vcpu);
12528
12529 kvm_clear_async_pf_completion_queue(vcpu);
12530 kvm_async_pf_hash_reset(vcpu);
12531 vcpu->arch.apf.halted = false;
12532
12533 if (vcpu->arch.guest_fpu.fpstate && kvm_mpx_supported()) {
12534 struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12535
12536 /*
12537 * All paths that lead to INIT are required to load the guest's
12538 * FPU state (because most paths are buried in KVM_RUN).
12539 */
12540 if (init_event)
12541 kvm_put_guest_fpu(vcpu);
12542
12543 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDREGS);
12544 fpstate_clear_xstate_component(fpstate, XFEATURE_BNDCSR);
12545
12546 if (init_event)
12547 kvm_load_guest_fpu(vcpu);
12548 }
12549
12550 if (!init_event) {
12551 vcpu->arch.smbase = 0x30000;
12552
12553 vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
12554
12555 vcpu->arch.msr_misc_features_enables = 0;
12556 vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12557 MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
12558
12559 __kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12560 __kvm_set_msr(vcpu, MSR_IA32_XSS, 0, true);
12561 }
12562
12563 /* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
12564 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
12565 kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
12566
12567 /*
12568 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12569 * if no CPUID match is found. Note, it's impossible to get a match at
12570 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
12571 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12572 * on RESET. But, go through the motions in case that's ever remedied.
12573 */
12574 cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
12575 kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
12576
12577 kvm_x86_call(vcpu_reset)(vcpu, init_event);
12578
12579 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12580 kvm_rip_write(vcpu, 0xfff0);
12581
12582 vcpu->arch.cr3 = 0;
12583 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12584
12585 /*
12586 * CR0.CD/NW are set on RESET, preserved on INIT. Note, some versions
12587 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12588 * (or qualify) that with a footnote stating that CD/NW are preserved.
12589 */
12590 new_cr0 = X86_CR0_ET;
12591 if (init_event)
12592 new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12593 else
12594 new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12595
12596 kvm_x86_call(set_cr0)(vcpu, new_cr0);
12597 kvm_x86_call(set_cr4)(vcpu, 0);
12598 kvm_x86_call(set_efer)(vcpu, 0);
12599 kvm_x86_call(update_exception_bitmap)(vcpu);
12600
12601 /*
12602 * On the standard CR0/CR4/EFER modification paths, there are several
12603 * complex conditions determining whether the MMU has to be reset and/or
12604 * which PCIDs have to be flushed. However, CR0.WP and the paging-related
12605 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12606 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12607 * CR0 will be '0' prior to RESET). So we only need to check CR0.PG here.
12608 */
12609 if (old_cr0 & X86_CR0_PG) {
12610 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12611 kvm_mmu_reset_context(vcpu);
12612 }
12613
12614 /*
12615 * Intel's SDM states that all TLB entries are flushed on INIT. AMD's
12616 * APM states the TLBs are untouched by INIT, but it also states that
12617 * the TLBs are flushed on "External initialization of the processor."
12618 * Flush the guest TLB regardless of vendor, there is no meaningful
12619 * benefit in relying on the guest to flush the TLB immediately after
12620 * INIT. A spurious TLB flush is benign and likely negligible from a
12621 * performance perspective.
12622 */
12623 if (init_event)
12624 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12625 }
12626 EXPORT_SYMBOL_GPL(kvm_vcpu_reset);
12627
kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)12628 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
12629 {
12630 struct kvm_segment cs;
12631
12632 kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
12633 cs.selector = vector << 8;
12634 cs.base = vector << 12;
12635 kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
12636 kvm_rip_write(vcpu, 0);
12637 }
12638 EXPORT_SYMBOL_GPL(kvm_vcpu_deliver_sipi_vector);
12639
kvm_arch_enable_virtualization(void)12640 void kvm_arch_enable_virtualization(void)
12641 {
12642 cpu_emergency_register_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12643 }
12644
kvm_arch_disable_virtualization(void)12645 void kvm_arch_disable_virtualization(void)
12646 {
12647 cpu_emergency_unregister_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12648 }
12649
kvm_arch_enable_virtualization_cpu(void)12650 int kvm_arch_enable_virtualization_cpu(void)
12651 {
12652 struct kvm *kvm;
12653 struct kvm_vcpu *vcpu;
12654 unsigned long i;
12655 int ret;
12656 u64 local_tsc;
12657 u64 max_tsc = 0;
12658 bool stable, backwards_tsc = false;
12659
12660 kvm_user_return_msr_cpu_online();
12661
12662 ret = kvm_x86_check_processor_compatibility();
12663 if (ret)
12664 return ret;
12665
12666 ret = kvm_x86_call(enable_virtualization_cpu)();
12667 if (ret != 0)
12668 return ret;
12669
12670 local_tsc = rdtsc();
12671 stable = !kvm_check_tsc_unstable();
12672 list_for_each_entry(kvm, &vm_list, vm_list) {
12673 kvm_for_each_vcpu(i, vcpu, kvm) {
12674 if (!stable && vcpu->cpu == smp_processor_id())
12675 kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
12676 if (stable && vcpu->arch.last_host_tsc > local_tsc) {
12677 backwards_tsc = true;
12678 if (vcpu->arch.last_host_tsc > max_tsc)
12679 max_tsc = vcpu->arch.last_host_tsc;
12680 }
12681 }
12682 }
12683
12684 /*
12685 * Sometimes, even reliable TSCs go backwards. This happens on
12686 * platforms that reset TSC during suspend or hibernate actions, but
12687 * maintain synchronization. We must compensate. Fortunately, we can
12688 * detect that condition here, which happens early in CPU bringup,
12689 * before any KVM threads can be running. Unfortunately, we can't
12690 * bring the TSCs fully up to date with real time, as we aren't yet far
12691 * enough into CPU bringup that we know how much real time has actually
12692 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
12693 * variables that haven't been updated yet.
12694 *
12695 * So we simply find the maximum observed TSC above, then record the
12696 * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
12697 * the adjustment will be applied. Note that we accumulate
12698 * adjustments, in case multiple suspend cycles happen before some VCPU
12699 * gets a chance to run again. In the event that no KVM threads get a
12700 * chance to run, we will miss the entire elapsed period, as we'll have
12701 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
12702 * loose cycle time. This isn't too big a deal, since the loss will be
12703 * uniform across all VCPUs (not to mention the scenario is extremely
12704 * unlikely). It is possible that a second hibernate recovery happens
12705 * much faster than a first, causing the observed TSC here to be
12706 * smaller; this would require additional padding adjustment, which is
12707 * why we set last_host_tsc to the local tsc observed here.
12708 *
12709 * N.B. - this code below runs only on platforms with reliable TSC,
12710 * as that is the only way backwards_tsc is set above. Also note
12711 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
12712 * have the same delta_cyc adjustment applied if backwards_tsc
12713 * is detected. Note further, this adjustment is only done once,
12714 * as we reset last_host_tsc on all VCPUs to stop this from being
12715 * called multiple times (one for each physical CPU bringup).
12716 *
12717 * Platforms with unreliable TSCs don't have to deal with this, they
12718 * will be compensated by the logic in vcpu_load, which sets the TSC to
12719 * catchup mode. This will catchup all VCPUs to real time, but cannot
12720 * guarantee that they stay in perfect synchronization.
12721 */
12722 if (backwards_tsc) {
12723 u64 delta_cyc = max_tsc - local_tsc;
12724 list_for_each_entry(kvm, &vm_list, vm_list) {
12725 kvm->arch.backwards_tsc_observed = true;
12726 kvm_for_each_vcpu(i, vcpu, kvm) {
12727 vcpu->arch.tsc_offset_adjustment += delta_cyc;
12728 vcpu->arch.last_host_tsc = local_tsc;
12729 kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
12730 }
12731
12732 /*
12733 * We have to disable TSC offset matching.. if you were
12734 * booting a VM while issuing an S4 host suspend....
12735 * you may have some problem. Solving this issue is
12736 * left as an exercise to the reader.
12737 */
12738 kvm->arch.last_tsc_nsec = 0;
12739 kvm->arch.last_tsc_write = 0;
12740 }
12741
12742 }
12743 return 0;
12744 }
12745
kvm_arch_disable_virtualization_cpu(void)12746 void kvm_arch_disable_virtualization_cpu(void)
12747 {
12748 kvm_x86_call(disable_virtualization_cpu)();
12749 drop_user_return_notifiers();
12750 }
12751
kvm_vcpu_is_reset_bsp(struct kvm_vcpu * vcpu)12752 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
12753 {
12754 return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
12755 }
12756 EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
12757
kvm_vcpu_is_bsp(struct kvm_vcpu * vcpu)12758 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
12759 {
12760 return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
12761 }
12762
kvm_arch_free_vm(struct kvm * kvm)12763 void kvm_arch_free_vm(struct kvm *kvm)
12764 {
12765 #if IS_ENABLED(CONFIG_HYPERV)
12766 kfree(kvm->arch.hv_pa_pg);
12767 #endif
12768 __kvm_arch_free_vm(kvm);
12769 }
12770
12771
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)12772 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
12773 {
12774 int ret;
12775 unsigned long flags;
12776
12777 if (!kvm_is_vm_type_supported(type))
12778 return -EINVAL;
12779
12780 kvm->arch.vm_type = type;
12781 kvm->arch.has_private_mem =
12782 (type == KVM_X86_SW_PROTECTED_VM);
12783 /* Decided by the vendor code for other VM types. */
12784 kvm->arch.pre_fault_allowed =
12785 type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
12786 kvm->arch.disabled_quirks = kvm_caps.inapplicable_quirks & kvm_caps.supported_quirks;
12787
12788 ret = kvm_page_track_init(kvm);
12789 if (ret)
12790 goto out;
12791
12792 kvm_mmu_init_vm(kvm);
12793
12794 ret = kvm_x86_call(vm_init)(kvm);
12795 if (ret)
12796 goto out_uninit_mmu;
12797
12798 INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
12799 atomic_set(&kvm->arch.noncoherent_dma_count, 0);
12800
12801 /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
12802 set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
12803 /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
12804 set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
12805 &kvm->arch.irq_sources_bitmap);
12806
12807 raw_spin_lock_init(&kvm->arch.tsc_write_lock);
12808 mutex_init(&kvm->arch.apic_map_lock);
12809 seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
12810 kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
12811
12812 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
12813 pvclock_update_vm_gtod_copy(kvm);
12814 raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
12815
12816 kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
12817 kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
12818 kvm->arch.guest_can_read_msr_platform_info = true;
12819 kvm->arch.enable_pmu = enable_pmu;
12820
12821 #if IS_ENABLED(CONFIG_HYPERV)
12822 spin_lock_init(&kvm->arch.hv_root_tdp_lock);
12823 kvm->arch.hv_root_tdp = INVALID_PAGE;
12824 #endif
12825
12826 INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
12827 INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
12828
12829 kvm_apicv_init(kvm);
12830 kvm_hv_init_vm(kvm);
12831 kvm_xen_init_vm(kvm);
12832
12833 if (ignore_msrs && !report_ignored_msrs) {
12834 pr_warn_once("Running KVM with ignore_msrs=1 and report_ignored_msrs=0 is not a\n"
12835 "a supported configuration. Lying to the guest about the existence of MSRs\n"
12836 "may cause the guest operating system to hang or produce errors. If a guest\n"
12837 "does not run without ignore_msrs=1, please report it to kvm@vger.kernel.org.\n");
12838 }
12839
12840 once_init(&kvm->arch.nx_once);
12841 return 0;
12842
12843 out_uninit_mmu:
12844 kvm_mmu_uninit_vm(kvm);
12845 kvm_page_track_cleanup(kvm);
12846 out:
12847 return ret;
12848 }
12849
12850 /**
12851 * __x86_set_memory_region: Setup KVM internal memory slot
12852 *
12853 * @kvm: the kvm pointer to the VM.
12854 * @id: the slot ID to setup.
12855 * @gpa: the GPA to install the slot (unused when @size == 0).
12856 * @size: the size of the slot. Set to zero to uninstall a slot.
12857 *
12858 * This function helps to setup a KVM internal memory slot. Specify
12859 * @size > 0 to install a new slot, while @size == 0 to uninstall a
12860 * slot. The return code can be one of the following:
12861 *
12862 * HVA: on success (uninstall will return a bogus HVA)
12863 * -errno: on error
12864 *
12865 * The caller should always use IS_ERR() to check the return value
12866 * before use. Note, the KVM internal memory slots are guaranteed to
12867 * remain valid and unchanged until the VM is destroyed, i.e., the
12868 * GPA->HVA translation will not change. However, the HVA is a user
12869 * address, i.e. its accessibility is not guaranteed, and must be
12870 * accessed via __copy_{to,from}_user().
12871 */
__x86_set_memory_region(struct kvm * kvm,int id,gpa_t gpa,u32 size)12872 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
12873 u32 size)
12874 {
12875 int i, r;
12876 unsigned long hva, old_npages;
12877 struct kvm_memslots *slots = kvm_memslots(kvm);
12878 struct kvm_memory_slot *slot;
12879
12880 lockdep_assert_held(&kvm->slots_lock);
12881
12882 if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
12883 return ERR_PTR_USR(-EINVAL);
12884
12885 slot = id_to_memslot(slots, id);
12886 if (size) {
12887 if (slot && slot->npages)
12888 return ERR_PTR_USR(-EEXIST);
12889
12890 /*
12891 * MAP_SHARED to prevent internal slot pages from being moved
12892 * by fork()/COW.
12893 */
12894 hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
12895 MAP_SHARED | MAP_ANONYMOUS, 0);
12896 if (IS_ERR_VALUE(hva))
12897 return (void __user *)hva;
12898 } else {
12899 if (!slot || !slot->npages)
12900 return NULL;
12901
12902 old_npages = slot->npages;
12903 hva = slot->userspace_addr;
12904 }
12905
12906 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
12907 struct kvm_userspace_memory_region2 m;
12908
12909 m.slot = id | (i << 16);
12910 m.flags = 0;
12911 m.guest_phys_addr = gpa;
12912 m.userspace_addr = hva;
12913 m.memory_size = size;
12914 r = kvm_set_internal_memslot(kvm, &m);
12915 if (r < 0)
12916 return ERR_PTR_USR(r);
12917 }
12918
12919 if (!size)
12920 vm_munmap(hva, old_npages * PAGE_SIZE);
12921
12922 return (void __user *)hva;
12923 }
12924 EXPORT_SYMBOL_GPL(__x86_set_memory_region);
12925
kvm_arch_pre_destroy_vm(struct kvm * kvm)12926 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
12927 {
12928 /*
12929 * Stop all background workers and kthreads before destroying vCPUs, as
12930 * iterating over vCPUs in a different task while vCPUs are being freed
12931 * is unsafe, i.e. will lead to use-after-free. The PIT also needs to
12932 * be stopped before IRQ routing is freed.
12933 */
12934 cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
12935 cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
12936
12937 kvm_free_pit(kvm);
12938
12939 kvm_mmu_pre_destroy_vm(kvm);
12940 static_call_cond(kvm_x86_vm_pre_destroy)(kvm);
12941 }
12942
kvm_arch_destroy_vm(struct kvm * kvm)12943 void kvm_arch_destroy_vm(struct kvm *kvm)
12944 {
12945 if (current->mm == kvm->mm) {
12946 /*
12947 * Free memory regions allocated on behalf of userspace,
12948 * unless the memory map has changed due to process exit
12949 * or fd copying.
12950 */
12951 mutex_lock(&kvm->slots_lock);
12952 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
12953 0, 0);
12954 __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
12955 0, 0);
12956 __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
12957 mutex_unlock(&kvm->slots_lock);
12958 }
12959 kvm_destroy_vcpus(kvm);
12960 kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
12961 kvm_pic_destroy(kvm);
12962 kvm_ioapic_destroy(kvm);
12963 kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
12964 kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
12965 kvm_mmu_uninit_vm(kvm);
12966 kvm_page_track_cleanup(kvm);
12967 kvm_xen_destroy_vm(kvm);
12968 kvm_hv_destroy_vm(kvm);
12969 kvm_x86_call(vm_destroy)(kvm);
12970 }
12971
memslot_rmap_free(struct kvm_memory_slot * slot)12972 static void memslot_rmap_free(struct kvm_memory_slot *slot)
12973 {
12974 int i;
12975
12976 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
12977 vfree(slot->arch.rmap[i]);
12978 slot->arch.rmap[i] = NULL;
12979 }
12980 }
12981
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)12982 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
12983 {
12984 int i;
12985
12986 memslot_rmap_free(slot);
12987
12988 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
12989 vfree(slot->arch.lpage_info[i - 1]);
12990 slot->arch.lpage_info[i - 1] = NULL;
12991 }
12992
12993 kvm_page_track_free_memslot(slot);
12994 }
12995
memslot_rmap_alloc(struct kvm_memory_slot * slot,unsigned long npages)12996 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
12997 {
12998 const int sz = sizeof(*slot->arch.rmap[0]);
12999 int i;
13000
13001 for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13002 int level = i + 1;
13003 int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13004
13005 if (slot->arch.rmap[i])
13006 continue;
13007
13008 slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
13009 if (!slot->arch.rmap[i]) {
13010 memslot_rmap_free(slot);
13011 return -ENOMEM;
13012 }
13013 }
13014
13015 return 0;
13016 }
13017
kvm_alloc_memslot_metadata(struct kvm * kvm,struct kvm_memory_slot * slot)13018 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
13019 struct kvm_memory_slot *slot)
13020 {
13021 unsigned long npages = slot->npages;
13022 int i, r;
13023
13024 /*
13025 * Clear out the previous array pointers for the KVM_MR_MOVE case. The
13026 * old arrays will be freed by kvm_set_memory_region() if installing
13027 * the new memslot is successful.
13028 */
13029 memset(&slot->arch, 0, sizeof(slot->arch));
13030
13031 if (kvm_memslots_have_rmaps(kvm)) {
13032 r = memslot_rmap_alloc(slot, npages);
13033 if (r)
13034 return r;
13035 }
13036
13037 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13038 struct kvm_lpage_info *linfo;
13039 unsigned long ugfn;
13040 int lpages;
13041 int level = i + 1;
13042
13043 lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13044
13045 linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
13046 if (!linfo)
13047 goto out_free;
13048
13049 slot->arch.lpage_info[i - 1] = linfo;
13050
13051 if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
13052 linfo[0].disallow_lpage = 1;
13053 if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
13054 linfo[lpages - 1].disallow_lpage = 1;
13055 ugfn = slot->userspace_addr >> PAGE_SHIFT;
13056 /*
13057 * If the gfn and userspace address are not aligned wrt each
13058 * other, disable large page support for this slot.
13059 */
13060 if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
13061 unsigned long j;
13062
13063 for (j = 0; j < lpages; ++j)
13064 linfo[j].disallow_lpage = 1;
13065 }
13066 }
13067
13068 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
13069 kvm_mmu_init_memslot_memory_attributes(kvm, slot);
13070 #endif
13071
13072 if (kvm_page_track_create_memslot(kvm, slot, npages))
13073 goto out_free;
13074
13075 return 0;
13076
13077 out_free:
13078 memslot_rmap_free(slot);
13079
13080 for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13081 vfree(slot->arch.lpage_info[i - 1]);
13082 slot->arch.lpage_info[i - 1] = NULL;
13083 }
13084 return -ENOMEM;
13085 }
13086
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)13087 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
13088 {
13089 struct kvm_vcpu *vcpu;
13090 unsigned long i;
13091
13092 /*
13093 * memslots->generation has been incremented.
13094 * mmio generation may have reached its maximum value.
13095 */
13096 kvm_mmu_invalidate_mmio_sptes(kvm, gen);
13097
13098 /* Force re-initialization of steal_time cache */
13099 kvm_for_each_vcpu(i, vcpu, kvm)
13100 kvm_vcpu_kick(vcpu);
13101 }
13102
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)13103 int kvm_arch_prepare_memory_region(struct kvm *kvm,
13104 const struct kvm_memory_slot *old,
13105 struct kvm_memory_slot *new,
13106 enum kvm_mr_change change)
13107 {
13108 /*
13109 * KVM doesn't support moving memslots when there are external page
13110 * trackers attached to the VM, i.e. if KVMGT is in use.
13111 */
13112 if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
13113 return -EINVAL;
13114
13115 if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
13116 if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
13117 return -EINVAL;
13118
13119 if (kvm_is_gfn_alias(kvm, new->base_gfn + new->npages - 1))
13120 return -EINVAL;
13121
13122 return kvm_alloc_memslot_metadata(kvm, new);
13123 }
13124
13125 if (change == KVM_MR_FLAGS_ONLY)
13126 memcpy(&new->arch, &old->arch, sizeof(old->arch));
13127 else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
13128 return -EIO;
13129
13130 return 0;
13131 }
13132
13133
kvm_mmu_update_cpu_dirty_logging(struct kvm * kvm,bool enable)13134 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
13135 {
13136 int nr_slots;
13137
13138 if (!kvm->arch.cpu_dirty_log_size)
13139 return;
13140
13141 nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
13142 if ((enable && nr_slots == 1) || !nr_slots)
13143 kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
13144 }
13145
kvm_mmu_slot_apply_flags(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13146 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
13147 struct kvm_memory_slot *old,
13148 const struct kvm_memory_slot *new,
13149 enum kvm_mr_change change)
13150 {
13151 u32 old_flags = old ? old->flags : 0;
13152 u32 new_flags = new ? new->flags : 0;
13153 bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
13154
13155 /*
13156 * Update CPU dirty logging if dirty logging is being toggled. This
13157 * applies to all operations.
13158 */
13159 if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
13160 kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
13161
13162 /*
13163 * Nothing more to do for RO slots (which can't be dirtied and can't be
13164 * made writable) or CREATE/MOVE/DELETE of a slot.
13165 *
13166 * For a memslot with dirty logging disabled:
13167 * CREATE: No dirty mappings will already exist.
13168 * MOVE/DELETE: The old mappings will already have been cleaned up by
13169 * kvm_arch_flush_shadow_memslot()
13170 *
13171 * For a memslot with dirty logging enabled:
13172 * CREATE: No shadow pages exist, thus nothing to write-protect
13173 * and no dirty bits to clear.
13174 * MOVE/DELETE: The old mappings will already have been cleaned up by
13175 * kvm_arch_flush_shadow_memslot().
13176 */
13177 if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
13178 return;
13179
13180 /*
13181 * READONLY and non-flags changes were filtered out above, and the only
13182 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13183 * logging isn't being toggled on or off.
13184 */
13185 if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
13186 return;
13187
13188 if (!log_dirty_pages) {
13189 /*
13190 * Recover huge page mappings in the slot now that dirty logging
13191 * is disabled, i.e. now that KVM does not have to track guest
13192 * writes at 4KiB granularity.
13193 *
13194 * Dirty logging might be disabled by userspace if an ongoing VM
13195 * live migration is cancelled and the VM must continue running
13196 * on the source.
13197 */
13198 kvm_mmu_recover_huge_pages(kvm, new);
13199 } else {
13200 /*
13201 * Initially-all-set does not require write protecting any page,
13202 * because they're all assumed to be dirty.
13203 */
13204 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13205 return;
13206
13207 if (READ_ONCE(eager_page_split))
13208 kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13209
13210 if (kvm->arch.cpu_dirty_log_size) {
13211 kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13212 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13213 } else {
13214 kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
13215 }
13216
13217 /*
13218 * Unconditionally flush the TLBs after enabling dirty logging.
13219 * A flush is almost always going to be necessary (see below),
13220 * and unconditionally flushing allows the helpers to omit
13221 * the subtly complex checks when removing write access.
13222 *
13223 * Do the flush outside of mmu_lock to reduce the amount of
13224 * time mmu_lock is held. Flushing after dropping mmu_lock is
13225 * safe as KVM only needs to guarantee the slot is fully
13226 * write-protected before returning to userspace, i.e. before
13227 * userspace can consume the dirty status.
13228 *
13229 * Flushing outside of mmu_lock requires KVM to be careful when
13230 * making decisions based on writable status of an SPTE, e.g. a
13231 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13232 *
13233 * Specifically, KVM also write-protects guest page tables to
13234 * monitor changes when using shadow paging, and must guarantee
13235 * no CPUs can write to those page before mmu_lock is dropped.
13236 * Because CPUs may have stale TLB entries at this point, a
13237 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13238 *
13239 * KVM also allows making SPTES writable outside of mmu_lock,
13240 * e.g. to allow dirty logging without taking mmu_lock.
13241 *
13242 * To handle these scenarios, KVM uses a separate software-only
13243 * bit (MMU-writable) to track if a SPTE is !writable due to
13244 * a guest page table being write-protected (KVM clears the
13245 * MMU-writable flag when write-protecting for shadow paging).
13246 *
13247 * The use of MMU-writable is also the primary motivation for
13248 * the unconditional flush. Because KVM must guarantee that a
13249 * CPU doesn't contain stale, writable TLB entries for a
13250 * !MMU-writable SPTE, KVM must flush if it encounters any
13251 * MMU-writable SPTE regardless of whether the actual hardware
13252 * writable bit was set. I.e. KVM is almost guaranteed to need
13253 * to flush, while unconditionally flushing allows the "remove
13254 * write access" helpers to ignore MMU-writable entirely.
13255 *
13256 * See is_writable_pte() for more details (the case involving
13257 * access-tracked SPTEs is particularly relevant).
13258 */
13259 kvm_flush_remote_tlbs_memslot(kvm, new);
13260 }
13261 }
13262
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13263 void kvm_arch_commit_memory_region(struct kvm *kvm,
13264 struct kvm_memory_slot *old,
13265 const struct kvm_memory_slot *new,
13266 enum kvm_mr_change change)
13267 {
13268 if (change == KVM_MR_DELETE)
13269 kvm_page_track_delete_slot(kvm, old);
13270
13271 if (!kvm->arch.n_requested_mmu_pages &&
13272 (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13273 unsigned long nr_mmu_pages;
13274
13275 nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13276 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13277 kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13278 }
13279
13280 kvm_mmu_slot_apply_flags(kvm, old, new, change);
13281
13282 /* Free the arrays associated with the old memslot. */
13283 if (change == KVM_MR_MOVE)
13284 kvm_arch_free_memslot(kvm, old);
13285 }
13286
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)13287 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13288 {
13289 WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13290
13291 if (vcpu->arch.guest_state_protected)
13292 return true;
13293
13294 return kvm_x86_call(get_cpl)(vcpu) == 0;
13295 }
13296
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)13297 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13298 {
13299 WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13300
13301 if (vcpu->arch.guest_state_protected)
13302 return 0;
13303
13304 return kvm_rip_read(vcpu);
13305 }
13306
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)13307 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13308 {
13309 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13310 }
13311
kvm_arch_interrupt_allowed(struct kvm_vcpu * vcpu)13312 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13313 {
13314 return kvm_x86_call(interrupt_allowed)(vcpu, false);
13315 }
13316
kvm_get_linear_rip(struct kvm_vcpu * vcpu)13317 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13318 {
13319 /* Can't read the RIP when guest state is protected, just return 0 */
13320 if (vcpu->arch.guest_state_protected)
13321 return 0;
13322
13323 if (is_64_bit_mode(vcpu))
13324 return kvm_rip_read(vcpu);
13325 return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13326 kvm_rip_read(vcpu));
13327 }
13328 EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
13329
kvm_is_linear_rip(struct kvm_vcpu * vcpu,unsigned long linear_rip)13330 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13331 {
13332 return kvm_get_linear_rip(vcpu) == linear_rip;
13333 }
13334 EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
13335
kvm_get_rflags(struct kvm_vcpu * vcpu)13336 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13337 {
13338 unsigned long rflags;
13339
13340 rflags = kvm_x86_call(get_rflags)(vcpu);
13341 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13342 rflags &= ~X86_EFLAGS_TF;
13343 return rflags;
13344 }
13345 EXPORT_SYMBOL_GPL(kvm_get_rflags);
13346
__kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13347 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13348 {
13349 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13350 kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13351 rflags |= X86_EFLAGS_TF;
13352 kvm_x86_call(set_rflags)(vcpu, rflags);
13353 }
13354
kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13355 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13356 {
13357 __kvm_set_rflags(vcpu, rflags);
13358 kvm_make_request(KVM_REQ_EVENT, vcpu);
13359 }
13360 EXPORT_SYMBOL_GPL(kvm_set_rflags);
13361
kvm_async_pf_hash_fn(gfn_t gfn)13362 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13363 {
13364 BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13365
13366 return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13367 }
13368
kvm_async_pf_next_probe(u32 key)13369 static inline u32 kvm_async_pf_next_probe(u32 key)
13370 {
13371 return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13372 }
13373
kvm_add_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13374 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13375 {
13376 u32 key = kvm_async_pf_hash_fn(gfn);
13377
13378 while (vcpu->arch.apf.gfns[key] != ~0)
13379 key = kvm_async_pf_next_probe(key);
13380
13381 vcpu->arch.apf.gfns[key] = gfn;
13382 }
13383
kvm_async_pf_gfn_slot(struct kvm_vcpu * vcpu,gfn_t gfn)13384 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13385 {
13386 int i;
13387 u32 key = kvm_async_pf_hash_fn(gfn);
13388
13389 for (i = 0; i < ASYNC_PF_PER_VCPU &&
13390 (vcpu->arch.apf.gfns[key] != gfn &&
13391 vcpu->arch.apf.gfns[key] != ~0); i++)
13392 key = kvm_async_pf_next_probe(key);
13393
13394 return key;
13395 }
13396
kvm_find_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13397 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13398 {
13399 return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13400 }
13401
kvm_del_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13402 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13403 {
13404 u32 i, j, k;
13405
13406 i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13407
13408 if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13409 return;
13410
13411 while (true) {
13412 vcpu->arch.apf.gfns[i] = ~0;
13413 do {
13414 j = kvm_async_pf_next_probe(j);
13415 if (vcpu->arch.apf.gfns[j] == ~0)
13416 return;
13417 k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13418 /*
13419 * k lies cyclically in ]i,j]
13420 * | i.k.j |
13421 * |....j i.k.| or |.k..j i...|
13422 */
13423 } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13424 vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13425 i = j;
13426 }
13427 }
13428
apf_put_user_notpresent(struct kvm_vcpu * vcpu)13429 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13430 {
13431 u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13432
13433 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13434 sizeof(reason));
13435 }
13436
apf_put_user_ready(struct kvm_vcpu * vcpu,u32 token)13437 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13438 {
13439 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13440
13441 return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13442 &token, offset, sizeof(token));
13443 }
13444
apf_pageready_slot_free(struct kvm_vcpu * vcpu)13445 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13446 {
13447 unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13448 u32 val;
13449
13450 if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13451 &val, offset, sizeof(val)))
13452 return false;
13453
13454 return !val;
13455 }
13456
kvm_can_deliver_async_pf(struct kvm_vcpu * vcpu)13457 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13458 {
13459
13460 if (!kvm_pv_async_pf_enabled(vcpu))
13461 return false;
13462
13463 if (!vcpu->arch.apf.send_always &&
13464 (vcpu->arch.guest_state_protected || !kvm_x86_call(get_cpl)(vcpu)))
13465 return false;
13466
13467 if (is_guest_mode(vcpu)) {
13468 /*
13469 * L1 needs to opt into the special #PF vmexits that are
13470 * used to deliver async page faults.
13471 */
13472 return vcpu->arch.apf.delivery_as_pf_vmexit;
13473 } else {
13474 /*
13475 * Play it safe in case the guest temporarily disables paging.
13476 * The real mode IDT in particular is unlikely to have a #PF
13477 * exception setup.
13478 */
13479 return is_paging(vcpu);
13480 }
13481 }
13482
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)13483 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13484 {
13485 if (unlikely(!lapic_in_kernel(vcpu) ||
13486 kvm_event_needs_reinjection(vcpu) ||
13487 kvm_is_exception_pending(vcpu)))
13488 return false;
13489
13490 if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13491 return false;
13492
13493 /*
13494 * If interrupts are off we cannot even use an artificial
13495 * halt state.
13496 */
13497 return kvm_arch_interrupt_allowed(vcpu);
13498 }
13499
kvm_arch_async_page_not_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13500 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
13501 struct kvm_async_pf *work)
13502 {
13503 struct x86_exception fault;
13504
13505 trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
13506 kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
13507
13508 if (kvm_can_deliver_async_pf(vcpu) &&
13509 !apf_put_user_notpresent(vcpu)) {
13510 fault.vector = PF_VECTOR;
13511 fault.error_code_valid = true;
13512 fault.error_code = 0;
13513 fault.nested_page_fault = false;
13514 fault.address = work->arch.token;
13515 fault.async_page_fault = true;
13516 kvm_inject_page_fault(vcpu, &fault);
13517 return true;
13518 } else {
13519 /*
13520 * It is not possible to deliver a paravirtualized asynchronous
13521 * page fault, but putting the guest in an artificial halt state
13522 * can be beneficial nevertheless: if an interrupt arrives, we
13523 * can deliver it timely and perhaps the guest will schedule
13524 * another process. When the instruction that triggered a page
13525 * fault is retried, hopefully the page will be ready in the host.
13526 */
13527 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
13528 return false;
13529 }
13530 }
13531
kvm_arch_async_page_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13532 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13533 struct kvm_async_pf *work)
13534 {
13535 struct kvm_lapic_irq irq = {
13536 .delivery_mode = APIC_DM_FIXED,
13537 .vector = vcpu->arch.apf.vec
13538 };
13539
13540 if (work->wakeup_all)
13541 work->arch.token = ~0; /* broadcast wakeup */
13542 else
13543 kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
13544 trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
13545
13546 if ((work->wakeup_all || work->notpresent_injected) &&
13547 kvm_pv_async_pf_enabled(vcpu) &&
13548 !apf_put_user_ready(vcpu, work->arch.token)) {
13549 vcpu->arch.apf.pageready_pending = true;
13550 kvm_apic_set_irq(vcpu, &irq, NULL);
13551 }
13552
13553 vcpu->arch.apf.halted = false;
13554 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
13555 }
13556
kvm_arch_async_page_present_queued(struct kvm_vcpu * vcpu)13557 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13558 {
13559 kvm_make_request(KVM_REQ_APF_READY, vcpu);
13560 if (!vcpu->arch.apf.pageready_pending)
13561 kvm_vcpu_kick(vcpu);
13562 }
13563
kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu * vcpu)13564 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
13565 {
13566 if (!kvm_pv_async_pf_enabled(vcpu))
13567 return true;
13568 else
13569 return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
13570 }
13571
kvm_arch_start_assignment(struct kvm * kvm)13572 void kvm_arch_start_assignment(struct kvm *kvm)
13573 {
13574 if (atomic_inc_return(&kvm->arch.assigned_device_count) == 1)
13575 kvm_x86_call(pi_start_assignment)(kvm);
13576 }
13577 EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
13578
kvm_arch_end_assignment(struct kvm * kvm)13579 void kvm_arch_end_assignment(struct kvm *kvm)
13580 {
13581 atomic_dec(&kvm->arch.assigned_device_count);
13582 }
13583 EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
13584
kvm_arch_has_assigned_device(struct kvm * kvm)13585 bool noinstr kvm_arch_has_assigned_device(struct kvm *kvm)
13586 {
13587 return raw_atomic_read(&kvm->arch.assigned_device_count);
13588 }
13589 EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
13590
kvm_noncoherent_dma_assignment_start_or_stop(struct kvm * kvm)13591 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
13592 {
13593 /*
13594 * Non-coherent DMA assignment and de-assignment may affect whether or
13595 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
13596 * due to toggling the "ignore PAT" bit. Zap all SPTEs when the first
13597 * (or last) non-coherent device is (un)registered to so that new SPTEs
13598 * with the correct "ignore guest PAT" setting are created.
13599 *
13600 * If KVM always honors guest PAT, however, there is nothing to do.
13601 */
13602 if (kvm_check_has_quirk(kvm, KVM_X86_QUIRK_IGNORE_GUEST_PAT))
13603 kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
13604 }
13605
kvm_arch_register_noncoherent_dma(struct kvm * kvm)13606 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13607 {
13608 if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
13609 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13610 }
13611 EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
13612
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)13613 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13614 {
13615 if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
13616 kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13617 }
13618 EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
13619
kvm_arch_has_noncoherent_dma(struct kvm * kvm)13620 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13621 {
13622 return atomic_read(&kvm->arch.noncoherent_dma_count);
13623 }
13624 EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
13625
kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)13626 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
13627 struct irq_bypass_producer *prod)
13628 {
13629 struct kvm_kernel_irqfd *irqfd =
13630 container_of(cons, struct kvm_kernel_irqfd, consumer);
13631 struct kvm *kvm = irqfd->kvm;
13632 int ret;
13633
13634 kvm_arch_start_assignment(irqfd->kvm);
13635
13636 spin_lock_irq(&kvm->irqfds.lock);
13637 irqfd->producer = prod;
13638
13639 ret = kvm_x86_call(pi_update_irte)(irqfd->kvm,
13640 prod->irq, irqfd->gsi, 1);
13641 if (ret)
13642 kvm_arch_end_assignment(irqfd->kvm);
13643
13644 spin_unlock_irq(&kvm->irqfds.lock);
13645
13646
13647 return ret;
13648 }
13649
kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)13650 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
13651 struct irq_bypass_producer *prod)
13652 {
13653 int ret;
13654 struct kvm_kernel_irqfd *irqfd =
13655 container_of(cons, struct kvm_kernel_irqfd, consumer);
13656 struct kvm *kvm = irqfd->kvm;
13657
13658 WARN_ON(irqfd->producer != prod);
13659
13660 /*
13661 * When producer of consumer is unregistered, we change back to
13662 * remapped mode, so we can re-use the current implementation
13663 * when the irq is masked/disabled or the consumer side (KVM
13664 * int this case doesn't want to receive the interrupts.
13665 */
13666 spin_lock_irq(&kvm->irqfds.lock);
13667 irqfd->producer = NULL;
13668
13669 ret = kvm_x86_call(pi_update_irte)(irqfd->kvm,
13670 prod->irq, irqfd->gsi, 0);
13671 if (ret)
13672 printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
13673 " fails: %d\n", irqfd->consumer.token, ret);
13674
13675 spin_unlock_irq(&kvm->irqfds.lock);
13676
13677
13678 kvm_arch_end_assignment(irqfd->kvm);
13679 }
13680
kvm_arch_update_irqfd_routing(struct kvm * kvm,unsigned int host_irq,uint32_t guest_irq,bool set)13681 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
13682 uint32_t guest_irq, bool set)
13683 {
13684 return kvm_x86_call(pi_update_irte)(kvm, host_irq, guest_irq, set);
13685 }
13686
kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry * old,struct kvm_kernel_irq_routing_entry * new)13687 bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *old,
13688 struct kvm_kernel_irq_routing_entry *new)
13689 {
13690 if (old->type != KVM_IRQ_ROUTING_MSI ||
13691 new->type != KVM_IRQ_ROUTING_MSI)
13692 return true;
13693
13694 return !!memcmp(&old->msi, &new->msi, sizeof(new->msi));
13695 }
13696
kvm_vector_hashing_enabled(void)13697 bool kvm_vector_hashing_enabled(void)
13698 {
13699 return vector_hashing;
13700 }
13701
kvm_arch_no_poll(struct kvm_vcpu * vcpu)13702 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13703 {
13704 return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13705 }
13706 EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
13707
13708 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
kvm_arch_gmem_prepare(struct kvm * kvm,gfn_t gfn,kvm_pfn_t pfn,int max_order)13709 int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
13710 {
13711 return kvm_x86_call(gmem_prepare)(kvm, pfn, gfn, max_order);
13712 }
13713 #endif
13714
13715 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
kvm_arch_gmem_invalidate(kvm_pfn_t start,kvm_pfn_t end)13716 void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
13717 {
13718 kvm_x86_call(gmem_invalidate)(start, end);
13719 }
13720 #endif
13721
kvm_spec_ctrl_test_value(u64 value)13722 int kvm_spec_ctrl_test_value(u64 value)
13723 {
13724 /*
13725 * test that setting IA32_SPEC_CTRL to given value
13726 * is allowed by the host processor
13727 */
13728
13729 u64 saved_value;
13730 unsigned long flags;
13731 int ret = 0;
13732
13733 local_irq_save(flags);
13734
13735 if (rdmsrq_safe(MSR_IA32_SPEC_CTRL, &saved_value))
13736 ret = 1;
13737 else if (wrmsrq_safe(MSR_IA32_SPEC_CTRL, value))
13738 ret = 1;
13739 else
13740 wrmsrq(MSR_IA32_SPEC_CTRL, saved_value);
13741
13742 local_irq_restore(flags);
13743
13744 return ret;
13745 }
13746 EXPORT_SYMBOL_GPL(kvm_spec_ctrl_test_value);
13747
kvm_fixup_and_inject_pf_error(struct kvm_vcpu * vcpu,gva_t gva,u16 error_code)13748 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
13749 {
13750 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
13751 struct x86_exception fault;
13752 u64 access = error_code &
13753 (PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
13754
13755 if (!(error_code & PFERR_PRESENT_MASK) ||
13756 mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
13757 /*
13758 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
13759 * tables probably do not match the TLB. Just proceed
13760 * with the error code that the processor gave.
13761 */
13762 fault.vector = PF_VECTOR;
13763 fault.error_code_valid = true;
13764 fault.error_code = error_code;
13765 fault.nested_page_fault = false;
13766 fault.address = gva;
13767 fault.async_page_fault = false;
13768 }
13769 vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
13770 }
13771 EXPORT_SYMBOL_GPL(kvm_fixup_and_inject_pf_error);
13772
13773 /*
13774 * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
13775 * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
13776 * indicates whether exit to userspace is needed.
13777 */
kvm_handle_memory_failure(struct kvm_vcpu * vcpu,int r,struct x86_exception * e)13778 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
13779 struct x86_exception *e)
13780 {
13781 if (r == X86EMUL_PROPAGATE_FAULT) {
13782 if (KVM_BUG_ON(!e, vcpu->kvm))
13783 return -EIO;
13784
13785 kvm_inject_emulated_page_fault(vcpu, e);
13786 return 1;
13787 }
13788
13789 /*
13790 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
13791 * while handling a VMX instruction KVM could've handled the request
13792 * correctly by exiting to userspace and performing I/O but there
13793 * doesn't seem to be a real use-case behind such requests, just return
13794 * KVM_EXIT_INTERNAL_ERROR for now.
13795 */
13796 kvm_prepare_emulation_failure_exit(vcpu);
13797
13798 return 0;
13799 }
13800 EXPORT_SYMBOL_GPL(kvm_handle_memory_failure);
13801
kvm_handle_invpcid(struct kvm_vcpu * vcpu,unsigned long type,gva_t gva)13802 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
13803 {
13804 bool pcid_enabled;
13805 struct x86_exception e;
13806 struct {
13807 u64 pcid;
13808 u64 gla;
13809 } operand;
13810 int r;
13811
13812 r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
13813 if (r != X86EMUL_CONTINUE)
13814 return kvm_handle_memory_failure(vcpu, r, &e);
13815
13816 if (operand.pcid >> 12 != 0) {
13817 kvm_inject_gp(vcpu, 0);
13818 return 1;
13819 }
13820
13821 pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
13822
13823 switch (type) {
13824 case INVPCID_TYPE_INDIV_ADDR:
13825 /*
13826 * LAM doesn't apply to addresses that are inputs to TLB
13827 * invalidation.
13828 */
13829 if ((!pcid_enabled && (operand.pcid != 0)) ||
13830 is_noncanonical_invlpg_address(operand.gla, vcpu)) {
13831 kvm_inject_gp(vcpu, 0);
13832 return 1;
13833 }
13834 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
13835 return kvm_skip_emulated_instruction(vcpu);
13836
13837 case INVPCID_TYPE_SINGLE_CTXT:
13838 if (!pcid_enabled && (operand.pcid != 0)) {
13839 kvm_inject_gp(vcpu, 0);
13840 return 1;
13841 }
13842
13843 kvm_invalidate_pcid(vcpu, operand.pcid);
13844 return kvm_skip_emulated_instruction(vcpu);
13845
13846 case INVPCID_TYPE_ALL_NON_GLOBAL:
13847 /*
13848 * Currently, KVM doesn't mark global entries in the shadow
13849 * page tables, so a non-global flush just degenerates to a
13850 * global flush. If needed, we could optimize this later by
13851 * keeping track of global entries in shadow page tables.
13852 */
13853
13854 fallthrough;
13855 case INVPCID_TYPE_ALL_INCL_GLOBAL:
13856 kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
13857 return kvm_skip_emulated_instruction(vcpu);
13858
13859 default:
13860 kvm_inject_gp(vcpu, 0);
13861 return 1;
13862 }
13863 }
13864 EXPORT_SYMBOL_GPL(kvm_handle_invpcid);
13865
complete_sev_es_emulated_mmio(struct kvm_vcpu * vcpu)13866 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
13867 {
13868 struct kvm_run *run = vcpu->run;
13869 struct kvm_mmio_fragment *frag;
13870 unsigned int len;
13871
13872 BUG_ON(!vcpu->mmio_needed);
13873
13874 /* Complete previous fragment */
13875 frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
13876 len = min(8u, frag->len);
13877 if (!vcpu->mmio_is_write)
13878 memcpy(frag->data, run->mmio.data, len);
13879
13880 if (frag->len <= 8) {
13881 /* Switch to the next fragment. */
13882 frag++;
13883 vcpu->mmio_cur_fragment++;
13884 } else {
13885 /* Go forward to the next mmio piece. */
13886 frag->data += len;
13887 frag->gpa += len;
13888 frag->len -= len;
13889 }
13890
13891 if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
13892 vcpu->mmio_needed = 0;
13893
13894 // VMG change, at this point, we're always done
13895 // RIP has already been advanced
13896 return 1;
13897 }
13898
13899 // More MMIO is needed
13900 run->mmio.phys_addr = frag->gpa;
13901 run->mmio.len = min(8u, frag->len);
13902 run->mmio.is_write = vcpu->mmio_is_write;
13903 if (run->mmio.is_write)
13904 memcpy(run->mmio.data, frag->data, min(8u, frag->len));
13905 run->exit_reason = KVM_EXIT_MMIO;
13906
13907 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13908
13909 return 0;
13910 }
13911
kvm_sev_es_mmio_write(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)13912 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13913 void *data)
13914 {
13915 int handled;
13916 struct kvm_mmio_fragment *frag;
13917
13918 if (!data)
13919 return -EINVAL;
13920
13921 handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13922 if (handled == bytes)
13923 return 1;
13924
13925 bytes -= handled;
13926 gpa += handled;
13927 data += handled;
13928
13929 /*TODO: Check if need to increment number of frags */
13930 frag = vcpu->mmio_fragments;
13931 vcpu->mmio_nr_fragments = 1;
13932 frag->len = bytes;
13933 frag->gpa = gpa;
13934 frag->data = data;
13935
13936 vcpu->mmio_needed = 1;
13937 vcpu->mmio_cur_fragment = 0;
13938
13939 vcpu->run->mmio.phys_addr = gpa;
13940 vcpu->run->mmio.len = min(8u, frag->len);
13941 vcpu->run->mmio.is_write = 1;
13942 memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
13943 vcpu->run->exit_reason = KVM_EXIT_MMIO;
13944
13945 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13946
13947 return 0;
13948 }
13949 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_write);
13950
kvm_sev_es_mmio_read(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)13951 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
13952 void *data)
13953 {
13954 int handled;
13955 struct kvm_mmio_fragment *frag;
13956
13957 if (!data)
13958 return -EINVAL;
13959
13960 handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
13961 if (handled == bytes)
13962 return 1;
13963
13964 bytes -= handled;
13965 gpa += handled;
13966 data += handled;
13967
13968 /*TODO: Check if need to increment number of frags */
13969 frag = vcpu->mmio_fragments;
13970 vcpu->mmio_nr_fragments = 1;
13971 frag->len = bytes;
13972 frag->gpa = gpa;
13973 frag->data = data;
13974
13975 vcpu->mmio_needed = 1;
13976 vcpu->mmio_cur_fragment = 0;
13977
13978 vcpu->run->mmio.phys_addr = gpa;
13979 vcpu->run->mmio.len = min(8u, frag->len);
13980 vcpu->run->mmio.is_write = 0;
13981 vcpu->run->exit_reason = KVM_EXIT_MMIO;
13982
13983 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
13984
13985 return 0;
13986 }
13987 EXPORT_SYMBOL_GPL(kvm_sev_es_mmio_read);
13988
advance_sev_es_emulated_pio(struct kvm_vcpu * vcpu,unsigned count,int size)13989 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
13990 {
13991 vcpu->arch.sev_pio_count -= count;
13992 vcpu->arch.sev_pio_data += count * size;
13993 }
13994
13995 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
13996 unsigned int port);
13997
complete_sev_es_emulated_outs(struct kvm_vcpu * vcpu)13998 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
13999 {
14000 int size = vcpu->arch.pio.size;
14001 int port = vcpu->arch.pio.port;
14002
14003 vcpu->arch.pio.count = 0;
14004 if (vcpu->arch.sev_pio_count)
14005 return kvm_sev_es_outs(vcpu, size, port);
14006 return 1;
14007 }
14008
kvm_sev_es_outs(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14009 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14010 unsigned int port)
14011 {
14012 for (;;) {
14013 unsigned int count =
14014 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14015 int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
14016
14017 /* memcpy done already by emulator_pio_out. */
14018 advance_sev_es_emulated_pio(vcpu, count, size);
14019 if (!ret)
14020 break;
14021
14022 /* Emulation done by the kernel. */
14023 if (!vcpu->arch.sev_pio_count)
14024 return 1;
14025 }
14026
14027 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
14028 return 0;
14029 }
14030
14031 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14032 unsigned int port);
14033
complete_sev_es_emulated_ins(struct kvm_vcpu * vcpu)14034 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
14035 {
14036 unsigned count = vcpu->arch.pio.count;
14037 int size = vcpu->arch.pio.size;
14038 int port = vcpu->arch.pio.port;
14039
14040 complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
14041 advance_sev_es_emulated_pio(vcpu, count, size);
14042 if (vcpu->arch.sev_pio_count)
14043 return kvm_sev_es_ins(vcpu, size, port);
14044 return 1;
14045 }
14046
kvm_sev_es_ins(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14047 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14048 unsigned int port)
14049 {
14050 for (;;) {
14051 unsigned int count =
14052 min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14053 if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
14054 break;
14055
14056 /* Emulation done by the kernel. */
14057 advance_sev_es_emulated_pio(vcpu, count, size);
14058 if (!vcpu->arch.sev_pio_count)
14059 return 1;
14060 }
14061
14062 vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
14063 return 0;
14064 }
14065
kvm_sev_es_string_io(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port,void * data,unsigned int count,int in)14066 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
14067 unsigned int port, void *data, unsigned int count,
14068 int in)
14069 {
14070 vcpu->arch.sev_pio_data = data;
14071 vcpu->arch.sev_pio_count = count;
14072 return in ? kvm_sev_es_ins(vcpu, size, port)
14073 : kvm_sev_es_outs(vcpu, size, port);
14074 }
14075 EXPORT_SYMBOL_GPL(kvm_sev_es_string_io);
14076
14077 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
14078 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
14079 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_mmio);
14080 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
14081 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
14082 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
14083 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
14084 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
14085 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
14086 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
14087 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
14088 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
14089 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
14090 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
14091 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
14092 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
14093 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
14094 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
14095 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
14096 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
14097 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
14098 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
14099 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
14100 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
14101 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
14102 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
14103 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
14104 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
14105 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
14106 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
14107 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
14108
kvm_x86_init(void)14109 static int __init kvm_x86_init(void)
14110 {
14111 kvm_init_xstate_sizes();
14112
14113 kvm_mmu_x86_module_init();
14114 mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
14115 return 0;
14116 }
14117 module_init(kvm_x86_init);
14118
kvm_x86_exit(void)14119 static void __exit kvm_x86_exit(void)
14120 {
14121 WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
14122 }
14123 module_exit(kvm_x86_exit);
14124