xref: /linux/arch/x86/kvm/x86.c (revision 4ea7c1717f3f2344f7a1cdab4f5875cfa89c87a9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * derived from drivers/kvm/kvm_main.c
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright (C) 2008 Qumranet, Inc.
9  * Copyright IBM Corporation, 2008
10  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11  *
12  * Authors:
13  *   Avi Kivity   <avi@qumranet.com>
14  *   Yaniv Kamay  <yaniv@qumranet.com>
15  *   Amit Shah    <amit.shah@qumranet.com>
16  *   Ben-Ami Yassour <benami@il.ibm.com>
17  */
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19 
20 #include <linux/kvm_host.h>
21 #include "irq.h"
22 #include "ioapic.h"
23 #include "mmu.h"
24 #include "i8254.h"
25 #include "tss.h"
26 #include "kvm_cache_regs.h"
27 #include "kvm_emulate.h"
28 #include "mmu/page_track.h"
29 #include "x86.h"
30 #include "cpuid.h"
31 #include "pmu.h"
32 #include "hyperv.h"
33 #include "lapic.h"
34 #include "xen.h"
35 #include "smm.h"
36 
37 #include <linux/clocksource.h>
38 #include <linux/interrupt.h>
39 #include <linux/kvm.h>
40 #include <linux/fs.h>
41 #include <linux/vmalloc.h>
42 #include <linux/export.h>
43 #include <linux/moduleparam.h>
44 #include <linux/mman.h>
45 #include <linux/highmem.h>
46 #include <linux/iommu.h>
47 #include <linux/cpufreq.h>
48 #include <linux/user-return-notifier.h>
49 #include <linux/srcu.h>
50 #include <linux/slab.h>
51 #include <linux/perf_event.h>
52 #include <linux/uaccess.h>
53 #include <linux/hash.h>
54 #include <linux/pci.h>
55 #include <linux/timekeeper_internal.h>
56 #include <linux/pvclock_gtod.h>
57 #include <linux/kvm_irqfd.h>
58 #include <linux/irqbypass.h>
59 #include <linux/sched/stat.h>
60 #include <linux/sched/isolation.h>
61 #include <linux/mem_encrypt.h>
62 #include <linux/suspend.h>
63 #include <linux/smp.h>
64 
65 #include <trace/events/ipi.h>
66 #include <trace/events/kvm.h>
67 
68 #include <asm/debugreg.h>
69 #include <asm/msr.h>
70 #include <asm/desc.h>
71 #include <asm/mce.h>
72 #include <asm/pkru.h>
73 #include <linux/kernel_stat.h>
74 #include <asm/fpu/api.h>
75 #include <asm/fpu/xcr.h>
76 #include <asm/fpu/xstate.h>
77 #include <asm/pvclock.h>
78 #include <asm/div64.h>
79 #include <asm/irq_remapping.h>
80 #include <asm/mshyperv.h>
81 #include <asm/hypervisor.h>
82 #include <asm/tlbflush.h>
83 #include <asm/intel_pt.h>
84 #include <asm/emulate_prefix.h>
85 #include <asm/sgx.h>
86 #include <clocksource/hyperv_timer.h>
87 
88 #define CREATE_TRACE_POINTS
89 #include "trace.h"
90 
91 #define MAX_IO_MSRS 256
92 
93 /*
94  * Note, kvm_caps fields should *never* have default values, all fields must be
95  * recomputed from scratch during vendor module load, e.g. to account for a
96  * vendor module being reloaded with different module parameters.
97  */
98 struct kvm_caps kvm_caps __read_mostly;
99 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_caps);
100 
101 struct kvm_host_values kvm_host __read_mostly;
102 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_host);
103 
104 #define  ERR_PTR_USR(e)  ((void __user *)ERR_PTR(e))
105 
106 #define emul_to_vcpu(ctxt) \
107 	((struct kvm_vcpu *)(ctxt)->vcpu)
108 
109 /* EFER defaults:
110  * - enable syscall per default because its emulated by KVM
111  * - enable LME and LMA per default on 64 bit KVM
112  */
113 #ifdef CONFIG_X86_64
114 static
115 u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
116 #else
117 static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
118 #endif
119 
120 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
121 
122 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
123 
124 #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
125                                     KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
126 
127 static void update_cr8_intercept(struct kvm_vcpu *vcpu);
128 static void process_nmi(struct kvm_vcpu *vcpu);
129 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
130 static void store_regs(struct kvm_vcpu *vcpu);
131 static int sync_regs(struct kvm_vcpu *vcpu);
132 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu);
133 
134 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
135 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2);
136 
137 static DEFINE_MUTEX(vendor_module_lock);
138 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu);
139 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu);
140 
141 struct kvm_x86_ops kvm_x86_ops __read_mostly;
142 
143 #define KVM_X86_OP(func)					     \
144 	DEFINE_STATIC_CALL_NULL(kvm_x86_##func,			     \
145 				*(((struct kvm_x86_ops *)0)->func));
146 #define KVM_X86_OP_OPTIONAL KVM_X86_OP
147 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
148 #include <asm/kvm-x86-ops.h>
149 EXPORT_STATIC_CALL_GPL(kvm_x86_get_cs_db_l_bits);
150 EXPORT_STATIC_CALL_GPL(kvm_x86_cache_reg);
151 
152 static bool __read_mostly ignore_msrs = 0;
153 module_param(ignore_msrs, bool, 0644);
154 
155 bool __read_mostly report_ignored_msrs = true;
156 module_param(report_ignored_msrs, bool, 0644);
157 EXPORT_SYMBOL_FOR_KVM_INTERNAL(report_ignored_msrs);
158 
159 unsigned int min_timer_period_us = 200;
160 module_param(min_timer_period_us, uint, 0644);
161 
162 static bool __read_mostly kvmclock_periodic_sync = true;
163 module_param(kvmclock_periodic_sync, bool, 0444);
164 
165 /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
166 static u32 __read_mostly tsc_tolerance_ppm = 250;
167 module_param(tsc_tolerance_ppm, uint, 0644);
168 
169 bool __read_mostly enable_vmware_backdoor = false;
170 module_param(enable_vmware_backdoor, bool, 0444);
171 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_vmware_backdoor);
172 
173 /*
174  * Flags to manipulate forced emulation behavior (any non-zero value will
175  * enable forced emulation).
176  */
177 #define KVM_FEP_CLEAR_RFLAGS_RF	BIT(1)
178 static int __read_mostly force_emulation_prefix;
179 module_param(force_emulation_prefix, int, 0644);
180 
181 int __read_mostly pi_inject_timer = -1;
182 module_param(pi_inject_timer, bint, 0644);
183 
184 /* Enable/disable PMU virtualization */
185 bool __read_mostly enable_pmu = true;
186 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_pmu);
187 module_param(enable_pmu, bool, 0444);
188 
189 bool __read_mostly eager_page_split = true;
190 module_param(eager_page_split, bool, 0644);
191 
192 /* Enable/disable SMT_RSB bug mitigation */
193 static bool __read_mostly mitigate_smt_rsb;
194 module_param(mitigate_smt_rsb, bool, 0444);
195 
196 /*
197  * Restoring the host value for MSRs that are only consumed when running in
198  * usermode, e.g. SYSCALL MSRs and TSC_AUX, can be deferred until the CPU
199  * returns to userspace, i.e. the kernel can run with the guest's value.
200  */
201 #define KVM_MAX_NR_USER_RETURN_MSRS 16
202 
203 struct kvm_user_return_msrs {
204 	struct user_return_notifier urn;
205 	bool registered;
206 	struct kvm_user_return_msr_values {
207 		u64 host;
208 		u64 curr;
209 	} values[KVM_MAX_NR_USER_RETURN_MSRS];
210 };
211 
212 u32 __read_mostly kvm_nr_uret_msrs;
213 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_nr_uret_msrs);
214 static u32 __read_mostly kvm_uret_msrs_list[KVM_MAX_NR_USER_RETURN_MSRS];
215 static struct kvm_user_return_msrs __percpu *user_return_msrs;
216 
217 #define KVM_SUPPORTED_XCR0     (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \
218 				| XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \
219 				| XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \
220 				| XFEATURE_MASK_PKRU | XFEATURE_MASK_XTILE)
221 
222 #define XFEATURE_MASK_CET_ALL	(XFEATURE_MASK_CET_USER | XFEATURE_MASK_CET_KERNEL)
223 /*
224  * Note, KVM supports exposing PT to the guest, but does not support context
225  * switching PT via XSTATE (KVM's PT virtualization relies on perf; swapping
226  * PT via guest XSTATE would clobber perf state), i.e. KVM doesn't support
227  * IA32_XSS[bit 8] (guests can/must use RDMSR/WRMSR to save/restore PT MSRs).
228  */
229 #define KVM_SUPPORTED_XSS	(XFEATURE_MASK_CET_ALL)
230 
231 bool __read_mostly allow_smaller_maxphyaddr = 0;
232 EXPORT_SYMBOL_FOR_KVM_INTERNAL(allow_smaller_maxphyaddr);
233 
234 bool __read_mostly enable_apicv = true;
235 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_apicv);
236 
237 bool __read_mostly enable_ipiv = true;
238 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_ipiv);
239 
240 bool __read_mostly enable_device_posted_irqs = true;
241 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_device_posted_irqs);
242 
243 const struct _kvm_stats_desc kvm_vm_stats_desc[] = {
244 	KVM_GENERIC_VM_STATS(),
245 	STATS_DESC_COUNTER(VM, mmu_shadow_zapped),
246 	STATS_DESC_COUNTER(VM, mmu_pte_write),
247 	STATS_DESC_COUNTER(VM, mmu_pde_zapped),
248 	STATS_DESC_COUNTER(VM, mmu_flooded),
249 	STATS_DESC_COUNTER(VM, mmu_recycled),
250 	STATS_DESC_COUNTER(VM, mmu_cache_miss),
251 	STATS_DESC_ICOUNTER(VM, mmu_unsync),
252 	STATS_DESC_ICOUNTER(VM, pages_4k),
253 	STATS_DESC_ICOUNTER(VM, pages_2m),
254 	STATS_DESC_ICOUNTER(VM, pages_1g),
255 	STATS_DESC_ICOUNTER(VM, nx_lpage_splits),
256 	STATS_DESC_PCOUNTER(VM, max_mmu_rmap_size),
257 	STATS_DESC_PCOUNTER(VM, max_mmu_page_hash_collisions)
258 };
259 
260 const struct kvm_stats_header kvm_vm_stats_header = {
261 	.name_size = KVM_STATS_NAME_SIZE,
262 	.num_desc = ARRAY_SIZE(kvm_vm_stats_desc),
263 	.id_offset = sizeof(struct kvm_stats_header),
264 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
265 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
266 		       sizeof(kvm_vm_stats_desc),
267 };
268 
269 const struct _kvm_stats_desc kvm_vcpu_stats_desc[] = {
270 	KVM_GENERIC_VCPU_STATS(),
271 	STATS_DESC_COUNTER(VCPU, pf_taken),
272 	STATS_DESC_COUNTER(VCPU, pf_fixed),
273 	STATS_DESC_COUNTER(VCPU, pf_emulate),
274 	STATS_DESC_COUNTER(VCPU, pf_spurious),
275 	STATS_DESC_COUNTER(VCPU, pf_fast),
276 	STATS_DESC_COUNTER(VCPU, pf_mmio_spte_created),
277 	STATS_DESC_COUNTER(VCPU, pf_guest),
278 	STATS_DESC_COUNTER(VCPU, tlb_flush),
279 	STATS_DESC_COUNTER(VCPU, invlpg),
280 	STATS_DESC_COUNTER(VCPU, exits),
281 	STATS_DESC_COUNTER(VCPU, io_exits),
282 	STATS_DESC_COUNTER(VCPU, mmio_exits),
283 	STATS_DESC_COUNTER(VCPU, signal_exits),
284 	STATS_DESC_COUNTER(VCPU, irq_window_exits),
285 	STATS_DESC_COUNTER(VCPU, nmi_window_exits),
286 	STATS_DESC_COUNTER(VCPU, l1d_flush),
287 	STATS_DESC_COUNTER(VCPU, halt_exits),
288 	STATS_DESC_COUNTER(VCPU, request_irq_exits),
289 	STATS_DESC_COUNTER(VCPU, irq_exits),
290 	STATS_DESC_COUNTER(VCPU, host_state_reload),
291 	STATS_DESC_COUNTER(VCPU, fpu_reload),
292 	STATS_DESC_COUNTER(VCPU, insn_emulation),
293 	STATS_DESC_COUNTER(VCPU, insn_emulation_fail),
294 	STATS_DESC_COUNTER(VCPU, hypercalls),
295 	STATS_DESC_COUNTER(VCPU, irq_injections),
296 	STATS_DESC_COUNTER(VCPU, nmi_injections),
297 	STATS_DESC_COUNTER(VCPU, req_event),
298 	STATS_DESC_COUNTER(VCPU, nested_run),
299 	STATS_DESC_COUNTER(VCPU, directed_yield_attempted),
300 	STATS_DESC_COUNTER(VCPU, directed_yield_successful),
301 	STATS_DESC_COUNTER(VCPU, preemption_reported),
302 	STATS_DESC_COUNTER(VCPU, preemption_other),
303 	STATS_DESC_IBOOLEAN(VCPU, guest_mode),
304 	STATS_DESC_COUNTER(VCPU, notify_window_exits),
305 };
306 
307 const struct kvm_stats_header kvm_vcpu_stats_header = {
308 	.name_size = KVM_STATS_NAME_SIZE,
309 	.num_desc = ARRAY_SIZE(kvm_vcpu_stats_desc),
310 	.id_offset = sizeof(struct kvm_stats_header),
311 	.desc_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE,
312 	.data_offset = sizeof(struct kvm_stats_header) + KVM_STATS_NAME_SIZE +
313 		       sizeof(kvm_vcpu_stats_desc),
314 };
315 
316 static struct kmem_cache *x86_emulator_cache;
317 
318 /*
319  * The three MSR lists(msrs_to_save, emulated_msrs, msr_based_features) track
320  * the set of MSRs that KVM exposes to userspace through KVM_GET_MSRS,
321  * KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.  msrs_to_save holds MSRs that
322  * require host support, i.e. should be probed via RDMSR.  emulated_msrs holds
323  * MSRs that KVM emulates without strictly requiring host support.
324  * msr_based_features holds MSRs that enumerate features, i.e. are effectively
325  * CPUID leafs.  Note, msr_based_features isn't mutually exclusive with
326  * msrs_to_save and emulated_msrs.
327  */
328 
329 static const u32 msrs_to_save_base[] = {
330 	MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
331 	MSR_STAR,
332 #ifdef CONFIG_X86_64
333 	MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
334 #endif
335 	MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
336 	MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
337 	MSR_IA32_SPEC_CTRL, MSR_IA32_TSX_CTRL,
338 	MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
339 	MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
340 	MSR_IA32_RTIT_ADDR0_A, MSR_IA32_RTIT_ADDR0_B,
341 	MSR_IA32_RTIT_ADDR1_A, MSR_IA32_RTIT_ADDR1_B,
342 	MSR_IA32_RTIT_ADDR2_A, MSR_IA32_RTIT_ADDR2_B,
343 	MSR_IA32_RTIT_ADDR3_A, MSR_IA32_RTIT_ADDR3_B,
344 	MSR_IA32_UMWAIT_CONTROL,
345 
346 	MSR_IA32_XFD, MSR_IA32_XFD_ERR, MSR_IA32_XSS,
347 
348 	MSR_IA32_U_CET, MSR_IA32_S_CET,
349 	MSR_IA32_PL0_SSP, MSR_IA32_PL1_SSP, MSR_IA32_PL2_SSP,
350 	MSR_IA32_PL3_SSP, MSR_IA32_INT_SSP_TAB,
351 };
352 
353 static const u32 msrs_to_save_pmu[] = {
354 	MSR_ARCH_PERFMON_FIXED_CTR0, MSR_ARCH_PERFMON_FIXED_CTR1,
355 	MSR_ARCH_PERFMON_FIXED_CTR0 + 2,
356 	MSR_CORE_PERF_FIXED_CTR_CTRL, MSR_CORE_PERF_GLOBAL_STATUS,
357 	MSR_CORE_PERF_GLOBAL_CTRL,
358 	MSR_IA32_PEBS_ENABLE, MSR_IA32_DS_AREA, MSR_PEBS_DATA_CFG,
359 
360 	/* This part of MSRs should match KVM_MAX_NR_INTEL_GP_COUNTERS. */
361 	MSR_ARCH_PERFMON_PERFCTR0, MSR_ARCH_PERFMON_PERFCTR1,
362 	MSR_ARCH_PERFMON_PERFCTR0 + 2, MSR_ARCH_PERFMON_PERFCTR0 + 3,
363 	MSR_ARCH_PERFMON_PERFCTR0 + 4, MSR_ARCH_PERFMON_PERFCTR0 + 5,
364 	MSR_ARCH_PERFMON_PERFCTR0 + 6, MSR_ARCH_PERFMON_PERFCTR0 + 7,
365 	MSR_ARCH_PERFMON_EVENTSEL0, MSR_ARCH_PERFMON_EVENTSEL1,
366 	MSR_ARCH_PERFMON_EVENTSEL0 + 2, MSR_ARCH_PERFMON_EVENTSEL0 + 3,
367 	MSR_ARCH_PERFMON_EVENTSEL0 + 4, MSR_ARCH_PERFMON_EVENTSEL0 + 5,
368 	MSR_ARCH_PERFMON_EVENTSEL0 + 6, MSR_ARCH_PERFMON_EVENTSEL0 + 7,
369 
370 	MSR_K7_EVNTSEL0, MSR_K7_EVNTSEL1, MSR_K7_EVNTSEL2, MSR_K7_EVNTSEL3,
371 	MSR_K7_PERFCTR0, MSR_K7_PERFCTR1, MSR_K7_PERFCTR2, MSR_K7_PERFCTR3,
372 
373 	/* This part of MSRs should match KVM_MAX_NR_AMD_GP_COUNTERS. */
374 	MSR_F15H_PERF_CTL0, MSR_F15H_PERF_CTL1, MSR_F15H_PERF_CTL2,
375 	MSR_F15H_PERF_CTL3, MSR_F15H_PERF_CTL4, MSR_F15H_PERF_CTL5,
376 	MSR_F15H_PERF_CTR0, MSR_F15H_PERF_CTR1, MSR_F15H_PERF_CTR2,
377 	MSR_F15H_PERF_CTR3, MSR_F15H_PERF_CTR4, MSR_F15H_PERF_CTR5,
378 
379 	MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
380 	MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
381 	MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
382 	MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET,
383 };
384 
385 static u32 msrs_to_save[ARRAY_SIZE(msrs_to_save_base) +
386 			ARRAY_SIZE(msrs_to_save_pmu)];
387 static unsigned num_msrs_to_save;
388 
389 static const u32 emulated_msrs_all[] = {
390 	MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
391 	MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
392 
393 #ifdef CONFIG_KVM_HYPERV
394 	HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
395 	HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
396 	HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
397 	HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
398 	HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
399 	HV_X64_MSR_RESET,
400 	HV_X64_MSR_VP_INDEX,
401 	HV_X64_MSR_VP_RUNTIME,
402 	HV_X64_MSR_SCONTROL,
403 	HV_X64_MSR_STIMER0_CONFIG,
404 	HV_X64_MSR_VP_ASSIST_PAGE,
405 	HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
406 	HV_X64_MSR_TSC_EMULATION_STATUS, HV_X64_MSR_TSC_INVARIANT_CONTROL,
407 	HV_X64_MSR_SYNDBG_OPTIONS,
408 	HV_X64_MSR_SYNDBG_CONTROL, HV_X64_MSR_SYNDBG_STATUS,
409 	HV_X64_MSR_SYNDBG_SEND_BUFFER, HV_X64_MSR_SYNDBG_RECV_BUFFER,
410 	HV_X64_MSR_SYNDBG_PENDING_BUFFER,
411 #endif
412 
413 	MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
414 	MSR_KVM_PV_EOI_EN, MSR_KVM_ASYNC_PF_INT, MSR_KVM_ASYNC_PF_ACK,
415 
416 	MSR_IA32_TSC_ADJUST,
417 	MSR_IA32_TSC_DEADLINE,
418 	MSR_IA32_ARCH_CAPABILITIES,
419 	MSR_IA32_PERF_CAPABILITIES,
420 	MSR_IA32_MISC_ENABLE,
421 	MSR_IA32_MCG_STATUS,
422 	MSR_IA32_MCG_CTL,
423 	MSR_IA32_MCG_EXT_CTL,
424 	MSR_IA32_SMBASE,
425 	MSR_SMI_COUNT,
426 	MSR_PLATFORM_INFO,
427 	MSR_MISC_FEATURES_ENABLES,
428 	MSR_AMD64_VIRT_SPEC_CTRL,
429 	MSR_AMD64_TSC_RATIO,
430 	MSR_IA32_POWER_CTL,
431 	MSR_IA32_UCODE_REV,
432 
433 	/*
434 	 * KVM always supports the "true" VMX control MSRs, even if the host
435 	 * does not.  The VMX MSRs as a whole are considered "emulated" as KVM
436 	 * doesn't strictly require them to exist in the host (ignoring that
437 	 * KVM would refuse to load in the first place if the core set of MSRs
438 	 * aren't supported).
439 	 */
440 	MSR_IA32_VMX_BASIC,
441 	MSR_IA32_VMX_TRUE_PINBASED_CTLS,
442 	MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
443 	MSR_IA32_VMX_TRUE_EXIT_CTLS,
444 	MSR_IA32_VMX_TRUE_ENTRY_CTLS,
445 	MSR_IA32_VMX_MISC,
446 	MSR_IA32_VMX_CR0_FIXED0,
447 	MSR_IA32_VMX_CR4_FIXED0,
448 	MSR_IA32_VMX_VMCS_ENUM,
449 	MSR_IA32_VMX_PROCBASED_CTLS2,
450 	MSR_IA32_VMX_EPT_VPID_CAP,
451 	MSR_IA32_VMX_VMFUNC,
452 
453 	MSR_K7_HWCR,
454 	MSR_KVM_POLL_CONTROL,
455 };
456 
457 static u32 emulated_msrs[ARRAY_SIZE(emulated_msrs_all)];
458 static unsigned num_emulated_msrs;
459 
460 /*
461  * List of MSRs that control the existence of MSR-based features, i.e. MSRs
462  * that are effectively CPUID leafs.  VMX MSRs are also included in the set of
463  * feature MSRs, but are handled separately to allow expedited lookups.
464  */
465 static const u32 msr_based_features_all_except_vmx[] = {
466 	MSR_AMD64_DE_CFG,
467 	MSR_IA32_UCODE_REV,
468 	MSR_IA32_ARCH_CAPABILITIES,
469 	MSR_IA32_PERF_CAPABILITIES,
470 	MSR_PLATFORM_INFO,
471 };
472 
473 static u32 msr_based_features[ARRAY_SIZE(msr_based_features_all_except_vmx) +
474 			      (KVM_LAST_EMULATED_VMX_MSR - KVM_FIRST_EMULATED_VMX_MSR + 1)];
475 static unsigned int num_msr_based_features;
476 
477 /*
478  * All feature MSRs except uCode revID, which tracks the currently loaded uCode
479  * patch, are immutable once the vCPU model is defined.
480  */
kvm_is_immutable_feature_msr(u32 msr)481 static bool kvm_is_immutable_feature_msr(u32 msr)
482 {
483 	int i;
484 
485 	if (msr >= KVM_FIRST_EMULATED_VMX_MSR && msr <= KVM_LAST_EMULATED_VMX_MSR)
486 		return true;
487 
488 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++) {
489 		if (msr == msr_based_features_all_except_vmx[i])
490 			return msr != MSR_IA32_UCODE_REV;
491 	}
492 
493 	return false;
494 }
495 
kvm_is_advertised_msr(u32 msr_index)496 static bool kvm_is_advertised_msr(u32 msr_index)
497 {
498 	unsigned int i;
499 
500 	for (i = 0; i < num_msrs_to_save; i++) {
501 		if (msrs_to_save[i] == msr_index)
502 			return true;
503 	}
504 
505 	for (i = 0; i < num_emulated_msrs; i++) {
506 		if (emulated_msrs[i] == msr_index)
507 			return true;
508 	}
509 
510 	return false;
511 }
512 
513 typedef int (*msr_access_t)(struct kvm_vcpu *vcpu, u32 index, u64 *data,
514 			    bool host_initiated);
515 
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)516 static __always_inline int kvm_do_msr_access(struct kvm_vcpu *vcpu, u32 msr,
517 					     u64 *data, bool host_initiated,
518 					     enum kvm_msr_access rw,
519 					     msr_access_t msr_access_fn)
520 {
521 	const char *op = rw == MSR_TYPE_W ? "wrmsr" : "rdmsr";
522 	int ret;
523 
524 	BUILD_BUG_ON(rw != MSR_TYPE_R && rw != MSR_TYPE_W);
525 
526 	/*
527 	 * Zero the data on read failures to avoid leaking stack data to the
528 	 * guest and/or userspace, e.g. if the failure is ignored below.
529 	 */
530 	ret = msr_access_fn(vcpu, msr, data, host_initiated);
531 	if (ret && rw == MSR_TYPE_R)
532 		*data = 0;
533 
534 	if (ret != KVM_MSR_RET_UNSUPPORTED)
535 		return ret;
536 
537 	/*
538 	 * Userspace is allowed to read MSRs, and write '0' to MSRs, that KVM
539 	 * advertises to userspace, even if an MSR isn't fully supported.
540 	 * Simply check that @data is '0', which covers both the write '0' case
541 	 * and all reads (in which case @data is zeroed on failure; see above).
542 	 */
543 	if (host_initiated && !*data && kvm_is_advertised_msr(msr))
544 		return 0;
545 
546 	if (!ignore_msrs) {
547 		kvm_debug_ratelimited("unhandled %s: 0x%x data 0x%llx\n",
548 				      op, msr, *data);
549 		return ret;
550 	}
551 
552 	if (report_ignored_msrs)
553 		kvm_pr_unimpl("ignored %s: 0x%x data 0x%llx\n", op, msr, *data);
554 
555 	return 0;
556 }
557 
kvm_alloc_emulator_cache(void)558 static struct kmem_cache *kvm_alloc_emulator_cache(void)
559 {
560 	unsigned int useroffset = offsetof(struct x86_emulate_ctxt, src);
561 	unsigned int size = sizeof(struct x86_emulate_ctxt);
562 
563 	return kmem_cache_create_usercopy("x86_emulator", size,
564 					  __alignof__(struct x86_emulate_ctxt),
565 					  SLAB_ACCOUNT, useroffset,
566 					  size - useroffset, NULL);
567 }
568 
569 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
570 
kvm_async_pf_hash_reset(struct kvm_vcpu * vcpu)571 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
572 {
573 	int i;
574 	for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
575 		vcpu->arch.apf.gfns[i] = ~0;
576 }
577 
kvm_on_user_return(struct user_return_notifier * urn)578 static void kvm_on_user_return(struct user_return_notifier *urn)
579 {
580 	unsigned slot;
581 	struct kvm_user_return_msrs *msrs
582 		= container_of(urn, struct kvm_user_return_msrs, urn);
583 	struct kvm_user_return_msr_values *values;
584 	unsigned long flags;
585 
586 	/*
587 	 * Disabling irqs at this point since the following code could be
588 	 * interrupted and executed through kvm_arch_disable_virtualization_cpu()
589 	 */
590 	local_irq_save(flags);
591 	if (msrs->registered) {
592 		msrs->registered = false;
593 		user_return_notifier_unregister(urn);
594 	}
595 	local_irq_restore(flags);
596 	for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
597 		values = &msrs->values[slot];
598 		if (values->host != values->curr) {
599 			wrmsrq(kvm_uret_msrs_list[slot], values->host);
600 			values->curr = values->host;
601 		}
602 	}
603 }
604 
kvm_probe_user_return_msr(u32 msr)605 static int kvm_probe_user_return_msr(u32 msr)
606 {
607 	u64 val;
608 	int ret;
609 
610 	preempt_disable();
611 	ret = rdmsrq_safe(msr, &val);
612 	if (ret)
613 		goto out;
614 	ret = wrmsrq_safe(msr, val);
615 out:
616 	preempt_enable();
617 	return ret;
618 }
619 
kvm_add_user_return_msr(u32 msr)620 int kvm_add_user_return_msr(u32 msr)
621 {
622 	BUG_ON(kvm_nr_uret_msrs >= KVM_MAX_NR_USER_RETURN_MSRS);
623 
624 	if (kvm_probe_user_return_msr(msr))
625 		return -1;
626 
627 	kvm_uret_msrs_list[kvm_nr_uret_msrs] = msr;
628 	return kvm_nr_uret_msrs++;
629 }
630 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_add_user_return_msr);
631 
kvm_find_user_return_msr(u32 msr)632 int kvm_find_user_return_msr(u32 msr)
633 {
634 	int i;
635 
636 	for (i = 0; i < kvm_nr_uret_msrs; ++i) {
637 		if (kvm_uret_msrs_list[i] == msr)
638 			return i;
639 	}
640 	return -1;
641 }
642 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_find_user_return_msr);
643 
kvm_user_return_msr_cpu_online(void)644 static void kvm_user_return_msr_cpu_online(void)
645 {
646 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
647 	u64 value;
648 	int i;
649 
650 	for (i = 0; i < kvm_nr_uret_msrs; ++i) {
651 		rdmsrq_safe(kvm_uret_msrs_list[i], &value);
652 		msrs->values[i].host = value;
653 		msrs->values[i].curr = value;
654 	}
655 }
656 
kvm_user_return_register_notifier(struct kvm_user_return_msrs * msrs)657 static void kvm_user_return_register_notifier(struct kvm_user_return_msrs *msrs)
658 {
659 	if (!msrs->registered) {
660 		msrs->urn.on_user_return = kvm_on_user_return;
661 		user_return_notifier_register(&msrs->urn);
662 		msrs->registered = true;
663 	}
664 }
665 
kvm_set_user_return_msr(unsigned slot,u64 value,u64 mask)666 int kvm_set_user_return_msr(unsigned slot, u64 value, u64 mask)
667 {
668 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
669 	int err;
670 
671 	value = (value & mask) | (msrs->values[slot].host & ~mask);
672 	if (value == msrs->values[slot].curr)
673 		return 0;
674 	err = wrmsrq_safe(kvm_uret_msrs_list[slot], value);
675 	if (err)
676 		return 1;
677 
678 	msrs->values[slot].curr = value;
679 	kvm_user_return_register_notifier(msrs);
680 	return 0;
681 }
682 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_user_return_msr);
683 
kvm_user_return_msr_update_cache(unsigned int slot,u64 value)684 void kvm_user_return_msr_update_cache(unsigned int slot, u64 value)
685 {
686 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
687 
688 	msrs->values[slot].curr = value;
689 	kvm_user_return_register_notifier(msrs);
690 }
691 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_user_return_msr_update_cache);
692 
kvm_get_user_return_msr(unsigned int slot)693 u64 kvm_get_user_return_msr(unsigned int slot)
694 {
695 	return this_cpu_ptr(user_return_msrs)->values[slot].curr;
696 }
697 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_user_return_msr);
698 
drop_user_return_notifiers(void)699 static void drop_user_return_notifiers(void)
700 {
701 	struct kvm_user_return_msrs *msrs = this_cpu_ptr(user_return_msrs);
702 
703 	if (msrs->registered)
704 		kvm_on_user_return(&msrs->urn);
705 }
706 
707 /*
708  * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
709  *
710  * Hardware virtualization extension instructions may fault if a reboot turns
711  * off virtualization while processes are running.  Usually after catching the
712  * fault we just panic; during reboot instead the instruction is ignored.
713  */
kvm_spurious_fault(void)714 noinstr void kvm_spurious_fault(void)
715 {
716 	/* Fault while not rebooting.  We want the trace. */
717 	BUG_ON(!kvm_rebooting);
718 }
719 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_spurious_fault);
720 
721 #define EXCPT_BENIGN		0
722 #define EXCPT_CONTRIBUTORY	1
723 #define EXCPT_PF		2
724 
exception_class(int vector)725 static int exception_class(int vector)
726 {
727 	switch (vector) {
728 	case PF_VECTOR:
729 		return EXCPT_PF;
730 	case DE_VECTOR:
731 	case TS_VECTOR:
732 	case NP_VECTOR:
733 	case SS_VECTOR:
734 	case GP_VECTOR:
735 		return EXCPT_CONTRIBUTORY;
736 	default:
737 		break;
738 	}
739 	return EXCPT_BENIGN;
740 }
741 
742 #define EXCPT_FAULT		0
743 #define EXCPT_TRAP		1
744 #define EXCPT_ABORT		2
745 #define EXCPT_INTERRUPT		3
746 #define EXCPT_DB		4
747 
exception_type(int vector)748 static int exception_type(int vector)
749 {
750 	unsigned int mask;
751 
752 	if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
753 		return EXCPT_INTERRUPT;
754 
755 	mask = 1 << vector;
756 
757 	/*
758 	 * #DBs can be trap-like or fault-like, the caller must check other CPU
759 	 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
760 	 */
761 	if (mask & (1 << DB_VECTOR))
762 		return EXCPT_DB;
763 
764 	if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
765 		return EXCPT_TRAP;
766 
767 	if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
768 		return EXCPT_ABORT;
769 
770 	/* Reserved exceptions will result in fault */
771 	return EXCPT_FAULT;
772 }
773 
kvm_deliver_exception_payload(struct kvm_vcpu * vcpu,struct kvm_queued_exception * ex)774 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
775 				   struct kvm_queued_exception *ex)
776 {
777 	if (!ex->has_payload)
778 		return;
779 
780 	switch (ex->vector) {
781 	case DB_VECTOR:
782 		/*
783 		 * "Certain debug exceptions may clear bit 0-3.  The
784 		 * remaining contents of the DR6 register are never
785 		 * cleared by the processor".
786 		 */
787 		vcpu->arch.dr6 &= ~DR_TRAP_BITS;
788 		/*
789 		 * In order to reflect the #DB exception payload in guest
790 		 * dr6, three components need to be considered: active low
791 		 * bit, FIXED_1 bits and active high bits (e.g. DR6_BD,
792 		 * DR6_BS and DR6_BT)
793 		 * DR6_ACTIVE_LOW contains the FIXED_1 and active low bits.
794 		 * In the target guest dr6:
795 		 * FIXED_1 bits should always be set.
796 		 * Active low bits should be cleared if 1-setting in payload.
797 		 * Active high bits should be set if 1-setting in payload.
798 		 *
799 		 * Note, the payload is compatible with the pending debug
800 		 * exceptions/exit qualification under VMX, that active_low bits
801 		 * are active high in payload.
802 		 * So they need to be flipped for DR6.
803 		 */
804 		vcpu->arch.dr6 |= DR6_ACTIVE_LOW;
805 		vcpu->arch.dr6 |= ex->payload;
806 		vcpu->arch.dr6 ^= ex->payload & DR6_ACTIVE_LOW;
807 
808 		/*
809 		 * The #DB payload is defined as compatible with the 'pending
810 		 * debug exceptions' field under VMX, not DR6. While bit 12 is
811 		 * defined in the 'pending debug exceptions' field (enabled
812 		 * breakpoint), it is reserved and must be zero in DR6.
813 		 */
814 		vcpu->arch.dr6 &= ~BIT(12);
815 		break;
816 	case PF_VECTOR:
817 		vcpu->arch.cr2 = ex->payload;
818 		break;
819 	}
820 
821 	ex->has_payload = false;
822 	ex->payload = 0;
823 }
824 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_deliver_exception_payload);
825 
kvm_queue_exception_vmexit(struct kvm_vcpu * vcpu,unsigned int vector,bool has_error_code,u32 error_code,bool has_payload,unsigned long payload)826 static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
827 				       bool has_error_code, u32 error_code,
828 				       bool has_payload, unsigned long payload)
829 {
830 	struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
831 
832 	ex->vector = vector;
833 	ex->injected = false;
834 	ex->pending = true;
835 	ex->has_error_code = has_error_code;
836 	ex->error_code = error_code;
837 	ex->has_payload = has_payload;
838 	ex->payload = payload;
839 }
840 
kvm_multiple_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error,u32 error_code,bool has_payload,unsigned long payload)841 static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
842 				   bool has_error, u32 error_code,
843 				   bool has_payload, unsigned long payload)
844 {
845 	u32 prev_nr;
846 	int class1, class2;
847 
848 	kvm_make_request(KVM_REQ_EVENT, vcpu);
849 
850 	/*
851 	 * If the exception is destined for L2, morph it to a VM-Exit if L1
852 	 * wants to intercept the exception.
853 	 */
854 	if (is_guest_mode(vcpu) &&
855 	    kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) {
856 		kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code,
857 					   has_payload, payload);
858 		return;
859 	}
860 
861 	if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
862 	queue:
863 		vcpu->arch.exception.pending = true;
864 		vcpu->arch.exception.injected = false;
865 
866 		vcpu->arch.exception.has_error_code = has_error;
867 		vcpu->arch.exception.vector = nr;
868 		vcpu->arch.exception.error_code = error_code;
869 		vcpu->arch.exception.has_payload = has_payload;
870 		vcpu->arch.exception.payload = payload;
871 		if (!is_guest_mode(vcpu))
872 			kvm_deliver_exception_payload(vcpu,
873 						      &vcpu->arch.exception);
874 		return;
875 	}
876 
877 	/* to check exception */
878 	prev_nr = vcpu->arch.exception.vector;
879 	if (prev_nr == DF_VECTOR) {
880 		/* triple fault -> shutdown */
881 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
882 		return;
883 	}
884 	class1 = exception_class(prev_nr);
885 	class2 = exception_class(nr);
886 	if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
887 	    (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
888 		/*
889 		 * Synthesize #DF.  Clear the previously injected or pending
890 		 * exception so as not to incorrectly trigger shutdown.
891 		 */
892 		vcpu->arch.exception.injected = false;
893 		vcpu->arch.exception.pending = false;
894 
895 		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
896 	} else {
897 		/* replace previous exception with a new one in a hope
898 		   that instruction re-execution will regenerate lost
899 		   exception */
900 		goto queue;
901 	}
902 }
903 
kvm_queue_exception(struct kvm_vcpu * vcpu,unsigned nr)904 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
905 {
906 	kvm_multiple_exception(vcpu, nr, false, 0, false, 0);
907 }
908 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception);
909 
910 
kvm_queue_exception_p(struct kvm_vcpu * vcpu,unsigned nr,unsigned long payload)911 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
912 			   unsigned long payload)
913 {
914 	kvm_multiple_exception(vcpu, nr, false, 0, true, payload);
915 }
916 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_p);
917 
kvm_queue_exception_e_p(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code,unsigned long payload)918 static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
919 				    u32 error_code, unsigned long payload)
920 {
921 	kvm_multiple_exception(vcpu, nr, true, error_code, true, payload);
922 }
923 
kvm_requeue_exception(struct kvm_vcpu * vcpu,unsigned int nr,bool has_error_code,u32 error_code)924 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
925 			   bool has_error_code, u32 error_code)
926 {
927 
928 	/*
929 	 * On VM-Entry, an exception can be pending if and only if event
930 	 * injection was blocked by nested_run_pending.  In that case, however,
931 	 * vcpu_enter_guest() requests an immediate exit, and the guest
932 	 * shouldn't proceed far enough to need reinjection.
933 	 */
934 	WARN_ON_ONCE(kvm_is_exception_pending(vcpu));
935 
936 	/*
937 	 * Do not check for interception when injecting an event for L2, as the
938 	 * exception was checked for intercept when it was original queued, and
939 	 * re-checking is incorrect if _L1_ injected the exception, in which
940 	 * case it's exempt from interception.
941 	 */
942 	kvm_make_request(KVM_REQ_EVENT, vcpu);
943 
944 	vcpu->arch.exception.injected = true;
945 	vcpu->arch.exception.has_error_code = has_error_code;
946 	vcpu->arch.exception.vector = nr;
947 	vcpu->arch.exception.error_code = error_code;
948 	vcpu->arch.exception.has_payload = false;
949 	vcpu->arch.exception.payload = 0;
950 }
951 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_requeue_exception);
952 
kvm_complete_insn_gp(struct kvm_vcpu * vcpu,int err)953 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
954 {
955 	if (err)
956 		kvm_inject_gp(vcpu, 0);
957 	else
958 		return kvm_skip_emulated_instruction(vcpu);
959 
960 	return 1;
961 }
962 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_complete_insn_gp);
963 
complete_emulated_insn_gp(struct kvm_vcpu * vcpu,int err)964 static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
965 {
966 	if (err) {
967 		kvm_inject_gp(vcpu, 0);
968 		return 1;
969 	}
970 
971 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
972 				       EMULTYPE_COMPLETE_USER_EXIT);
973 }
974 
kvm_inject_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)975 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
976 {
977 	++vcpu->stat.pf_guest;
978 
979 	/*
980 	 * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
981 	 * whether or not L1 wants to intercept "regular" #PF.
982 	 */
983 	if (is_guest_mode(vcpu) && fault->async_page_fault)
984 		kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
985 					   true, fault->error_code,
986 					   true, fault->address);
987 	else
988 		kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
989 					fault->address);
990 }
991 
kvm_inject_emulated_page_fault(struct kvm_vcpu * vcpu,struct x86_exception * fault)992 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
993 				    struct x86_exception *fault)
994 {
995 	struct kvm_mmu *fault_mmu;
996 	WARN_ON_ONCE(fault->vector != PF_VECTOR);
997 
998 	fault_mmu = fault->nested_page_fault ? vcpu->arch.mmu :
999 					       vcpu->arch.walk_mmu;
1000 
1001 	/*
1002 	 * Invalidate the TLB entry for the faulting address, if it exists,
1003 	 * else the access will fault indefinitely (and to emulate hardware).
1004 	 */
1005 	if ((fault->error_code & PFERR_PRESENT_MASK) &&
1006 	    !(fault->error_code & PFERR_RSVD_MASK))
1007 		kvm_mmu_invalidate_addr(vcpu, fault_mmu, fault->address,
1008 					KVM_MMU_ROOT_CURRENT);
1009 
1010 	fault_mmu->inject_page_fault(vcpu, fault);
1011 }
1012 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_emulated_page_fault);
1013 
kvm_inject_nmi(struct kvm_vcpu * vcpu)1014 void kvm_inject_nmi(struct kvm_vcpu *vcpu)
1015 {
1016 	atomic_inc(&vcpu->arch.nmi_queued);
1017 	kvm_make_request(KVM_REQ_NMI, vcpu);
1018 }
1019 
kvm_queue_exception_e(struct kvm_vcpu * vcpu,unsigned nr,u32 error_code)1020 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
1021 {
1022 	kvm_multiple_exception(vcpu, nr, true, error_code, false, 0);
1023 }
1024 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_queue_exception_e);
1025 
1026 /*
1027  * Checks if cpl <= required_cpl; if true, return true.  Otherwise queue
1028  * a #GP and return false.
1029  */
kvm_require_cpl(struct kvm_vcpu * vcpu,int required_cpl)1030 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
1031 {
1032 	if (kvm_x86_call(get_cpl)(vcpu) <= required_cpl)
1033 		return true;
1034 	kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
1035 	return false;
1036 }
1037 
kvm_require_dr(struct kvm_vcpu * vcpu,int dr)1038 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
1039 {
1040 	if ((dr != 4 && dr != 5) || !kvm_is_cr4_bit_set(vcpu, X86_CR4_DE))
1041 		return true;
1042 
1043 	kvm_queue_exception(vcpu, UD_VECTOR);
1044 	return false;
1045 }
1046 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_require_dr);
1047 
pdptr_rsvd_bits(struct kvm_vcpu * vcpu)1048 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
1049 {
1050 	return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
1051 }
1052 
1053 /*
1054  * Load the pae pdptrs.  Return 1 if they are all valid, 0 otherwise.
1055  */
load_pdptrs(struct kvm_vcpu * vcpu,unsigned long cr3)1056 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3)
1057 {
1058 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
1059 	gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
1060 	gpa_t real_gpa;
1061 	int i;
1062 	int ret;
1063 	u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
1064 
1065 	/*
1066 	 * If the MMU is nested, CR3 holds an L2 GPA and needs to be translated
1067 	 * to an L1 GPA.
1068 	 */
1069 	real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(pdpt_gfn),
1070 				     PFERR_USER_MASK | PFERR_WRITE_MASK, NULL);
1071 	if (real_gpa == INVALID_GPA)
1072 		return 0;
1073 
1074 	/* Note the offset, PDPTRs are 32 byte aligned when using PAE paging. */
1075 	ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
1076 				       cr3 & GENMASK(11, 5), sizeof(pdpte));
1077 	if (ret < 0)
1078 		return 0;
1079 
1080 	for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
1081 		if ((pdpte[i] & PT_PRESENT_MASK) &&
1082 		    (pdpte[i] & pdptr_rsvd_bits(vcpu))) {
1083 			return 0;
1084 		}
1085 	}
1086 
1087 	/*
1088 	 * Marking VCPU_EXREG_PDPTR dirty doesn't work for !tdp_enabled.
1089 	 * Shadow page roots need to be reconstructed instead.
1090 	 */
1091 	if (!tdp_enabled && memcmp(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs)))
1092 		kvm_mmu_free_roots(vcpu->kvm, mmu, KVM_MMU_ROOT_CURRENT);
1093 
1094 	memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
1095 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
1096 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
1097 	vcpu->arch.pdptrs_from_userspace = false;
1098 
1099 	return 1;
1100 }
1101 EXPORT_SYMBOL_FOR_KVM_INTERNAL(load_pdptrs);
1102 
kvm_is_valid_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1103 static bool kvm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1104 {
1105 #ifdef CONFIG_X86_64
1106 	if (cr0 & 0xffffffff00000000UL)
1107 		return false;
1108 #endif
1109 
1110 	if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
1111 		return false;
1112 
1113 	if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
1114 		return false;
1115 
1116 	return kvm_x86_call(is_valid_cr0)(vcpu, cr0);
1117 }
1118 
kvm_post_set_cr0(struct kvm_vcpu * vcpu,unsigned long old_cr0,unsigned long cr0)1119 void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0)
1120 {
1121 	/*
1122 	 * CR0.WP is incorporated into the MMU role, but only for non-nested,
1123 	 * indirect shadow MMUs.  If paging is disabled, no updates are needed
1124 	 * as there are no permission bits to emulate.  If TDP is enabled, the
1125 	 * MMU's metadata needs to be updated, e.g. so that emulating guest
1126 	 * translations does the right thing, but there's no need to unload the
1127 	 * root as CR0.WP doesn't affect SPTEs.
1128 	 */
1129 	if ((cr0 ^ old_cr0) == X86_CR0_WP) {
1130 		if (!(cr0 & X86_CR0_PG))
1131 			return;
1132 
1133 		if (tdp_enabled) {
1134 			kvm_init_mmu(vcpu);
1135 			return;
1136 		}
1137 	}
1138 
1139 	if ((cr0 ^ old_cr0) & X86_CR0_PG) {
1140 		kvm_clear_async_pf_completion_queue(vcpu);
1141 		kvm_async_pf_hash_reset(vcpu);
1142 
1143 		/*
1144 		 * Clearing CR0.PG is defined to flush the TLB from the guest's
1145 		 * perspective.
1146 		 */
1147 		if (!(cr0 & X86_CR0_PG))
1148 			kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1149 	}
1150 
1151 	if ((cr0 ^ old_cr0) & KVM_MMU_CR0_ROLE_BITS)
1152 		kvm_mmu_reset_context(vcpu);
1153 }
1154 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_post_set_cr0);
1155 
kvm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1156 int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1157 {
1158 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
1159 
1160 	if (!kvm_is_valid_cr0(vcpu, cr0))
1161 		return 1;
1162 
1163 	cr0 |= X86_CR0_ET;
1164 
1165 	/* Write to CR0 reserved bits are ignored, even on Intel. */
1166 	cr0 &= ~CR0_RESERVED_BITS;
1167 
1168 #ifdef CONFIG_X86_64
1169 	if ((vcpu->arch.efer & EFER_LME) && !is_paging(vcpu) &&
1170 	    (cr0 & X86_CR0_PG)) {
1171 		int cs_db, cs_l;
1172 
1173 		if (!is_pae(vcpu))
1174 			return 1;
1175 		kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
1176 		if (cs_l)
1177 			return 1;
1178 	}
1179 #endif
1180 	if (!(vcpu->arch.efer & EFER_LME) && (cr0 & X86_CR0_PG) &&
1181 	    is_pae(vcpu) && ((cr0 ^ old_cr0) & X86_CR0_PDPTR_BITS) &&
1182 	    !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1183 		return 1;
1184 
1185 	if (!(cr0 & X86_CR0_PG) &&
1186 	    (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
1187 		return 1;
1188 
1189 	if (!(cr0 & X86_CR0_WP) && kvm_is_cr4_bit_set(vcpu, X86_CR4_CET))
1190 		return 1;
1191 
1192 	kvm_x86_call(set_cr0)(vcpu, cr0);
1193 
1194 	kvm_post_set_cr0(vcpu, old_cr0, cr0);
1195 
1196 	return 0;
1197 }
1198 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr0);
1199 
kvm_lmsw(struct kvm_vcpu * vcpu,unsigned long msw)1200 void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
1201 {
1202 	(void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
1203 }
1204 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_lmsw);
1205 
kvm_load_guest_xsave_state(struct kvm_vcpu * vcpu)1206 void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu)
1207 {
1208 	if (vcpu->arch.guest_state_protected)
1209 		return;
1210 
1211 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1212 
1213 		if (vcpu->arch.xcr0 != kvm_host.xcr0)
1214 			xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
1215 
1216 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1217 		    vcpu->arch.ia32_xss != kvm_host.xss)
1218 			wrmsrq(MSR_IA32_XSS, vcpu->arch.ia32_xss);
1219 	}
1220 
1221 	if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1222 	    vcpu->arch.pkru != vcpu->arch.host_pkru &&
1223 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1224 	     kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE)))
1225 		wrpkru(vcpu->arch.pkru);
1226 }
1227 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_load_guest_xsave_state);
1228 
kvm_load_host_xsave_state(struct kvm_vcpu * vcpu)1229 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu)
1230 {
1231 	if (vcpu->arch.guest_state_protected)
1232 		return;
1233 
1234 	if (cpu_feature_enabled(X86_FEATURE_PKU) &&
1235 	    ((vcpu->arch.xcr0 & XFEATURE_MASK_PKRU) ||
1236 	     kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE))) {
1237 		vcpu->arch.pkru = rdpkru();
1238 		if (vcpu->arch.pkru != vcpu->arch.host_pkru)
1239 			wrpkru(vcpu->arch.host_pkru);
1240 	}
1241 
1242 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE)) {
1243 
1244 		if (vcpu->arch.xcr0 != kvm_host.xcr0)
1245 			xsetbv(XCR_XFEATURE_ENABLED_MASK, kvm_host.xcr0);
1246 
1247 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
1248 		    vcpu->arch.ia32_xss != kvm_host.xss)
1249 			wrmsrq(MSR_IA32_XSS, kvm_host.xss);
1250 	}
1251 
1252 }
1253 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_load_host_xsave_state);
1254 
1255 #ifdef CONFIG_X86_64
kvm_guest_supported_xfd(struct kvm_vcpu * vcpu)1256 static inline u64 kvm_guest_supported_xfd(struct kvm_vcpu *vcpu)
1257 {
1258 	return vcpu->arch.guest_supported_xcr0 & XFEATURE_MASK_USER_DYNAMIC;
1259 }
1260 #endif
1261 
__kvm_set_xcr(struct kvm_vcpu * vcpu,u32 index,u64 xcr)1262 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
1263 {
1264 	u64 xcr0 = xcr;
1265 	u64 old_xcr0 = vcpu->arch.xcr0;
1266 	u64 valid_bits;
1267 
1268 	/* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now  */
1269 	if (index != XCR_XFEATURE_ENABLED_MASK)
1270 		return 1;
1271 	if (!(xcr0 & XFEATURE_MASK_FP))
1272 		return 1;
1273 	if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
1274 		return 1;
1275 
1276 	/*
1277 	 * Do not allow the guest to set bits that we do not support
1278 	 * saving.  However, xcr0 bit 0 is always set, even if the
1279 	 * emulated CPU does not support XSAVE (see kvm_vcpu_reset()).
1280 	 */
1281 	valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
1282 	if (xcr0 & ~valid_bits)
1283 		return 1;
1284 
1285 	if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
1286 	    (!(xcr0 & XFEATURE_MASK_BNDCSR)))
1287 		return 1;
1288 
1289 	if (xcr0 & XFEATURE_MASK_AVX512) {
1290 		if (!(xcr0 & XFEATURE_MASK_YMM))
1291 			return 1;
1292 		if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
1293 			return 1;
1294 	}
1295 
1296 	if ((xcr0 & XFEATURE_MASK_XTILE) &&
1297 	    ((xcr0 & XFEATURE_MASK_XTILE) != XFEATURE_MASK_XTILE))
1298 		return 1;
1299 
1300 	vcpu->arch.xcr0 = xcr0;
1301 
1302 	if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
1303 		vcpu->arch.cpuid_dynamic_bits_dirty = true;
1304 	return 0;
1305 }
1306 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_set_xcr);
1307 
kvm_emulate_xsetbv(struct kvm_vcpu * vcpu)1308 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
1309 {
1310 	/* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
1311 	if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
1312 	    __kvm_set_xcr(vcpu, kvm_rcx_read(vcpu), kvm_read_edx_eax(vcpu))) {
1313 		kvm_inject_gp(vcpu, 0);
1314 		return 1;
1315 	}
1316 
1317 	return kvm_skip_emulated_instruction(vcpu);
1318 }
1319 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_xsetbv);
1320 
kvm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1321 static bool kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1322 {
1323 	return __kvm_is_valid_cr4(vcpu, cr4) &&
1324 	       kvm_x86_call(is_valid_cr4)(vcpu, cr4);
1325 }
1326 
kvm_post_set_cr4(struct kvm_vcpu * vcpu,unsigned long old_cr4,unsigned long cr4)1327 void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4)
1328 {
1329 	if ((cr4 ^ old_cr4) & KVM_MMU_CR4_ROLE_BITS)
1330 		kvm_mmu_reset_context(vcpu);
1331 
1332 	/*
1333 	 * If CR4.PCIDE is changed 0 -> 1, there is no need to flush the TLB
1334 	 * according to the SDM; however, stale prev_roots could be reused
1335 	 * incorrectly in the future after a MOV to CR3 with NOFLUSH=1, so we
1336 	 * free them all.  This is *not* a superset of KVM_REQ_TLB_FLUSH_GUEST
1337 	 * or KVM_REQ_TLB_FLUSH_CURRENT, because the hardware TLB is not flushed,
1338 	 * so fall through.
1339 	 */
1340 	if (!tdp_enabled &&
1341 	    (cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE))
1342 		kvm_mmu_unload(vcpu);
1343 
1344 	/*
1345 	 * The TLB has to be flushed for all PCIDs if any of the following
1346 	 * (architecturally required) changes happen:
1347 	 * - CR4.PCIDE is changed from 1 to 0
1348 	 * - CR4.PGE is toggled
1349 	 *
1350 	 * This is a superset of KVM_REQ_TLB_FLUSH_CURRENT.
1351 	 */
1352 	if (((cr4 ^ old_cr4) & X86_CR4_PGE) ||
1353 	    (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
1354 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1355 
1356 	/*
1357 	 * The TLB has to be flushed for the current PCID if any of the
1358 	 * following (architecturally required) changes happen:
1359 	 * - CR4.SMEP is changed from 0 to 1
1360 	 * - CR4.PAE is toggled
1361 	 */
1362 	else if (((cr4 ^ old_cr4) & X86_CR4_PAE) ||
1363 		 ((cr4 & X86_CR4_SMEP) && !(old_cr4 & X86_CR4_SMEP)))
1364 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1365 
1366 }
1367 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_post_set_cr4);
1368 
kvm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1369 int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1370 {
1371 	unsigned long old_cr4 = kvm_read_cr4(vcpu);
1372 
1373 	if (!kvm_is_valid_cr4(vcpu, cr4))
1374 		return 1;
1375 
1376 	if (is_long_mode(vcpu)) {
1377 		if (!(cr4 & X86_CR4_PAE))
1378 			return 1;
1379 		if ((cr4 ^ old_cr4) & X86_CR4_LA57)
1380 			return 1;
1381 	} else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
1382 		   && ((cr4 ^ old_cr4) & X86_CR4_PDPTR_BITS)
1383 		   && !load_pdptrs(vcpu, kvm_read_cr3(vcpu)))
1384 		return 1;
1385 
1386 	if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
1387 		/* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
1388 		if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
1389 			return 1;
1390 	}
1391 
1392 	if ((cr4 & X86_CR4_CET) && !kvm_is_cr0_bit_set(vcpu, X86_CR0_WP))
1393 		return 1;
1394 
1395 	kvm_x86_call(set_cr4)(vcpu, cr4);
1396 
1397 	kvm_post_set_cr4(vcpu, old_cr4, cr4);
1398 
1399 	return 0;
1400 }
1401 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr4);
1402 
kvm_invalidate_pcid(struct kvm_vcpu * vcpu,unsigned long pcid)1403 static void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
1404 {
1405 	struct kvm_mmu *mmu = vcpu->arch.mmu;
1406 	unsigned long roots_to_free = 0;
1407 	int i;
1408 
1409 	/*
1410 	 * MOV CR3 and INVPCID are usually not intercepted when using TDP, but
1411 	 * this is reachable when running EPT=1 and unrestricted_guest=0,  and
1412 	 * also via the emulator.  KVM's TDP page tables are not in the scope of
1413 	 * the invalidation, but the guest's TLB entries need to be flushed as
1414 	 * the CPU may have cached entries in its TLB for the target PCID.
1415 	 */
1416 	if (unlikely(tdp_enabled)) {
1417 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
1418 		return;
1419 	}
1420 
1421 	/*
1422 	 * If neither the current CR3 nor any of the prev_roots use the given
1423 	 * PCID, then nothing needs to be done here because a resync will
1424 	 * happen anyway before switching to any other CR3.
1425 	 */
1426 	if (kvm_get_active_pcid(vcpu) == pcid) {
1427 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1428 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1429 	}
1430 
1431 	/*
1432 	 * If PCID is disabled, there is no need to free prev_roots even if the
1433 	 * PCIDs for them are also 0, because MOV to CR3 always flushes the TLB
1434 	 * with PCIDE=0.
1435 	 */
1436 	if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE))
1437 		return;
1438 
1439 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
1440 		if (kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd) == pcid)
1441 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
1442 
1443 	kvm_mmu_free_roots(vcpu->kvm, mmu, roots_to_free);
1444 }
1445 
kvm_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)1446 int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1447 {
1448 	bool skip_tlb_flush = false;
1449 	unsigned long pcid = 0;
1450 #ifdef CONFIG_X86_64
1451 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)) {
1452 		skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
1453 		cr3 &= ~X86_CR3_PCID_NOFLUSH;
1454 		pcid = cr3 & X86_CR3_PCID_MASK;
1455 	}
1456 #endif
1457 
1458 	/* PDPTRs are always reloaded for PAE paging. */
1459 	if (cr3 == kvm_read_cr3(vcpu) && !is_pae_paging(vcpu))
1460 		goto handle_tlb_flush;
1461 
1462 	/*
1463 	 * Do not condition the GPA check on long mode, this helper is used to
1464 	 * stuff CR3, e.g. for RSM emulation, and there is no guarantee that
1465 	 * the current vCPU mode is accurate.
1466 	 */
1467 	if (!kvm_vcpu_is_legal_cr3(vcpu, cr3))
1468 		return 1;
1469 
1470 	if (is_pae_paging(vcpu) && !load_pdptrs(vcpu, cr3))
1471 		return 1;
1472 
1473 	if (cr3 != kvm_read_cr3(vcpu))
1474 		kvm_mmu_new_pgd(vcpu, cr3);
1475 
1476 	vcpu->arch.cr3 = cr3;
1477 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
1478 	/* Do not call post_set_cr3, we do not get here for confidential guests.  */
1479 
1480 handle_tlb_flush:
1481 	/*
1482 	 * A load of CR3 that flushes the TLB flushes only the current PCID,
1483 	 * even if PCID is disabled, in which case PCID=0 is flushed.  It's a
1484 	 * moot point in the end because _disabling_ PCID will flush all PCIDs,
1485 	 * and it's impossible to use a non-zero PCID when PCID is disabled,
1486 	 * i.e. only PCID=0 can be relevant.
1487 	 */
1488 	if (!skip_tlb_flush)
1489 		kvm_invalidate_pcid(vcpu, pcid);
1490 
1491 	return 0;
1492 }
1493 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr3);
1494 
kvm_set_cr8(struct kvm_vcpu * vcpu,unsigned long cr8)1495 int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
1496 {
1497 	if (cr8 & CR8_RESERVED_BITS)
1498 		return 1;
1499 	if (lapic_in_kernel(vcpu))
1500 		kvm_lapic_set_tpr(vcpu, cr8);
1501 	else
1502 		vcpu->arch.cr8 = cr8;
1503 	return 0;
1504 }
1505 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_cr8);
1506 
kvm_get_cr8(struct kvm_vcpu * vcpu)1507 unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
1508 {
1509 	if (lapic_in_kernel(vcpu))
1510 		return kvm_lapic_get_cr8(vcpu);
1511 	else
1512 		return vcpu->arch.cr8;
1513 }
1514 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_cr8);
1515 
kvm_update_dr0123(struct kvm_vcpu * vcpu)1516 static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
1517 {
1518 	int i;
1519 
1520 	if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
1521 		for (i = 0; i < KVM_NR_DB_REGS; i++)
1522 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
1523 	}
1524 }
1525 
kvm_update_dr7(struct kvm_vcpu * vcpu)1526 void kvm_update_dr7(struct kvm_vcpu *vcpu)
1527 {
1528 	unsigned long dr7;
1529 
1530 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
1531 		dr7 = vcpu->arch.guest_debug_dr7;
1532 	else
1533 		dr7 = vcpu->arch.dr7;
1534 	kvm_x86_call(set_dr7)(vcpu, dr7);
1535 	vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
1536 	if (dr7 & DR7_BP_EN_MASK)
1537 		vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
1538 }
1539 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_update_dr7);
1540 
kvm_dr6_fixed(struct kvm_vcpu * vcpu)1541 static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
1542 {
1543 	u64 fixed = DR6_FIXED_1;
1544 
1545 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_RTM))
1546 		fixed |= DR6_RTM;
1547 
1548 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1549 		fixed |= DR6_BUS_LOCK;
1550 	return fixed;
1551 }
1552 
kvm_set_dr(struct kvm_vcpu * vcpu,int dr,unsigned long val)1553 int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
1554 {
1555 	size_t size = ARRAY_SIZE(vcpu->arch.db);
1556 
1557 	switch (dr) {
1558 	case 0 ... 3:
1559 		vcpu->arch.db[array_index_nospec(dr, size)] = val;
1560 		if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
1561 			vcpu->arch.eff_db[dr] = val;
1562 		break;
1563 	case 4:
1564 	case 6:
1565 		if (!kvm_dr6_valid(val))
1566 			return 1; /* #GP */
1567 		vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
1568 		break;
1569 	case 5:
1570 	default: /* 7 */
1571 		if (!kvm_dr7_valid(val))
1572 			return 1; /* #GP */
1573 		vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
1574 		kvm_update_dr7(vcpu);
1575 		break;
1576 	}
1577 
1578 	return 0;
1579 }
1580 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_dr);
1581 
kvm_get_dr(struct kvm_vcpu * vcpu,int dr)1582 unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr)
1583 {
1584 	size_t size = ARRAY_SIZE(vcpu->arch.db);
1585 
1586 	switch (dr) {
1587 	case 0 ... 3:
1588 		return vcpu->arch.db[array_index_nospec(dr, size)];
1589 	case 4:
1590 	case 6:
1591 		return vcpu->arch.dr6;
1592 	case 5:
1593 	default: /* 7 */
1594 		return vcpu->arch.dr7;
1595 	}
1596 }
1597 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_dr);
1598 
kvm_emulate_rdpmc(struct kvm_vcpu * vcpu)1599 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu)
1600 {
1601 	u32 pmc = kvm_rcx_read(vcpu);
1602 	u64 data;
1603 
1604 	if (kvm_pmu_rdpmc(vcpu, pmc, &data)) {
1605 		kvm_inject_gp(vcpu, 0);
1606 		return 1;
1607 	}
1608 
1609 	kvm_rax_write(vcpu, (u32)data);
1610 	kvm_rdx_write(vcpu, data >> 32);
1611 	return kvm_skip_emulated_instruction(vcpu);
1612 }
1613 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdpmc);
1614 
1615 /*
1616  * Some IA32_ARCH_CAPABILITIES bits have dependencies on MSRs that KVM
1617  * does not yet virtualize. These include:
1618  *   10 - MISC_PACKAGE_CTRLS
1619  *   11 - ENERGY_FILTERING_CTL
1620  *   12 - DOITM
1621  *   18 - FB_CLEAR_CTRL
1622  *   21 - XAPIC_DISABLE_STATUS
1623  *   23 - OVERCLOCKING_STATUS
1624  */
1625 
1626 #define KVM_SUPPORTED_ARCH_CAP \
1627 	(ARCH_CAP_RDCL_NO | ARCH_CAP_IBRS_ALL | ARCH_CAP_RSBA | \
1628 	 ARCH_CAP_SKIP_VMENTRY_L1DFLUSH | ARCH_CAP_SSB_NO | ARCH_CAP_MDS_NO | \
1629 	 ARCH_CAP_PSCHANGE_MC_NO | ARCH_CAP_TSX_CTRL_MSR | ARCH_CAP_TAA_NO | \
1630 	 ARCH_CAP_SBDR_SSDP_NO | ARCH_CAP_FBSDP_NO | ARCH_CAP_PSDP_NO | \
1631 	 ARCH_CAP_FB_CLEAR | ARCH_CAP_RRSBA | ARCH_CAP_PBRSB_NO | ARCH_CAP_GDS_NO | \
1632 	 ARCH_CAP_RFDS_NO | ARCH_CAP_RFDS_CLEAR | ARCH_CAP_BHI_NO | ARCH_CAP_ITS_NO)
1633 
kvm_get_arch_capabilities(void)1634 static u64 kvm_get_arch_capabilities(void)
1635 {
1636 	u64 data = kvm_host.arch_capabilities & KVM_SUPPORTED_ARCH_CAP;
1637 
1638 	/*
1639 	 * If nx_huge_pages is enabled, KVM's shadow paging will ensure that
1640 	 * the nested hypervisor runs with NX huge pages.  If it is not,
1641 	 * L1 is anyway vulnerable to ITLB_MULTIHIT exploits from other
1642 	 * L1 guests, so it need not worry about its own (L2) guests.
1643 	 */
1644 	data |= ARCH_CAP_PSCHANGE_MC_NO;
1645 
1646 	/*
1647 	 * If we're doing cache flushes (either "always" or "cond")
1648 	 * we will do one whenever the guest does a vmlaunch/vmresume.
1649 	 * If an outer hypervisor is doing the cache flush for us
1650 	 * (ARCH_CAP_SKIP_VMENTRY_L1DFLUSH), we can safely pass that
1651 	 * capability to the guest too, and if EPT is disabled we're not
1652 	 * vulnerable.  Overall, only VMENTER_L1D_FLUSH_NEVER will
1653 	 * require a nested hypervisor to do a flush of its own.
1654 	 */
1655 	if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
1656 		data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
1657 
1658 	if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
1659 		data |= ARCH_CAP_RDCL_NO;
1660 	if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1661 		data |= ARCH_CAP_SSB_NO;
1662 	if (!boot_cpu_has_bug(X86_BUG_MDS))
1663 		data |= ARCH_CAP_MDS_NO;
1664 	if (!boot_cpu_has_bug(X86_BUG_RFDS))
1665 		data |= ARCH_CAP_RFDS_NO;
1666 	if (!boot_cpu_has_bug(X86_BUG_ITS))
1667 		data |= ARCH_CAP_ITS_NO;
1668 
1669 	if (!boot_cpu_has(X86_FEATURE_RTM)) {
1670 		/*
1671 		 * If RTM=0 because the kernel has disabled TSX, the host might
1672 		 * have TAA_NO or TSX_CTRL.  Clear TAA_NO (the guest sees RTM=0
1673 		 * and therefore knows that there cannot be TAA) but keep
1674 		 * TSX_CTRL: some buggy userspaces leave it set on tsx=on hosts,
1675 		 * and we want to allow migrating those guests to tsx=off hosts.
1676 		 */
1677 		data &= ~ARCH_CAP_TAA_NO;
1678 	} else if (!boot_cpu_has_bug(X86_BUG_TAA)) {
1679 		data |= ARCH_CAP_TAA_NO;
1680 	} else {
1681 		/*
1682 		 * Nothing to do here; we emulate TSX_CTRL if present on the
1683 		 * host so the guest can choose between disabling TSX or
1684 		 * using VERW to clear CPU buffers.
1685 		 */
1686 	}
1687 
1688 	if (!boot_cpu_has_bug(X86_BUG_GDS) || gds_ucode_mitigated())
1689 		data |= ARCH_CAP_GDS_NO;
1690 
1691 	return data;
1692 }
1693 
kvm_get_feature_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1694 static int kvm_get_feature_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1695 			       bool host_initiated)
1696 {
1697 	WARN_ON_ONCE(!host_initiated);
1698 
1699 	switch (index) {
1700 	case MSR_IA32_ARCH_CAPABILITIES:
1701 		*data = kvm_get_arch_capabilities();
1702 		break;
1703 	case MSR_IA32_PERF_CAPABILITIES:
1704 		*data = kvm_caps.supported_perf_cap;
1705 		break;
1706 	case MSR_PLATFORM_INFO:
1707 		*data = MSR_PLATFORM_INFO_CPUID_FAULT;
1708 		break;
1709 	case MSR_IA32_UCODE_REV:
1710 		rdmsrq_safe(index, data);
1711 		break;
1712 	default:
1713 		return kvm_x86_call(get_feature_msr)(index, data);
1714 	}
1715 	return 0;
1716 }
1717 
do_get_feature_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)1718 static int do_get_feature_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
1719 {
1720 	return kvm_do_msr_access(vcpu, index, data, true, MSR_TYPE_R,
1721 				 kvm_get_feature_msr);
1722 }
1723 
__kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1724 static bool __kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1725 {
1726 	if (efer & EFER_AUTOIBRS && !guest_cpu_cap_has(vcpu, X86_FEATURE_AUTOIBRS))
1727 		return false;
1728 
1729 	if (efer & EFER_FFXSR && !guest_cpu_cap_has(vcpu, X86_FEATURE_FXSR_OPT))
1730 		return false;
1731 
1732 	if (efer & EFER_SVME && !guest_cpu_cap_has(vcpu, X86_FEATURE_SVM))
1733 		return false;
1734 
1735 	if (efer & (EFER_LME | EFER_LMA) &&
1736 	    !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1737 		return false;
1738 
1739 	if (efer & EFER_NX && !guest_cpu_cap_has(vcpu, X86_FEATURE_NX))
1740 		return false;
1741 
1742 	return true;
1743 
1744 }
kvm_valid_efer(struct kvm_vcpu * vcpu,u64 efer)1745 bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
1746 {
1747 	if (efer & efer_reserved_bits)
1748 		return false;
1749 
1750 	return __kvm_valid_efer(vcpu, efer);
1751 }
1752 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_valid_efer);
1753 
set_efer(struct kvm_vcpu * vcpu,struct msr_data * msr_info)1754 static int set_efer(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1755 {
1756 	u64 old_efer = vcpu->arch.efer;
1757 	u64 efer = msr_info->data;
1758 	int r;
1759 
1760 	if (efer & efer_reserved_bits)
1761 		return 1;
1762 
1763 	if (!msr_info->host_initiated) {
1764 		if (!__kvm_valid_efer(vcpu, efer))
1765 			return 1;
1766 
1767 		if (is_paging(vcpu) &&
1768 		    (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
1769 			return 1;
1770 	}
1771 
1772 	efer &= ~EFER_LMA;
1773 	efer |= vcpu->arch.efer & EFER_LMA;
1774 
1775 	r = kvm_x86_call(set_efer)(vcpu, efer);
1776 	if (r) {
1777 		WARN_ON(r > 0);
1778 		return r;
1779 	}
1780 
1781 	if ((efer ^ old_efer) & KVM_MMU_EFER_ROLE_BITS)
1782 		kvm_mmu_reset_context(vcpu);
1783 
1784 	if (!static_cpu_has(X86_FEATURE_XSAVES) &&
1785 	    (efer & EFER_SVME))
1786 		kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1787 
1788 	return 0;
1789 }
1790 
kvm_enable_efer_bits(u64 mask)1791 void kvm_enable_efer_bits(u64 mask)
1792 {
1793        efer_reserved_bits &= ~mask;
1794 }
1795 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_enable_efer_bits);
1796 
kvm_msr_allowed(struct kvm_vcpu * vcpu,u32 index,u32 type)1797 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
1798 {
1799 	struct kvm_x86_msr_filter *msr_filter;
1800 	struct msr_bitmap_range *ranges;
1801 	struct kvm *kvm = vcpu->kvm;
1802 	bool allowed;
1803 	int idx;
1804 	u32 i;
1805 
1806 	/* x2APIC MSRs do not support filtering. */
1807 	if (index >= 0x800 && index <= 0x8ff)
1808 		return true;
1809 
1810 	idx = srcu_read_lock(&kvm->srcu);
1811 
1812 	msr_filter = srcu_dereference(kvm->arch.msr_filter, &kvm->srcu);
1813 	if (!msr_filter) {
1814 		allowed = true;
1815 		goto out;
1816 	}
1817 
1818 	allowed = msr_filter->default_allow;
1819 	ranges = msr_filter->ranges;
1820 
1821 	for (i = 0; i < msr_filter->count; i++) {
1822 		u32 start = ranges[i].base;
1823 		u32 end = start + ranges[i].nmsrs;
1824 		u32 flags = ranges[i].flags;
1825 		unsigned long *bitmap = ranges[i].bitmap;
1826 
1827 		if ((index >= start) && (index < end) && (flags & type)) {
1828 			allowed = test_bit(index - start, bitmap);
1829 			break;
1830 		}
1831 	}
1832 
1833 out:
1834 	srcu_read_unlock(&kvm->srcu, idx);
1835 
1836 	return allowed;
1837 }
1838 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_msr_allowed);
1839 
1840 /*
1841  * Write @data into the MSR specified by @index.  Select MSR specific fault
1842  * checks are bypassed if @host_initiated is %true.
1843  * Returns 0 on success, non-0 otherwise.
1844  * Assumes vcpu_load() was already called.
1845  */
__kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1846 static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
1847 			 bool host_initiated)
1848 {
1849 	struct msr_data msr;
1850 
1851 	switch (index) {
1852 	case MSR_FS_BASE:
1853 	case MSR_GS_BASE:
1854 	case MSR_KERNEL_GS_BASE:
1855 	case MSR_CSTAR:
1856 	case MSR_LSTAR:
1857 		if (is_noncanonical_msr_address(data, vcpu))
1858 			return 1;
1859 		break;
1860 	case MSR_IA32_SYSENTER_EIP:
1861 	case MSR_IA32_SYSENTER_ESP:
1862 		/*
1863 		 * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
1864 		 * non-canonical address is written on Intel but not on
1865 		 * AMD (which ignores the top 32-bits, because it does
1866 		 * not implement 64-bit SYSENTER).
1867 		 *
1868 		 * 64-bit code should hence be able to write a non-canonical
1869 		 * value on AMD.  Making the address canonical ensures that
1870 		 * vmentry does not fail on Intel after writing a non-canonical
1871 		 * value, and that something deterministic happens if the guest
1872 		 * invokes 64-bit SYSENTER.
1873 		 */
1874 		data = __canonical_address(data, max_host_virt_addr_bits());
1875 		break;
1876 	case MSR_TSC_AUX:
1877 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1878 			return 1;
1879 
1880 		if (!host_initiated &&
1881 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1882 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1883 			return 1;
1884 
1885 		/*
1886 		 * Per Intel's SDM, bits 63:32 are reserved, but AMD's APM has
1887 		 * incomplete and conflicting architectural behavior.  Current
1888 		 * AMD CPUs completely ignore bits 63:32, i.e. they aren't
1889 		 * reserved and always read as zeros.  Enforce Intel's reserved
1890 		 * bits check if the guest CPU is Intel compatible, otherwise
1891 		 * clear the bits.  This ensures cross-vendor migration will
1892 		 * provide consistent behavior for the guest.
1893 		 */
1894 		if (guest_cpuid_is_intel_compatible(vcpu) && (data >> 32) != 0)
1895 			return 1;
1896 
1897 		data = (u32)data;
1898 		break;
1899 	case MSR_IA32_U_CET:
1900 	case MSR_IA32_S_CET:
1901 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
1902 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT))
1903 			return KVM_MSR_RET_UNSUPPORTED;
1904 		if (!kvm_is_valid_u_s_cet(vcpu, data))
1905 			return 1;
1906 		break;
1907 	case MSR_KVM_INTERNAL_GUEST_SSP:
1908 		if (!host_initiated)
1909 			return 1;
1910 		fallthrough;
1911 		/*
1912 		 * Note that the MSR emulation here is flawed when a vCPU
1913 		 * doesn't support the Intel 64 architecture. The expected
1914 		 * architectural behavior in this case is that the upper 32
1915 		 * bits do not exist and should always read '0'. However,
1916 		 * because the actual hardware on which the virtual CPU is
1917 		 * running does support Intel 64, XRSTORS/XSAVES in the
1918 		 * guest could observe behavior that violates the
1919 		 * architecture. Intercepting XRSTORS/XSAVES for this
1920 		 * special case isn't deemed worthwhile.
1921 		 */
1922 	case MSR_IA32_PL0_SSP ... MSR_IA32_INT_SSP_TAB:
1923 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
1924 			return KVM_MSR_RET_UNSUPPORTED;
1925 		/*
1926 		 * MSR_IA32_INT_SSP_TAB is not present on processors that do
1927 		 * not support Intel 64 architecture.
1928 		 */
1929 		if (index == MSR_IA32_INT_SSP_TAB && !guest_cpu_cap_has(vcpu, X86_FEATURE_LM))
1930 			return KVM_MSR_RET_UNSUPPORTED;
1931 		if (is_noncanonical_msr_address(data, vcpu))
1932 			return 1;
1933 		/* All SSP MSRs except MSR_IA32_INT_SSP_TAB must be 4-byte aligned */
1934 		if (index != MSR_IA32_INT_SSP_TAB && !IS_ALIGNED(data, 4))
1935 			return 1;
1936 		break;
1937 	}
1938 
1939 	msr.data = data;
1940 	msr.index = index;
1941 	msr.host_initiated = host_initiated;
1942 
1943 	return kvm_x86_call(set_msr)(vcpu, &msr);
1944 }
1945 
_kvm_set_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1946 static int _kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1947 			bool host_initiated)
1948 {
1949 	return __kvm_set_msr(vcpu, index, *data, host_initiated);
1950 }
1951 
kvm_set_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 data,bool host_initiated)1952 static int kvm_set_msr_ignored_check(struct kvm_vcpu *vcpu,
1953 				     u32 index, u64 data, bool host_initiated)
1954 {
1955 	return kvm_do_msr_access(vcpu, index, &data, host_initiated, MSR_TYPE_W,
1956 				 _kvm_set_msr);
1957 }
1958 
1959 /*
1960  * Read the MSR specified by @index into @data.  Select MSR specific fault
1961  * checks are bypassed if @host_initiated is %true.
1962  * Returns 0 on success, non-0 otherwise.
1963  * Assumes vcpu_load() was already called.
1964  */
__kvm_get_msr(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)1965 static int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
1966 			 bool host_initiated)
1967 {
1968 	struct msr_data msr;
1969 	int ret;
1970 
1971 	switch (index) {
1972 	case MSR_TSC_AUX:
1973 		if (!kvm_is_supported_user_return_msr(MSR_TSC_AUX))
1974 			return 1;
1975 
1976 		if (!host_initiated &&
1977 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
1978 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID))
1979 			return 1;
1980 		break;
1981 	case MSR_IA32_U_CET:
1982 	case MSR_IA32_S_CET:
1983 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
1984 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT))
1985 			return KVM_MSR_RET_UNSUPPORTED;
1986 		break;
1987 	case MSR_KVM_INTERNAL_GUEST_SSP:
1988 		if (!host_initiated)
1989 			return 1;
1990 		fallthrough;
1991 	case MSR_IA32_PL0_SSP ... MSR_IA32_INT_SSP_TAB:
1992 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
1993 			return KVM_MSR_RET_UNSUPPORTED;
1994 		break;
1995 	}
1996 
1997 	msr.index = index;
1998 	msr.host_initiated = host_initiated;
1999 
2000 	ret = kvm_x86_call(get_msr)(vcpu, &msr);
2001 	if (!ret)
2002 		*data = msr.data;
2003 	return ret;
2004 }
2005 
kvm_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2006 int kvm_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2007 {
2008 	return __kvm_set_msr(vcpu, index, data, true);
2009 }
2010 
kvm_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2011 int kvm_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2012 {
2013 	return __kvm_get_msr(vcpu, index, data, true);
2014 }
2015 
kvm_get_msr_ignored_check(struct kvm_vcpu * vcpu,u32 index,u64 * data,bool host_initiated)2016 static int kvm_get_msr_ignored_check(struct kvm_vcpu *vcpu,
2017 				     u32 index, u64 *data, bool host_initiated)
2018 {
2019 	return kvm_do_msr_access(vcpu, index, data, host_initiated, MSR_TYPE_R,
2020 				 __kvm_get_msr);
2021 }
2022 
__kvm_emulate_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2023 int __kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2024 {
2025 	return kvm_get_msr_ignored_check(vcpu, index, data, false);
2026 }
2027 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_emulate_msr_read);
2028 
__kvm_emulate_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2029 int __kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2030 {
2031 	return kvm_set_msr_ignored_check(vcpu, index, data, false);
2032 }
2033 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_emulate_msr_write);
2034 
kvm_emulate_msr_read(struct kvm_vcpu * vcpu,u32 index,u64 * data)2035 int kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data)
2036 {
2037 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ))
2038 		return KVM_MSR_RET_FILTERED;
2039 
2040 	return __kvm_emulate_msr_read(vcpu, index, data);
2041 }
2042 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_read);
2043 
kvm_emulate_msr_write(struct kvm_vcpu * vcpu,u32 index,u64 data)2044 int kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data)
2045 {
2046 	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE))
2047 		return KVM_MSR_RET_FILTERED;
2048 
2049 	return __kvm_emulate_msr_write(vcpu, index, data);
2050 }
2051 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_write);
2052 
2053 
complete_userspace_rdmsr(struct kvm_vcpu * vcpu)2054 static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
2055 {
2056 	if (!vcpu->run->msr.error) {
2057 		kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
2058 		kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
2059 	}
2060 }
2061 
complete_emulated_msr_access(struct kvm_vcpu * vcpu)2062 static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
2063 {
2064 	return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
2065 }
2066 
complete_emulated_rdmsr(struct kvm_vcpu * vcpu)2067 static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
2068 {
2069 	complete_userspace_rdmsr(vcpu);
2070 	return complete_emulated_msr_access(vcpu);
2071 }
2072 
complete_fast_msr_access(struct kvm_vcpu * vcpu)2073 static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
2074 {
2075 	return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
2076 }
2077 
complete_fast_rdmsr(struct kvm_vcpu * vcpu)2078 static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
2079 {
2080 	complete_userspace_rdmsr(vcpu);
2081 	return complete_fast_msr_access(vcpu);
2082 }
2083 
complete_fast_rdmsr_imm(struct kvm_vcpu * vcpu)2084 static int complete_fast_rdmsr_imm(struct kvm_vcpu *vcpu)
2085 {
2086 	if (!vcpu->run->msr.error)
2087 		kvm_register_write(vcpu, vcpu->arch.cui_rdmsr_imm_reg,
2088 				   vcpu->run->msr.data);
2089 
2090 	return complete_fast_msr_access(vcpu);
2091 }
2092 
kvm_msr_reason(int r)2093 static u64 kvm_msr_reason(int r)
2094 {
2095 	switch (r) {
2096 	case KVM_MSR_RET_UNSUPPORTED:
2097 		return KVM_MSR_EXIT_REASON_UNKNOWN;
2098 	case KVM_MSR_RET_FILTERED:
2099 		return KVM_MSR_EXIT_REASON_FILTER;
2100 	default:
2101 		return KVM_MSR_EXIT_REASON_INVAL;
2102 	}
2103 }
2104 
kvm_msr_user_space(struct kvm_vcpu * vcpu,u32 index,u32 exit_reason,u64 data,int (* completion)(struct kvm_vcpu * vcpu),int r)2105 static int kvm_msr_user_space(struct kvm_vcpu *vcpu, u32 index,
2106 			      u32 exit_reason, u64 data,
2107 			      int (*completion)(struct kvm_vcpu *vcpu),
2108 			      int r)
2109 {
2110 	u64 msr_reason = kvm_msr_reason(r);
2111 
2112 	/* Check if the user wanted to know about this MSR fault */
2113 	if (!(vcpu->kvm->arch.user_space_msr_mask & msr_reason))
2114 		return 0;
2115 
2116 	vcpu->run->exit_reason = exit_reason;
2117 	vcpu->run->msr.error = 0;
2118 	memset(vcpu->run->msr.pad, 0, sizeof(vcpu->run->msr.pad));
2119 	vcpu->run->msr.reason = msr_reason;
2120 	vcpu->run->msr.index = index;
2121 	vcpu->run->msr.data = data;
2122 	vcpu->arch.complete_userspace_io = completion;
2123 
2124 	return 1;
2125 }
2126 
__kvm_emulate_rdmsr(struct kvm_vcpu * vcpu,u32 msr,int reg,int (* complete_rdmsr)(struct kvm_vcpu *))2127 static int __kvm_emulate_rdmsr(struct kvm_vcpu *vcpu, u32 msr, int reg,
2128 			       int (*complete_rdmsr)(struct kvm_vcpu *))
2129 {
2130 	u64 data;
2131 	int r;
2132 
2133 	r = kvm_emulate_msr_read(vcpu, msr, &data);
2134 
2135 	if (!r) {
2136 		trace_kvm_msr_read(msr, data);
2137 
2138 		if (reg < 0) {
2139 			kvm_rax_write(vcpu, data & -1u);
2140 			kvm_rdx_write(vcpu, (data >> 32) & -1u);
2141 		} else {
2142 			kvm_register_write(vcpu, reg, data);
2143 		}
2144 	} else {
2145 		/* MSR read failed? See if we should ask user space */
2146 		if (kvm_msr_user_space(vcpu, msr, KVM_EXIT_X86_RDMSR, 0,
2147 				       complete_rdmsr, r))
2148 			return 0;
2149 		trace_kvm_msr_read_ex(msr);
2150 	}
2151 
2152 	return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2153 }
2154 
kvm_emulate_rdmsr(struct kvm_vcpu * vcpu)2155 int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu)
2156 {
2157 	return __kvm_emulate_rdmsr(vcpu, kvm_rcx_read(vcpu), -1,
2158 				   complete_fast_rdmsr);
2159 }
2160 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdmsr);
2161 
kvm_emulate_rdmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2162 int kvm_emulate_rdmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2163 {
2164 	vcpu->arch.cui_rdmsr_imm_reg = reg;
2165 
2166 	return __kvm_emulate_rdmsr(vcpu, msr, reg, complete_fast_rdmsr_imm);
2167 }
2168 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_rdmsr_imm);
2169 
__kvm_emulate_wrmsr(struct kvm_vcpu * vcpu,u32 msr,u64 data)2170 static int __kvm_emulate_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2171 {
2172 	int r;
2173 
2174 	r = kvm_emulate_msr_write(vcpu, msr, data);
2175 	if (!r) {
2176 		trace_kvm_msr_write(msr, data);
2177 	} else {
2178 		/* MSR write failed? See if we should ask user space */
2179 		if (kvm_msr_user_space(vcpu, msr, KVM_EXIT_X86_WRMSR, data,
2180 				       complete_fast_msr_access, r))
2181 			return 0;
2182 		/* Signal all other negative errors to userspace */
2183 		if (r < 0)
2184 			return r;
2185 		trace_kvm_msr_write_ex(msr, data);
2186 	}
2187 
2188 	return kvm_x86_call(complete_emulated_msr)(vcpu, r);
2189 }
2190 
kvm_emulate_wrmsr(struct kvm_vcpu * vcpu)2191 int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu)
2192 {
2193 	return __kvm_emulate_wrmsr(vcpu, kvm_rcx_read(vcpu),
2194 				   kvm_read_edx_eax(vcpu));
2195 }
2196 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wrmsr);
2197 
kvm_emulate_wrmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2198 int kvm_emulate_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2199 {
2200 	return __kvm_emulate_wrmsr(vcpu, msr, kvm_register_read(vcpu, reg));
2201 }
2202 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wrmsr_imm);
2203 
kvm_emulate_as_nop(struct kvm_vcpu * vcpu)2204 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu)
2205 {
2206 	return kvm_skip_emulated_instruction(vcpu);
2207 }
2208 
kvm_emulate_invd(struct kvm_vcpu * vcpu)2209 int kvm_emulate_invd(struct kvm_vcpu *vcpu)
2210 {
2211 	/* Treat an INVD instruction as a NOP and just skip it. */
2212 	return kvm_emulate_as_nop(vcpu);
2213 }
2214 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_invd);
2215 
handle_fastpath_invd(struct kvm_vcpu * vcpu)2216 fastpath_t handle_fastpath_invd(struct kvm_vcpu *vcpu)
2217 {
2218 	if (!kvm_emulate_invd(vcpu))
2219 		return EXIT_FASTPATH_EXIT_USERSPACE;
2220 
2221 	return EXIT_FASTPATH_REENTER_GUEST;
2222 }
2223 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_invd);
2224 
kvm_handle_invalid_op(struct kvm_vcpu * vcpu)2225 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu)
2226 {
2227 	kvm_queue_exception(vcpu, UD_VECTOR);
2228 	return 1;
2229 }
2230 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invalid_op);
2231 
2232 
kvm_emulate_monitor_mwait(struct kvm_vcpu * vcpu,const char * insn)2233 static int kvm_emulate_monitor_mwait(struct kvm_vcpu *vcpu, const char *insn)
2234 {
2235 	bool enabled;
2236 
2237 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS))
2238 		goto emulate_as_nop;
2239 
2240 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
2241 		enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_MWAIT);
2242 	else
2243 		enabled = vcpu->arch.ia32_misc_enable_msr & MSR_IA32_MISC_ENABLE_MWAIT;
2244 
2245 	if (!enabled)
2246 		return kvm_handle_invalid_op(vcpu);
2247 
2248 emulate_as_nop:
2249 	pr_warn_once("%s instruction emulated as NOP!\n", insn);
2250 	return kvm_emulate_as_nop(vcpu);
2251 }
kvm_emulate_mwait(struct kvm_vcpu * vcpu)2252 int kvm_emulate_mwait(struct kvm_vcpu *vcpu)
2253 {
2254 	return kvm_emulate_monitor_mwait(vcpu, "MWAIT");
2255 }
2256 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_mwait);
2257 
kvm_emulate_monitor(struct kvm_vcpu * vcpu)2258 int kvm_emulate_monitor(struct kvm_vcpu *vcpu)
2259 {
2260 	return kvm_emulate_monitor_mwait(vcpu, "MONITOR");
2261 }
2262 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_monitor);
2263 
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu)2264 static inline bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu)
2265 {
2266 	xfer_to_guest_mode_prepare();
2267 
2268 	return READ_ONCE(vcpu->mode) == EXITING_GUEST_MODE ||
2269 	       kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending();
2270 }
2271 
__handle_fastpath_wrmsr(struct kvm_vcpu * vcpu,u32 msr,u64 data)2272 static fastpath_t __handle_fastpath_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2273 {
2274 	switch (msr) {
2275 	case APIC_BASE_MSR + (APIC_ICR >> 4):
2276 		if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic) ||
2277 		    kvm_x2apic_icr_write_fast(vcpu->arch.apic, data))
2278 			return EXIT_FASTPATH_NONE;
2279 		break;
2280 	case MSR_IA32_TSC_DEADLINE:
2281 		kvm_set_lapic_tscdeadline_msr(vcpu, data);
2282 		break;
2283 	default:
2284 		return EXIT_FASTPATH_NONE;
2285 	}
2286 
2287 	trace_kvm_msr_write(msr, data);
2288 
2289 	if (!kvm_skip_emulated_instruction(vcpu))
2290 		return EXIT_FASTPATH_EXIT_USERSPACE;
2291 
2292 	return EXIT_FASTPATH_REENTER_GUEST;
2293 }
2294 
handle_fastpath_wrmsr(struct kvm_vcpu * vcpu)2295 fastpath_t handle_fastpath_wrmsr(struct kvm_vcpu *vcpu)
2296 {
2297 	return __handle_fastpath_wrmsr(vcpu, kvm_rcx_read(vcpu),
2298 				       kvm_read_edx_eax(vcpu));
2299 }
2300 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr);
2301 
handle_fastpath_wrmsr_imm(struct kvm_vcpu * vcpu,u32 msr,int reg)2302 fastpath_t handle_fastpath_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
2303 {
2304 	return __handle_fastpath_wrmsr(vcpu, msr, kvm_register_read(vcpu, reg));
2305 }
2306 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr_imm);
2307 
2308 /*
2309  * Adapt set_msr() to msr_io()'s calling convention
2310  */
do_get_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2311 static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2312 {
2313 	return kvm_get_msr_ignored_check(vcpu, index, data, true);
2314 }
2315 
do_set_msr(struct kvm_vcpu * vcpu,unsigned index,u64 * data)2316 static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
2317 {
2318 	u64 val;
2319 
2320 	/*
2321 	 * Disallow writes to immutable feature MSRs after KVM_RUN.  KVM does
2322 	 * not support modifying the guest vCPU model on the fly, e.g. changing
2323 	 * the nVMX capabilities while L2 is running is nonsensical.  Allow
2324 	 * writes of the same value, e.g. to allow userspace to blindly stuff
2325 	 * all MSRs when emulating RESET.
2326 	 */
2327 	if (kvm_vcpu_has_run(vcpu) && kvm_is_immutable_feature_msr(index) &&
2328 	    (do_get_msr(vcpu, index, &val) || *data != val))
2329 		return -EINVAL;
2330 
2331 	return kvm_set_msr_ignored_check(vcpu, index, *data, true);
2332 }
2333 
2334 #ifdef CONFIG_X86_64
2335 struct pvclock_clock {
2336 	int vclock_mode;
2337 	u64 cycle_last;
2338 	u64 mask;
2339 	u32 mult;
2340 	u32 shift;
2341 	u64 base_cycles;
2342 	u64 offset;
2343 };
2344 
2345 struct pvclock_gtod_data {
2346 	seqcount_t	seq;
2347 
2348 	struct pvclock_clock clock; /* extract of a clocksource struct */
2349 	struct pvclock_clock raw_clock; /* extract of a clocksource struct */
2350 
2351 	ktime_t		offs_boot;
2352 	u64		wall_time_sec;
2353 };
2354 
2355 static struct pvclock_gtod_data pvclock_gtod_data;
2356 
update_pvclock_gtod(struct timekeeper * tk)2357 static void update_pvclock_gtod(struct timekeeper *tk)
2358 {
2359 	struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
2360 
2361 	write_seqcount_begin(&vdata->seq);
2362 
2363 	/* copy pvclock gtod data */
2364 	vdata->clock.vclock_mode	= tk->tkr_mono.clock->vdso_clock_mode;
2365 	vdata->clock.cycle_last		= tk->tkr_mono.cycle_last;
2366 	vdata->clock.mask		= tk->tkr_mono.mask;
2367 	vdata->clock.mult		= tk->tkr_mono.mult;
2368 	vdata->clock.shift		= tk->tkr_mono.shift;
2369 	vdata->clock.base_cycles	= tk->tkr_mono.xtime_nsec;
2370 	vdata->clock.offset		= tk->tkr_mono.base;
2371 
2372 	vdata->raw_clock.vclock_mode	= tk->tkr_raw.clock->vdso_clock_mode;
2373 	vdata->raw_clock.cycle_last	= tk->tkr_raw.cycle_last;
2374 	vdata->raw_clock.mask		= tk->tkr_raw.mask;
2375 	vdata->raw_clock.mult		= tk->tkr_raw.mult;
2376 	vdata->raw_clock.shift		= tk->tkr_raw.shift;
2377 	vdata->raw_clock.base_cycles	= tk->tkr_raw.xtime_nsec;
2378 	vdata->raw_clock.offset		= tk->tkr_raw.base;
2379 
2380 	vdata->wall_time_sec            = tk->xtime_sec;
2381 
2382 	vdata->offs_boot		= tk->offs_boot;
2383 
2384 	write_seqcount_end(&vdata->seq);
2385 }
2386 
get_kvmclock_base_ns(void)2387 static s64 get_kvmclock_base_ns(void)
2388 {
2389 	/* Count up from boot time, but with the frequency of the raw clock.  */
2390 	return ktime_to_ns(ktime_add(ktime_get_raw(), pvclock_gtod_data.offs_boot));
2391 }
2392 #else
get_kvmclock_base_ns(void)2393 static s64 get_kvmclock_base_ns(void)
2394 {
2395 	/* Master clock not used, so we can just use CLOCK_BOOTTIME.  */
2396 	return ktime_get_boottime_ns();
2397 }
2398 #endif
2399 
kvm_write_wall_clock(struct kvm * kvm,gpa_t wall_clock,int sec_hi_ofs)2400 static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock, int sec_hi_ofs)
2401 {
2402 	int version;
2403 	int r;
2404 	struct pvclock_wall_clock wc;
2405 	u32 wc_sec_hi;
2406 	u64 wall_nsec;
2407 
2408 	if (!wall_clock)
2409 		return;
2410 
2411 	r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
2412 	if (r)
2413 		return;
2414 
2415 	if (version & 1)
2416 		++version;  /* first time write, random junk */
2417 
2418 	++version;
2419 
2420 	if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
2421 		return;
2422 
2423 	wall_nsec = kvm_get_wall_clock_epoch(kvm);
2424 
2425 	wc.nsec = do_div(wall_nsec, NSEC_PER_SEC);
2426 	wc.sec = (u32)wall_nsec; /* overflow in 2106 guest time */
2427 	wc.version = version;
2428 
2429 	kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
2430 
2431 	if (sec_hi_ofs) {
2432 		wc_sec_hi = wall_nsec >> 32;
2433 		kvm_write_guest(kvm, wall_clock + sec_hi_ofs,
2434 				&wc_sec_hi, sizeof(wc_sec_hi));
2435 	}
2436 
2437 	version++;
2438 	kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
2439 }
2440 
kvm_write_system_time(struct kvm_vcpu * vcpu,gpa_t system_time,bool old_msr,bool host_initiated)2441 static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
2442 				  bool old_msr, bool host_initiated)
2443 {
2444 	struct kvm_arch *ka = &vcpu->kvm->arch;
2445 
2446 	if (vcpu->vcpu_id == 0 && !host_initiated) {
2447 		if (ka->boot_vcpu_runs_old_kvmclock != old_msr)
2448 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2449 
2450 		ka->boot_vcpu_runs_old_kvmclock = old_msr;
2451 	}
2452 
2453 	vcpu->arch.time = system_time;
2454 	kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
2455 
2456 	/* we verify if the enable bit is set... */
2457 	if (system_time & 1)
2458 		kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
2459 				 sizeof(struct pvclock_vcpu_time_info));
2460 	else
2461 		kvm_gpc_deactivate(&vcpu->arch.pv_time);
2462 
2463 	return;
2464 }
2465 
div_frac(uint32_t dividend,uint32_t divisor)2466 static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
2467 {
2468 	do_shl32_div32(dividend, divisor);
2469 	return dividend;
2470 }
2471 
kvm_get_time_scale(uint64_t scaled_hz,uint64_t base_hz,s8 * pshift,u32 * pmultiplier)2472 static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
2473 			       s8 *pshift, u32 *pmultiplier)
2474 {
2475 	uint64_t scaled64;
2476 	int32_t  shift = 0;
2477 	uint64_t tps64;
2478 	uint32_t tps32;
2479 
2480 	tps64 = base_hz;
2481 	scaled64 = scaled_hz;
2482 	while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
2483 		tps64 >>= 1;
2484 		shift--;
2485 	}
2486 
2487 	tps32 = (uint32_t)tps64;
2488 	while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
2489 		if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
2490 			scaled64 >>= 1;
2491 		else
2492 			tps32 <<= 1;
2493 		shift++;
2494 	}
2495 
2496 	*pshift = shift;
2497 	*pmultiplier = div_frac(scaled64, tps32);
2498 }
2499 
2500 #ifdef CONFIG_X86_64
2501 static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
2502 #endif
2503 
2504 static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
2505 static unsigned long max_tsc_khz;
2506 
adjust_tsc_khz(u32 khz,s32 ppm)2507 static u32 adjust_tsc_khz(u32 khz, s32 ppm)
2508 {
2509 	u64 v = (u64)khz * (1000000 + ppm);
2510 	do_div(v, 1000000);
2511 	return v;
2512 }
2513 
2514 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier);
2515 
set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz,bool scale)2516 static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
2517 {
2518 	u64 ratio;
2519 
2520 	/* Guest TSC same frequency as host TSC? */
2521 	if (!scale) {
2522 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2523 		return 0;
2524 	}
2525 
2526 	/* TSC scaling supported? */
2527 	if (!kvm_caps.has_tsc_control) {
2528 		if (user_tsc_khz > tsc_khz) {
2529 			vcpu->arch.tsc_catchup = 1;
2530 			vcpu->arch.tsc_always_catchup = 1;
2531 			return 0;
2532 		} else {
2533 			pr_warn_ratelimited("user requested TSC rate below hardware speed\n");
2534 			return -1;
2535 		}
2536 	}
2537 
2538 	/* TSC scaling required  - calculate ratio */
2539 	ratio = mul_u64_u32_div(1ULL << kvm_caps.tsc_scaling_ratio_frac_bits,
2540 				user_tsc_khz, tsc_khz);
2541 
2542 	if (ratio == 0 || ratio >= kvm_caps.max_tsc_scaling_ratio) {
2543 		pr_warn_ratelimited("Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
2544 			            user_tsc_khz);
2545 		return -1;
2546 	}
2547 
2548 	kvm_vcpu_write_tsc_multiplier(vcpu, ratio);
2549 	return 0;
2550 }
2551 
kvm_set_tsc_khz(struct kvm_vcpu * vcpu,u32 user_tsc_khz)2552 static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
2553 {
2554 	u32 thresh_lo, thresh_hi;
2555 	int use_scaling = 0;
2556 
2557 	/* tsc_khz can be zero if TSC calibration fails */
2558 	if (user_tsc_khz == 0) {
2559 		/* set tsc_scaling_ratio to a safe value */
2560 		kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio);
2561 		return -1;
2562 	}
2563 
2564 	/* Compute a scale to convert nanoseconds in TSC cycles */
2565 	kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
2566 			   &vcpu->arch.virtual_tsc_shift,
2567 			   &vcpu->arch.virtual_tsc_mult);
2568 	vcpu->arch.virtual_tsc_khz = user_tsc_khz;
2569 
2570 	/*
2571 	 * Compute the variation in TSC rate which is acceptable
2572 	 * within the range of tolerance and decide if the
2573 	 * rate being applied is within that bounds of the hardware
2574 	 * rate.  If so, no scaling or compensation need be done.
2575 	 */
2576 	thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
2577 	thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
2578 	if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
2579 		pr_debug("requested TSC rate %u falls outside tolerance [%u,%u]\n",
2580 			 user_tsc_khz, thresh_lo, thresh_hi);
2581 		use_scaling = 1;
2582 	}
2583 	return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
2584 }
2585 
compute_guest_tsc(struct kvm_vcpu * vcpu,s64 kernel_ns)2586 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
2587 {
2588 	u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
2589 				      vcpu->arch.virtual_tsc_mult,
2590 				      vcpu->arch.virtual_tsc_shift);
2591 	tsc += vcpu->arch.this_tsc_write;
2592 	return tsc;
2593 }
2594 
2595 #ifdef CONFIG_X86_64
gtod_is_based_on_tsc(int mode)2596 static inline bool gtod_is_based_on_tsc(int mode)
2597 {
2598 	return mode == VDSO_CLOCKMODE_TSC || mode == VDSO_CLOCKMODE_HVCLOCK;
2599 }
2600 #endif
2601 
kvm_track_tsc_matching(struct kvm_vcpu * vcpu,bool new_generation)2602 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generation)
2603 {
2604 #ifdef CONFIG_X86_64
2605 	struct kvm_arch *ka = &vcpu->kvm->arch;
2606 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2607 
2608 	/*
2609 	 * To use the masterclock, the host clocksource must be based on TSC
2610 	 * and all vCPUs must have matching TSCs.  Note, the count for matching
2611 	 * vCPUs doesn't include the reference vCPU, hence "+1".
2612 	 */
2613 	bool use_master_clock = (ka->nr_vcpus_matched_tsc + 1 ==
2614 				 atomic_read(&vcpu->kvm->online_vcpus)) &&
2615 				gtod_is_based_on_tsc(gtod->clock.vclock_mode);
2616 
2617 	/*
2618 	 * Request a masterclock update if the masterclock needs to be toggled
2619 	 * on/off, or when starting a new generation and the masterclock is
2620 	 * enabled (compute_guest_tsc() requires the masterclock snapshot to be
2621 	 * taken _after_ the new generation is created).
2622 	 */
2623 	if ((ka->use_master_clock && new_generation) ||
2624 	    (ka->use_master_clock != use_master_clock))
2625 		kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
2626 
2627 	trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
2628 			    atomic_read(&vcpu->kvm->online_vcpus),
2629 		            ka->use_master_clock, gtod->clock.vclock_mode);
2630 #endif
2631 }
2632 
2633 /*
2634  * Multiply tsc by a fixed point number represented by ratio.
2635  *
2636  * The most significant 64-N bits (mult) of ratio represent the
2637  * integral part of the fixed point number; the remaining N bits
2638  * (frac) represent the fractional part, ie. ratio represents a fixed
2639  * point number (mult + frac * 2^(-N)).
2640  *
2641  * N equals to kvm_caps.tsc_scaling_ratio_frac_bits.
2642  */
__scale_tsc(u64 ratio,u64 tsc)2643 static inline u64 __scale_tsc(u64 ratio, u64 tsc)
2644 {
2645 	return mul_u64_u64_shr(tsc, ratio, kvm_caps.tsc_scaling_ratio_frac_bits);
2646 }
2647 
kvm_scale_tsc(u64 tsc,u64 ratio)2648 u64 kvm_scale_tsc(u64 tsc, u64 ratio)
2649 {
2650 	u64 _tsc = tsc;
2651 
2652 	if (ratio != kvm_caps.default_tsc_scaling_ratio)
2653 		_tsc = __scale_tsc(ratio, tsc);
2654 
2655 	return _tsc;
2656 }
2657 
kvm_compute_l1_tsc_offset(struct kvm_vcpu * vcpu,u64 target_tsc)2658 static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
2659 {
2660 	u64 tsc;
2661 
2662 	tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio);
2663 
2664 	return target_tsc - tsc;
2665 }
2666 
kvm_read_l1_tsc(struct kvm_vcpu * vcpu,u64 host_tsc)2667 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
2668 {
2669 	return vcpu->arch.l1_tsc_offset +
2670 		kvm_scale_tsc(host_tsc, vcpu->arch.l1_tsc_scaling_ratio);
2671 }
2672 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_l1_tsc);
2673 
kvm_calc_nested_tsc_offset(u64 l1_offset,u64 l2_offset,u64 l2_multiplier)2674 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier)
2675 {
2676 	u64 nested_offset;
2677 
2678 	if (l2_multiplier == kvm_caps.default_tsc_scaling_ratio)
2679 		nested_offset = l1_offset;
2680 	else
2681 		nested_offset = mul_s64_u64_shr((s64) l1_offset, l2_multiplier,
2682 						kvm_caps.tsc_scaling_ratio_frac_bits);
2683 
2684 	nested_offset += l2_offset;
2685 	return nested_offset;
2686 }
2687 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_offset);
2688 
kvm_calc_nested_tsc_multiplier(u64 l1_multiplier,u64 l2_multiplier)2689 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
2690 {
2691 	if (l2_multiplier != kvm_caps.default_tsc_scaling_ratio)
2692 		return mul_u64_u64_shr(l1_multiplier, l2_multiplier,
2693 				       kvm_caps.tsc_scaling_ratio_frac_bits);
2694 
2695 	return l1_multiplier;
2696 }
2697 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_multiplier);
2698 
kvm_vcpu_write_tsc_offset(struct kvm_vcpu * vcpu,u64 l1_offset)2699 static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
2700 {
2701 	if (vcpu->arch.guest_tsc_protected)
2702 		return;
2703 
2704 	trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2705 				   vcpu->arch.l1_tsc_offset,
2706 				   l1_offset);
2707 
2708 	vcpu->arch.l1_tsc_offset = l1_offset;
2709 
2710 	/*
2711 	 * If we are here because L1 chose not to trap WRMSR to TSC then
2712 	 * according to the spec this should set L1's TSC (as opposed to
2713 	 * setting L1's offset for L2).
2714 	 */
2715 	if (is_guest_mode(vcpu))
2716 		vcpu->arch.tsc_offset = kvm_calc_nested_tsc_offset(
2717 			l1_offset,
2718 			kvm_x86_call(get_l2_tsc_offset)(vcpu),
2719 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2720 	else
2721 		vcpu->arch.tsc_offset = l1_offset;
2722 
2723 	kvm_x86_call(write_tsc_offset)(vcpu);
2724 }
2725 
kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu * vcpu,u64 l1_multiplier)2726 static void kvm_vcpu_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 l1_multiplier)
2727 {
2728 	vcpu->arch.l1_tsc_scaling_ratio = l1_multiplier;
2729 
2730 	/* Userspace is changing the multiplier while L2 is active */
2731 	if (is_guest_mode(vcpu))
2732 		vcpu->arch.tsc_scaling_ratio = kvm_calc_nested_tsc_multiplier(
2733 			l1_multiplier,
2734 			kvm_x86_call(get_l2_tsc_multiplier)(vcpu));
2735 	else
2736 		vcpu->arch.tsc_scaling_ratio = l1_multiplier;
2737 
2738 	if (kvm_caps.has_tsc_control)
2739 		kvm_x86_call(write_tsc_multiplier)(vcpu);
2740 }
2741 
kvm_check_tsc_unstable(void)2742 static inline bool kvm_check_tsc_unstable(void)
2743 {
2744 #ifdef CONFIG_X86_64
2745 	/*
2746 	 * TSC is marked unstable when we're running on Hyper-V,
2747 	 * 'TSC page' clocksource is good.
2748 	 */
2749 	if (pvclock_gtod_data.clock.vclock_mode == VDSO_CLOCKMODE_HVCLOCK)
2750 		return false;
2751 #endif
2752 	return check_tsc_unstable();
2753 }
2754 
2755 /*
2756  * Infers attempts to synchronize the guest's tsc from host writes. Sets the
2757  * offset for the vcpu and tracks the TSC matching generation that the vcpu
2758  * participates in.
2759  */
__kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 offset,u64 tsc,u64 ns,bool matched,bool user_set_tsc)2760 static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
2761 				  u64 ns, bool matched, bool user_set_tsc)
2762 {
2763 	struct kvm *kvm = vcpu->kvm;
2764 
2765 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
2766 
2767 	if (vcpu->arch.guest_tsc_protected)
2768 		return;
2769 
2770 	if (user_set_tsc)
2771 		vcpu->kvm->arch.user_set_tsc = true;
2772 
2773 	/*
2774 	 * We also track th most recent recorded KHZ, write and time to
2775 	 * allow the matching interval to be extended at each write.
2776 	 */
2777 	kvm->arch.last_tsc_nsec = ns;
2778 	kvm->arch.last_tsc_write = tsc;
2779 	kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
2780 	kvm->arch.last_tsc_offset = offset;
2781 
2782 	vcpu->arch.last_guest_tsc = tsc;
2783 
2784 	kvm_vcpu_write_tsc_offset(vcpu, offset);
2785 
2786 	if (!matched) {
2787 		/*
2788 		 * We split periods of matched TSC writes into generations.
2789 		 * For each generation, we track the original measured
2790 		 * nanosecond time, offset, and write, so if TSCs are in
2791 		 * sync, we can match exact offset, and if not, we can match
2792 		 * exact software computation in compute_guest_tsc()
2793 		 *
2794 		 * These values are tracked in kvm->arch.cur_xxx variables.
2795 		 */
2796 		kvm->arch.cur_tsc_generation++;
2797 		kvm->arch.cur_tsc_nsec = ns;
2798 		kvm->arch.cur_tsc_write = tsc;
2799 		kvm->arch.cur_tsc_offset = offset;
2800 		kvm->arch.nr_vcpus_matched_tsc = 0;
2801 	} else if (vcpu->arch.this_tsc_generation != kvm->arch.cur_tsc_generation) {
2802 		kvm->arch.nr_vcpus_matched_tsc++;
2803 	}
2804 
2805 	/* Keep track of which generation this VCPU has synchronized to */
2806 	vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
2807 	vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
2808 	vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
2809 
2810 	kvm_track_tsc_matching(vcpu, !matched);
2811 }
2812 
kvm_synchronize_tsc(struct kvm_vcpu * vcpu,u64 * user_value)2813 static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
2814 {
2815 	u64 data = user_value ? *user_value : 0;
2816 	struct kvm *kvm = vcpu->kvm;
2817 	u64 offset, ns, elapsed;
2818 	unsigned long flags;
2819 	bool matched = false;
2820 	bool synchronizing = false;
2821 
2822 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
2823 	offset = kvm_compute_l1_tsc_offset(vcpu, data);
2824 	ns = get_kvmclock_base_ns();
2825 	elapsed = ns - kvm->arch.last_tsc_nsec;
2826 
2827 	if (vcpu->arch.virtual_tsc_khz) {
2828 		if (data == 0) {
2829 			/*
2830 			 * Force synchronization when creating a vCPU, or when
2831 			 * userspace explicitly writes a zero value.
2832 			 */
2833 			synchronizing = true;
2834 		} else if (kvm->arch.user_set_tsc) {
2835 			u64 tsc_exp = kvm->arch.last_tsc_write +
2836 						nsec_to_cycles(vcpu, elapsed);
2837 			u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
2838 			/*
2839 			 * Here lies UAPI baggage: when a user-initiated TSC write has
2840 			 * a small delta (1 second) of virtual cycle time against the
2841 			 * previously set vCPU, we assume that they were intended to be
2842 			 * in sync and the delta was only due to the racy nature of the
2843 			 * legacy API.
2844 			 *
2845 			 * This trick falls down when restoring a guest which genuinely
2846 			 * has been running for less time than the 1 second of imprecision
2847 			 * which we allow for in the legacy API. In this case, the first
2848 			 * value written by userspace (on any vCPU) should not be subject
2849 			 * to this 'correction' to make it sync up with values that only
2850 			 * come from the kernel's default vCPU creation. Make the 1-second
2851 			 * slop hack only trigger if the user_set_tsc flag is already set.
2852 			 */
2853 			synchronizing = data < tsc_exp + tsc_hz &&
2854 					data + tsc_hz > tsc_exp;
2855 		}
2856 	}
2857 
2858 
2859 	/*
2860 	 * For a reliable TSC, we can match TSC offsets, and for an unstable
2861 	 * TSC, we add elapsed time in this computation.  We could let the
2862 	 * compensation code attempt to catch up if we fall behind, but
2863 	 * it's better to try to match offsets from the beginning.
2864          */
2865 	if (synchronizing &&
2866 	    vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
2867 		if (!kvm_check_tsc_unstable()) {
2868 			offset = kvm->arch.cur_tsc_offset;
2869 		} else {
2870 			u64 delta = nsec_to_cycles(vcpu, elapsed);
2871 			data += delta;
2872 			offset = kvm_compute_l1_tsc_offset(vcpu, data);
2873 		}
2874 		matched = true;
2875 	}
2876 
2877 	__kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value);
2878 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
2879 }
2880 
adjust_tsc_offset_guest(struct kvm_vcpu * vcpu,s64 adjustment)2881 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
2882 					   s64 adjustment)
2883 {
2884 	u64 tsc_offset = vcpu->arch.l1_tsc_offset;
2885 	kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
2886 }
2887 
adjust_tsc_offset_host(struct kvm_vcpu * vcpu,s64 adjustment)2888 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
2889 {
2890 	if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
2891 		WARN_ON(adjustment < 0);
2892 	adjustment = kvm_scale_tsc((u64) adjustment,
2893 				   vcpu->arch.l1_tsc_scaling_ratio);
2894 	adjust_tsc_offset_guest(vcpu, adjustment);
2895 }
2896 
2897 #ifdef CONFIG_X86_64
2898 
read_tsc(void)2899 static u64 read_tsc(void)
2900 {
2901 	u64 ret = (u64)rdtsc_ordered();
2902 	u64 last = pvclock_gtod_data.clock.cycle_last;
2903 
2904 	if (likely(ret >= last))
2905 		return ret;
2906 
2907 	/*
2908 	 * GCC likes to generate cmov here, but this branch is extremely
2909 	 * predictable (it's just a function of time and the likely is
2910 	 * very likely) and there's a data dependence, so force GCC
2911 	 * to generate a branch instead.  I don't barrier() because
2912 	 * we don't actually need a barrier, and if this function
2913 	 * ever gets inlined it will generate worse code.
2914 	 */
2915 	asm volatile ("");
2916 	return last;
2917 }
2918 
vgettsc(struct pvclock_clock * clock,u64 * tsc_timestamp,int * mode)2919 static inline u64 vgettsc(struct pvclock_clock *clock, u64 *tsc_timestamp,
2920 			  int *mode)
2921 {
2922 	u64 tsc_pg_val;
2923 	long v;
2924 
2925 	switch (clock->vclock_mode) {
2926 	case VDSO_CLOCKMODE_HVCLOCK:
2927 		if (hv_read_tsc_page_tsc(hv_get_tsc_page(),
2928 					 tsc_timestamp, &tsc_pg_val)) {
2929 			/* TSC page valid */
2930 			*mode = VDSO_CLOCKMODE_HVCLOCK;
2931 			v = (tsc_pg_val - clock->cycle_last) &
2932 				clock->mask;
2933 		} else {
2934 			/* TSC page invalid */
2935 			*mode = VDSO_CLOCKMODE_NONE;
2936 		}
2937 		break;
2938 	case VDSO_CLOCKMODE_TSC:
2939 		*mode = VDSO_CLOCKMODE_TSC;
2940 		*tsc_timestamp = read_tsc();
2941 		v = (*tsc_timestamp - clock->cycle_last) &
2942 			clock->mask;
2943 		break;
2944 	default:
2945 		*mode = VDSO_CLOCKMODE_NONE;
2946 	}
2947 
2948 	if (*mode == VDSO_CLOCKMODE_NONE)
2949 		*tsc_timestamp = v = 0;
2950 
2951 	return v * clock->mult;
2952 }
2953 
2954 /*
2955  * As with get_kvmclock_base_ns(), this counts from boot time, at the
2956  * frequency of CLOCK_MONOTONIC_RAW (hence adding gtos->offs_boot).
2957  */
do_kvmclock_base(s64 * t,u64 * tsc_timestamp)2958 static int do_kvmclock_base(s64 *t, u64 *tsc_timestamp)
2959 {
2960 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2961 	unsigned long seq;
2962 	int mode;
2963 	u64 ns;
2964 
2965 	do {
2966 		seq = read_seqcount_begin(&gtod->seq);
2967 		ns = gtod->raw_clock.base_cycles;
2968 		ns += vgettsc(&gtod->raw_clock, tsc_timestamp, &mode);
2969 		ns >>= gtod->raw_clock.shift;
2970 		ns += ktime_to_ns(ktime_add(gtod->raw_clock.offset, gtod->offs_boot));
2971 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2972 	*t = ns;
2973 
2974 	return mode;
2975 }
2976 
2977 /*
2978  * This calculates CLOCK_MONOTONIC at the time of the TSC snapshot, with
2979  * no boot time offset.
2980  */
do_monotonic(s64 * t,u64 * tsc_timestamp)2981 static int do_monotonic(s64 *t, u64 *tsc_timestamp)
2982 {
2983 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
2984 	unsigned long seq;
2985 	int mode;
2986 	u64 ns;
2987 
2988 	do {
2989 		seq = read_seqcount_begin(&gtod->seq);
2990 		ns = gtod->clock.base_cycles;
2991 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
2992 		ns >>= gtod->clock.shift;
2993 		ns += ktime_to_ns(gtod->clock.offset);
2994 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
2995 	*t = ns;
2996 
2997 	return mode;
2998 }
2999 
do_realtime(struct timespec64 * ts,u64 * tsc_timestamp)3000 static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
3001 {
3002 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
3003 	unsigned long seq;
3004 	int mode;
3005 	u64 ns;
3006 
3007 	do {
3008 		seq = read_seqcount_begin(&gtod->seq);
3009 		ts->tv_sec = gtod->wall_time_sec;
3010 		ns = gtod->clock.base_cycles;
3011 		ns += vgettsc(&gtod->clock, tsc_timestamp, &mode);
3012 		ns >>= gtod->clock.shift;
3013 	} while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
3014 
3015 	ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
3016 	ts->tv_nsec = ns;
3017 
3018 	return mode;
3019 }
3020 
3021 /*
3022  * Calculates the kvmclock_base_ns (CLOCK_MONOTONIC_RAW + boot time) and
3023  * reports the TSC value from which it do so. Returns true if host is
3024  * using TSC based clocksource.
3025  */
kvm_get_time_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)3026 static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
3027 {
3028 	/* checked again under seqlock below */
3029 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3030 		return false;
3031 
3032 	return gtod_is_based_on_tsc(do_kvmclock_base(kernel_ns,
3033 						     tsc_timestamp));
3034 }
3035 
3036 /*
3037  * Calculates CLOCK_MONOTONIC and reports the TSC value from which it did
3038  * so. Returns true if host is using TSC based clocksource.
3039  */
kvm_get_monotonic_and_clockread(s64 * kernel_ns,u64 * tsc_timestamp)3040 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
3041 {
3042 	/* checked again under seqlock below */
3043 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3044 		return false;
3045 
3046 	return gtod_is_based_on_tsc(do_monotonic(kernel_ns,
3047 						 tsc_timestamp));
3048 }
3049 
3050 /*
3051  * Calculates CLOCK_REALTIME and reports the TSC value from which it did
3052  * so. Returns true if host is using TSC based clocksource.
3053  *
3054  * DO NOT USE this for anything related to migration. You want CLOCK_TAI
3055  * for that.
3056  */
kvm_get_walltime_and_clockread(struct timespec64 * ts,u64 * tsc_timestamp)3057 static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
3058 					   u64 *tsc_timestamp)
3059 {
3060 	/* checked again under seqlock below */
3061 	if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
3062 		return false;
3063 
3064 	return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
3065 }
3066 #endif
3067 
3068 /*
3069  *
3070  * Assuming a stable TSC across physical CPUS, and a stable TSC
3071  * across virtual CPUs, the following condition is possible.
3072  * Each numbered line represents an event visible to both
3073  * CPUs at the next numbered event.
3074  *
3075  * "timespecX" represents host monotonic time. "tscX" represents
3076  * RDTSC value.
3077  *
3078  * 		VCPU0 on CPU0		|	VCPU1 on CPU1
3079  *
3080  * 1.  read timespec0,tsc0
3081  * 2.					| timespec1 = timespec0 + N
3082  * 					| tsc1 = tsc0 + M
3083  * 3. transition to guest		| transition to guest
3084  * 4. ret0 = timespec0 + (rdtsc - tsc0) |
3085  * 5.				        | ret1 = timespec1 + (rdtsc - tsc1)
3086  * 				        | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
3087  *
3088  * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
3089  *
3090  * 	- ret0 < ret1
3091  *	- timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
3092  *		...
3093  *	- 0 < N - M => M < N
3094  *
3095  * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
3096  * always the case (the difference between two distinct xtime instances
3097  * might be smaller then the difference between corresponding TSC reads,
3098  * when updating guest vcpus pvclock areas).
3099  *
3100  * To avoid that problem, do not allow visibility of distinct
3101  * system_timestamp/tsc_timestamp values simultaneously: use a master
3102  * copy of host monotonic time values. Update that master copy
3103  * in lockstep.
3104  *
3105  * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
3106  *
3107  */
3108 
pvclock_update_vm_gtod_copy(struct kvm * kvm)3109 static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
3110 {
3111 #ifdef CONFIG_X86_64
3112 	struct kvm_arch *ka = &kvm->arch;
3113 	int vclock_mode;
3114 	bool host_tsc_clocksource, vcpus_matched;
3115 
3116 	lockdep_assert_held(&kvm->arch.tsc_write_lock);
3117 	vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
3118 			atomic_read(&kvm->online_vcpus));
3119 
3120 	/*
3121 	 * If the host uses TSC clock, then passthrough TSC as stable
3122 	 * to the guest.
3123 	 */
3124 	host_tsc_clocksource = kvm_get_time_and_clockread(
3125 					&ka->master_kernel_ns,
3126 					&ka->master_cycle_now);
3127 
3128 	ka->use_master_clock = host_tsc_clocksource && vcpus_matched
3129 				&& !ka->backwards_tsc_observed
3130 				&& !ka->boot_vcpu_runs_old_kvmclock;
3131 
3132 	if (ka->use_master_clock)
3133 		atomic_set(&kvm_guest_has_master_clock, 1);
3134 
3135 	vclock_mode = pvclock_gtod_data.clock.vclock_mode;
3136 	trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
3137 					vcpus_matched);
3138 #endif
3139 }
3140 
kvm_make_mclock_inprogress_request(struct kvm * kvm)3141 static void kvm_make_mclock_inprogress_request(struct kvm *kvm)
3142 {
3143 	kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
3144 }
3145 
__kvm_start_pvclock_update(struct kvm * kvm)3146 static void __kvm_start_pvclock_update(struct kvm *kvm)
3147 {
3148 	raw_spin_lock_irq(&kvm->arch.tsc_write_lock);
3149 	write_seqcount_begin(&kvm->arch.pvclock_sc);
3150 }
3151 
kvm_start_pvclock_update(struct kvm * kvm)3152 static void kvm_start_pvclock_update(struct kvm *kvm)
3153 {
3154 	kvm_make_mclock_inprogress_request(kvm);
3155 
3156 	/* no guest entries from this point */
3157 	__kvm_start_pvclock_update(kvm);
3158 }
3159 
kvm_end_pvclock_update(struct kvm * kvm)3160 static void kvm_end_pvclock_update(struct kvm *kvm)
3161 {
3162 	struct kvm_arch *ka = &kvm->arch;
3163 	struct kvm_vcpu *vcpu;
3164 	unsigned long i;
3165 
3166 	write_seqcount_end(&ka->pvclock_sc);
3167 	raw_spin_unlock_irq(&ka->tsc_write_lock);
3168 	kvm_for_each_vcpu(i, vcpu, kvm)
3169 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3170 
3171 	/* guest entries allowed */
3172 	kvm_for_each_vcpu(i, vcpu, kvm)
3173 		kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
3174 }
3175 
kvm_update_masterclock(struct kvm * kvm)3176 static void kvm_update_masterclock(struct kvm *kvm)
3177 {
3178 	kvm_hv_request_tsc_page_update(kvm);
3179 	kvm_start_pvclock_update(kvm);
3180 	pvclock_update_vm_gtod_copy(kvm);
3181 	kvm_end_pvclock_update(kvm);
3182 }
3183 
3184 /*
3185  * Use the kernel's tsc_khz directly if the TSC is constant, otherwise use KVM's
3186  * per-CPU value (which may be zero if a CPU is going offline).  Note, tsc_khz
3187  * can change during boot even if the TSC is constant, as it's possible for KVM
3188  * to be loaded before TSC calibration completes.  Ideally, KVM would get a
3189  * notification when calibration completes, but practically speaking calibration
3190  * will complete before userspace is alive enough to create VMs.
3191  */
get_cpu_tsc_khz(void)3192 static unsigned long get_cpu_tsc_khz(void)
3193 {
3194 	if (static_cpu_has(X86_FEATURE_CONSTANT_TSC))
3195 		return tsc_khz;
3196 	else
3197 		return __this_cpu_read(cpu_tsc_khz);
3198 }
3199 
3200 /* Called within read_seqcount_begin/retry for kvm->pvclock_sc.  */
__get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3201 static void __get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3202 {
3203 	struct kvm_arch *ka = &kvm->arch;
3204 	struct pvclock_vcpu_time_info hv_clock;
3205 
3206 	/* both __this_cpu_read() and rdtsc() should be on the same cpu */
3207 	get_cpu();
3208 
3209 	data->flags = 0;
3210 	if (ka->use_master_clock &&
3211 	    (static_cpu_has(X86_FEATURE_CONSTANT_TSC) || __this_cpu_read(cpu_tsc_khz))) {
3212 #ifdef CONFIG_X86_64
3213 		struct timespec64 ts;
3214 
3215 		if (kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) {
3216 			data->realtime = ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec;
3217 			data->flags |= KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC;
3218 		} else
3219 #endif
3220 		data->host_tsc = rdtsc();
3221 
3222 		data->flags |= KVM_CLOCK_TSC_STABLE;
3223 		hv_clock.tsc_timestamp = ka->master_cycle_now;
3224 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3225 		kvm_get_time_scale(NSEC_PER_SEC, get_cpu_tsc_khz() * 1000LL,
3226 				   &hv_clock.tsc_shift,
3227 				   &hv_clock.tsc_to_system_mul);
3228 		data->clock = __pvclock_read_cycles(&hv_clock, data->host_tsc);
3229 	} else {
3230 		data->clock = get_kvmclock_base_ns() + ka->kvmclock_offset;
3231 	}
3232 
3233 	put_cpu();
3234 }
3235 
get_kvmclock(struct kvm * kvm,struct kvm_clock_data * data)3236 static void get_kvmclock(struct kvm *kvm, struct kvm_clock_data *data)
3237 {
3238 	struct kvm_arch *ka = &kvm->arch;
3239 	unsigned seq;
3240 
3241 	do {
3242 		seq = read_seqcount_begin(&ka->pvclock_sc);
3243 		__get_kvmclock(kvm, data);
3244 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3245 }
3246 
get_kvmclock_ns(struct kvm * kvm)3247 u64 get_kvmclock_ns(struct kvm *kvm)
3248 {
3249 	struct kvm_clock_data data;
3250 
3251 	get_kvmclock(kvm, &data);
3252 	return data.clock;
3253 }
3254 
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)3255 static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
3256 				    struct kvm_vcpu *vcpu,
3257 				    struct gfn_to_pfn_cache *gpc,
3258 				    unsigned int offset)
3259 {
3260 	struct pvclock_vcpu_time_info *guest_hv_clock;
3261 	struct pvclock_vcpu_time_info hv_clock;
3262 	unsigned long flags;
3263 
3264 	memcpy(&hv_clock, ref_hv_clock, sizeof(hv_clock));
3265 
3266 	read_lock_irqsave(&gpc->lock, flags);
3267 	while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
3268 		read_unlock_irqrestore(&gpc->lock, flags);
3269 
3270 		if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
3271 			return;
3272 
3273 		read_lock_irqsave(&gpc->lock, flags);
3274 	}
3275 
3276 	guest_hv_clock = (void *)(gpc->khva + offset);
3277 
3278 	/*
3279 	 * This VCPU is paused, but it's legal for a guest to read another
3280 	 * VCPU's kvmclock, so we really have to follow the specification where
3281 	 * it says that version is odd if data is being modified, and even after
3282 	 * it is consistent.
3283 	 */
3284 
3285 	guest_hv_clock->version = hv_clock.version = (guest_hv_clock->version + 1) | 1;
3286 	smp_wmb();
3287 
3288 	/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
3289 	hv_clock.flags |= (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
3290 
3291 	memcpy(guest_hv_clock, &hv_clock, sizeof(*guest_hv_clock));
3292 
3293 	smp_wmb();
3294 
3295 	guest_hv_clock->version = ++hv_clock.version;
3296 
3297 	kvm_gpc_mark_dirty_in_slot(gpc);
3298 	read_unlock_irqrestore(&gpc->lock, flags);
3299 
3300 	trace_kvm_pvclock_update(vcpu->vcpu_id, &hv_clock);
3301 }
3302 
kvm_guest_time_update(struct kvm_vcpu * v)3303 int kvm_guest_time_update(struct kvm_vcpu *v)
3304 {
3305 	struct pvclock_vcpu_time_info hv_clock = {};
3306 	unsigned long flags, tgt_tsc_khz;
3307 	unsigned seq;
3308 	struct kvm_vcpu_arch *vcpu = &v->arch;
3309 	struct kvm_arch *ka = &v->kvm->arch;
3310 	s64 kernel_ns;
3311 	u64 tsc_timestamp, host_tsc;
3312 	bool use_master_clock;
3313 
3314 	kernel_ns = 0;
3315 	host_tsc = 0;
3316 
3317 	/*
3318 	 * If the host uses TSC clock, then passthrough TSC as stable
3319 	 * to the guest.
3320 	 */
3321 	do {
3322 		seq = read_seqcount_begin(&ka->pvclock_sc);
3323 		use_master_clock = ka->use_master_clock;
3324 		if (use_master_clock) {
3325 			host_tsc = ka->master_cycle_now;
3326 			kernel_ns = ka->master_kernel_ns;
3327 		}
3328 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3329 
3330 	/* Keep irq disabled to prevent changes to the clock */
3331 	local_irq_save(flags);
3332 	tgt_tsc_khz = get_cpu_tsc_khz();
3333 	if (unlikely(tgt_tsc_khz == 0)) {
3334 		local_irq_restore(flags);
3335 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3336 		return 1;
3337 	}
3338 	if (!use_master_clock) {
3339 		host_tsc = rdtsc();
3340 		kernel_ns = get_kvmclock_base_ns();
3341 	}
3342 
3343 	tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
3344 
3345 	/*
3346 	 * We may have to catch up the TSC to match elapsed wall clock
3347 	 * time for two reasons, even if kvmclock is used.
3348 	 *   1) CPU could have been running below the maximum TSC rate
3349 	 *   2) Broken TSC compensation resets the base at each VCPU
3350 	 *      entry to avoid unknown leaps of TSC even when running
3351 	 *      again on the same CPU.  This may cause apparent elapsed
3352 	 *      time to disappear, and the guest to stand still or run
3353 	 *	very slowly.
3354 	 */
3355 	if (vcpu->tsc_catchup) {
3356 		u64 tsc = compute_guest_tsc(v, kernel_ns);
3357 		if (tsc > tsc_timestamp) {
3358 			adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
3359 			tsc_timestamp = tsc;
3360 		}
3361 	}
3362 
3363 	local_irq_restore(flags);
3364 
3365 	/* With all the info we got, fill in the values */
3366 
3367 	if (kvm_caps.has_tsc_control) {
3368 		tgt_tsc_khz = kvm_scale_tsc(tgt_tsc_khz,
3369 					    v->arch.l1_tsc_scaling_ratio);
3370 		tgt_tsc_khz = tgt_tsc_khz ? : 1;
3371 	}
3372 
3373 	if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
3374 		kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
3375 				   &vcpu->pvclock_tsc_shift,
3376 				   &vcpu->pvclock_tsc_mul);
3377 		vcpu->hw_tsc_khz = tgt_tsc_khz;
3378 	}
3379 
3380 	hv_clock.tsc_shift = vcpu->pvclock_tsc_shift;
3381 	hv_clock.tsc_to_system_mul = vcpu->pvclock_tsc_mul;
3382 	hv_clock.tsc_timestamp = tsc_timestamp;
3383 	hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
3384 	vcpu->last_guest_tsc = tsc_timestamp;
3385 
3386 	/* If the host uses TSC clocksource, then it is stable */
3387 	hv_clock.flags = 0;
3388 	if (use_master_clock)
3389 		hv_clock.flags |= PVCLOCK_TSC_STABLE_BIT;
3390 
3391 	if (vcpu->pv_time.active) {
3392 		/*
3393 		 * GUEST_STOPPED is only supported by kvmclock, and KVM's
3394 		 * historic behavior is to only process the request if kvmclock
3395 		 * is active/enabled.
3396 		 */
3397 		if (vcpu->pvclock_set_guest_stopped_request) {
3398 			hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
3399 			vcpu->pvclock_set_guest_stopped_request = false;
3400 		}
3401 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->pv_time, 0);
3402 
3403 		hv_clock.flags &= ~PVCLOCK_GUEST_STOPPED;
3404 	}
3405 
3406 	kvm_hv_setup_tsc_page(v->kvm, &hv_clock);
3407 
3408 #ifdef CONFIG_KVM_XEN
3409 	/*
3410 	 * For Xen guests we may need to override PVCLOCK_TSC_STABLE_BIT as unless
3411 	 * explicitly told to use TSC as its clocksource Xen will not set this bit.
3412 	 * This default behaviour led to bugs in some guest kernels which cause
3413 	 * problems if they observe PVCLOCK_TSC_STABLE_BIT in the pvclock flags.
3414 	 *
3415 	 * Note!  Clear TSC_STABLE only for Xen clocks, i.e. the order matters!
3416 	 */
3417 	if (ka->xen.hvm_config.flags & KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE)
3418 		hv_clock.flags &= ~PVCLOCK_TSC_STABLE_BIT;
3419 
3420 	if (vcpu->xen.vcpu_info_cache.active)
3421 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_info_cache,
3422 					offsetof(struct compat_vcpu_info, time));
3423 	if (vcpu->xen.vcpu_time_info_cache.active)
3424 		kvm_setup_guest_pvclock(&hv_clock, v, &vcpu->xen.vcpu_time_info_cache, 0);
3425 #endif
3426 	return 0;
3427 }
3428 
3429 /*
3430  * The pvclock_wall_clock ABI tells the guest the wall clock time at
3431  * which it started (i.e. its epoch, when its kvmclock was zero).
3432  *
3433  * In fact those clocks are subtly different; wall clock frequency is
3434  * adjusted by NTP and has leap seconds, while the kvmclock is a
3435  * simple function of the TSC without any such adjustment.
3436  *
3437  * Perhaps the ABI should have exposed CLOCK_TAI and a ratio between
3438  * that and kvmclock, but even that would be subject to change over
3439  * time.
3440  *
3441  * Attempt to calculate the epoch at a given moment using the *same*
3442  * TSC reading via kvm_get_walltime_and_clockread() to obtain both
3443  * wallclock and kvmclock times, and subtracting one from the other.
3444  *
3445  * Fall back to using their values at slightly different moments by
3446  * calling ktime_get_real_ns() and get_kvmclock_ns() separately.
3447  */
kvm_get_wall_clock_epoch(struct kvm * kvm)3448 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm)
3449 {
3450 #ifdef CONFIG_X86_64
3451 	struct pvclock_vcpu_time_info hv_clock;
3452 	struct kvm_arch *ka = &kvm->arch;
3453 	unsigned long seq, local_tsc_khz;
3454 	struct timespec64 ts;
3455 	uint64_t host_tsc;
3456 
3457 	do {
3458 		seq = read_seqcount_begin(&ka->pvclock_sc);
3459 
3460 		local_tsc_khz = 0;
3461 		if (!ka->use_master_clock)
3462 			break;
3463 
3464 		/*
3465 		 * The TSC read and the call to get_cpu_tsc_khz() must happen
3466 		 * on the same CPU.
3467 		 */
3468 		get_cpu();
3469 
3470 		local_tsc_khz = get_cpu_tsc_khz();
3471 
3472 		if (local_tsc_khz &&
3473 		    !kvm_get_walltime_and_clockread(&ts, &host_tsc))
3474 			local_tsc_khz = 0; /* Fall back to old method */
3475 
3476 		put_cpu();
3477 
3478 		/*
3479 		 * These values must be snapshotted within the seqcount loop.
3480 		 * After that, it's just mathematics which can happen on any
3481 		 * CPU at any time.
3482 		 */
3483 		hv_clock.tsc_timestamp = ka->master_cycle_now;
3484 		hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
3485 
3486 	} while (read_seqcount_retry(&ka->pvclock_sc, seq));
3487 
3488 	/*
3489 	 * If the conditions were right, and obtaining the wallclock+TSC was
3490 	 * successful, calculate the KVM clock at the corresponding time and
3491 	 * subtract one from the other to get the guest's epoch in nanoseconds
3492 	 * since 1970-01-01.
3493 	 */
3494 	if (local_tsc_khz) {
3495 		kvm_get_time_scale(NSEC_PER_SEC, local_tsc_khz * NSEC_PER_USEC,
3496 				   &hv_clock.tsc_shift,
3497 				   &hv_clock.tsc_to_system_mul);
3498 		return ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec -
3499 			__pvclock_read_cycles(&hv_clock, host_tsc);
3500 	}
3501 #endif
3502 	return ktime_get_real_ns() - get_kvmclock_ns(kvm);
3503 }
3504 
3505 /*
3506  * kvmclock updates which are isolated to a given vcpu, such as
3507  * vcpu->cpu migration, should not allow system_timestamp from
3508  * the rest of the vcpus to remain static. Otherwise ntp frequency
3509  * correction applies to one vcpu's system_timestamp but not
3510  * the others.
3511  *
3512  * So in those cases, request a kvmclock update for all vcpus.
3513  * We need to rate-limit these requests though, as they can
3514  * considerably slow guests that have a large number of vcpus.
3515  * The time for a remote vcpu to update its kvmclock is bound
3516  * by the delay we use to rate-limit the updates.
3517  */
3518 
3519 #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
3520 
kvmclock_update_fn(struct work_struct * work)3521 static void kvmclock_update_fn(struct work_struct *work)
3522 {
3523 	unsigned long i;
3524 	struct delayed_work *dwork = to_delayed_work(work);
3525 	struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3526 					   kvmclock_update_work);
3527 	struct kvm *kvm = container_of(ka, struct kvm, arch);
3528 	struct kvm_vcpu *vcpu;
3529 
3530 	kvm_for_each_vcpu(i, vcpu, kvm) {
3531 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
3532 		kvm_vcpu_kick(vcpu);
3533 	}
3534 }
3535 
kvm_gen_kvmclock_update(struct kvm_vcpu * v)3536 static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
3537 {
3538 	struct kvm *kvm = v->kvm;
3539 
3540 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
3541 	schedule_delayed_work(&kvm->arch.kvmclock_update_work,
3542 					KVMCLOCK_UPDATE_DELAY);
3543 }
3544 
3545 #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
3546 
kvmclock_sync_fn(struct work_struct * work)3547 static void kvmclock_sync_fn(struct work_struct *work)
3548 {
3549 	struct delayed_work *dwork = to_delayed_work(work);
3550 	struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
3551 					   kvmclock_sync_work);
3552 	struct kvm *kvm = container_of(ka, struct kvm, arch);
3553 
3554 	schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
3555 	schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
3556 					KVMCLOCK_SYNC_PERIOD);
3557 }
3558 
3559 /* These helpers are safe iff @msr is known to be an MCx bank MSR. */
is_mci_control_msr(u32 msr)3560 static bool is_mci_control_msr(u32 msr)
3561 {
3562 	return (msr & 3) == 0;
3563 }
is_mci_status_msr(u32 msr)3564 static bool is_mci_status_msr(u32 msr)
3565 {
3566 	return (msr & 3) == 1;
3567 }
3568 
3569 /*
3570  * On AMD, HWCR[McStatusWrEn] controls whether setting MCi_STATUS results in #GP.
3571  */
can_set_mci_status(struct kvm_vcpu * vcpu)3572 static bool can_set_mci_status(struct kvm_vcpu *vcpu)
3573 {
3574 	/* McStatusWrEn enabled? */
3575 	if (guest_cpuid_is_amd_compatible(vcpu))
3576 		return !!(vcpu->arch.msr_hwcr & BIT_ULL(18));
3577 
3578 	return false;
3579 }
3580 
set_msr_mce(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3581 static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3582 {
3583 	u64 mcg_cap = vcpu->arch.mcg_cap;
3584 	unsigned bank_num = mcg_cap & 0xff;
3585 	u32 msr = msr_info->index;
3586 	u64 data = msr_info->data;
3587 	u32 offset, last_msr;
3588 
3589 	switch (msr) {
3590 	case MSR_IA32_MCG_STATUS:
3591 		vcpu->arch.mcg_status = data;
3592 		break;
3593 	case MSR_IA32_MCG_CTL:
3594 		if (!(mcg_cap & MCG_CTL_P) &&
3595 		    (data || !msr_info->host_initiated))
3596 			return 1;
3597 		if (data != 0 && data != ~(u64)0)
3598 			return 1;
3599 		vcpu->arch.mcg_ctl = data;
3600 		break;
3601 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
3602 		last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
3603 		if (msr > last_msr)
3604 			return 1;
3605 
3606 		if (!(mcg_cap & MCG_CMCI_P) && (data || !msr_info->host_initiated))
3607 			return 1;
3608 		/* An attempt to write a 1 to a reserved bit raises #GP */
3609 		if (data & ~(MCI_CTL2_CMCI_EN | MCI_CTL2_CMCI_THRESHOLD_MASK))
3610 			return 1;
3611 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
3612 					    last_msr + 1 - MSR_IA32_MC0_CTL2);
3613 		vcpu->arch.mci_ctl2_banks[offset] = data;
3614 		break;
3615 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
3616 		last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
3617 		if (msr > last_msr)
3618 			return 1;
3619 
3620 		/*
3621 		 * Only 0 or all 1s can be written to IA32_MCi_CTL, all other
3622 		 * values are architecturally undefined.  But, some Linux
3623 		 * kernels clear bit 10 in bank 4 to workaround a BIOS/GART TLB
3624 		 * issue on AMD K8s, allow bit 10 to be clear when setting all
3625 		 * other bits in order to avoid an uncaught #GP in the guest.
3626 		 *
3627 		 * UNIXWARE clears bit 0 of MC1_CTL to ignore correctable,
3628 		 * single-bit ECC data errors.
3629 		 */
3630 		if (is_mci_control_msr(msr) &&
3631 		    data != 0 && (data | (1 << 10) | 1) != ~(u64)0)
3632 			return 1;
3633 
3634 		/*
3635 		 * All CPUs allow writing 0 to MCi_STATUS MSRs to clear the MSR.
3636 		 * AMD-based CPUs allow non-zero values, but if and only if
3637 		 * HWCR[McStatusWrEn] is set.
3638 		 */
3639 		if (!msr_info->host_initiated && is_mci_status_msr(msr) &&
3640 		    data != 0 && !can_set_mci_status(vcpu))
3641 			return 1;
3642 
3643 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
3644 					    last_msr + 1 - MSR_IA32_MC0_CTL);
3645 		vcpu->arch.mce_banks[offset] = data;
3646 		break;
3647 	default:
3648 		return 1;
3649 	}
3650 	return 0;
3651 }
3652 
kvm_pv_async_pf_enabled(struct kvm_vcpu * vcpu)3653 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
3654 {
3655 	u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
3656 
3657 	return (vcpu->arch.apf.msr_en_val & mask) == mask;
3658 }
3659 
kvm_pv_enable_async_pf(struct kvm_vcpu * vcpu,u64 data)3660 static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
3661 {
3662 	gpa_t gpa = data & ~0x3f;
3663 
3664 	/* Bits 4:5 are reserved, Should be zero */
3665 	if (data & 0x30)
3666 		return 1;
3667 
3668 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_VMEXIT) &&
3669 	    (data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT))
3670 		return 1;
3671 
3672 	if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT) &&
3673 	    (data & KVM_ASYNC_PF_DELIVERY_AS_INT))
3674 		return 1;
3675 
3676 	if (!lapic_in_kernel(vcpu))
3677 		return data ? 1 : 0;
3678 
3679 	vcpu->arch.apf.msr_en_val = data;
3680 
3681 	if (!kvm_pv_async_pf_enabled(vcpu)) {
3682 		kvm_clear_async_pf_completion_queue(vcpu);
3683 		kvm_async_pf_hash_reset(vcpu);
3684 		return 0;
3685 	}
3686 
3687 	if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
3688 					sizeof(u64)))
3689 		return 1;
3690 
3691 	vcpu->arch.apf.send_always = (data & KVM_ASYNC_PF_SEND_ALWAYS);
3692 	vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
3693 
3694 	kvm_async_pf_wakeup_all(vcpu);
3695 
3696 	return 0;
3697 }
3698 
kvm_pv_enable_async_pf_int(struct kvm_vcpu * vcpu,u64 data)3699 static int kvm_pv_enable_async_pf_int(struct kvm_vcpu *vcpu, u64 data)
3700 {
3701 	/* Bits 8-63 are reserved */
3702 	if (data >> 8)
3703 		return 1;
3704 
3705 	if (!lapic_in_kernel(vcpu))
3706 		return 1;
3707 
3708 	vcpu->arch.apf.msr_int_val = data;
3709 
3710 	vcpu->arch.apf.vec = data & KVM_ASYNC_PF_VEC_MASK;
3711 
3712 	return 0;
3713 }
3714 
kvmclock_reset(struct kvm_vcpu * vcpu)3715 static void kvmclock_reset(struct kvm_vcpu *vcpu)
3716 {
3717 	kvm_gpc_deactivate(&vcpu->arch.pv_time);
3718 	vcpu->arch.time = 0;
3719 }
3720 
kvm_vcpu_flush_tlb_all(struct kvm_vcpu * vcpu)3721 static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
3722 {
3723 	++vcpu->stat.tlb_flush;
3724 	kvm_x86_call(flush_tlb_all)(vcpu);
3725 
3726 	/* Flushing all ASIDs flushes the current ASID... */
3727 	kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3728 }
3729 
kvm_vcpu_flush_tlb_guest(struct kvm_vcpu * vcpu)3730 static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
3731 {
3732 	++vcpu->stat.tlb_flush;
3733 
3734 	if (!tdp_enabled) {
3735 		/*
3736 		 * A TLB flush on behalf of the guest is equivalent to
3737 		 * INVPCID(all), toggling CR4.PGE, etc., which requires
3738 		 * a forced sync of the shadow page tables.  Ensure all the
3739 		 * roots are synced and the guest TLB in hardware is clean.
3740 		 */
3741 		kvm_mmu_sync_roots(vcpu);
3742 		kvm_mmu_sync_prev_roots(vcpu);
3743 	}
3744 
3745 	kvm_x86_call(flush_tlb_guest)(vcpu);
3746 
3747 	/*
3748 	 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
3749 	 * grained flushing.
3750 	 */
3751 	kvm_hv_vcpu_purge_flush_tlb(vcpu);
3752 }
3753 
3754 
kvm_vcpu_flush_tlb_current(struct kvm_vcpu * vcpu)3755 static inline void kvm_vcpu_flush_tlb_current(struct kvm_vcpu *vcpu)
3756 {
3757 	++vcpu->stat.tlb_flush;
3758 	kvm_x86_call(flush_tlb_current)(vcpu);
3759 }
3760 
3761 /*
3762  * Service "local" TLB flush requests, which are specific to the current MMU
3763  * context.  In addition to the generic event handling in vcpu_enter_guest(),
3764  * TLB flushes that are targeted at an MMU context also need to be serviced
3765  * prior before nested VM-Enter/VM-Exit.
3766  */
kvm_service_local_tlb_flush_requests(struct kvm_vcpu * vcpu)3767 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
3768 {
3769 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu))
3770 		kvm_vcpu_flush_tlb_current(vcpu);
3771 
3772 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
3773 		kvm_vcpu_flush_tlb_guest(vcpu);
3774 }
3775 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_service_local_tlb_flush_requests);
3776 
record_steal_time(struct kvm_vcpu * vcpu)3777 static void record_steal_time(struct kvm_vcpu *vcpu)
3778 {
3779 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
3780 	struct kvm_steal_time __user *st;
3781 	struct kvm_memslots *slots;
3782 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
3783 	u64 steal;
3784 	u32 version;
3785 
3786 	if (kvm_xen_msr_enabled(vcpu->kvm)) {
3787 		kvm_xen_runstate_set_running(vcpu);
3788 		return;
3789 	}
3790 
3791 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
3792 		return;
3793 
3794 	if (WARN_ON_ONCE(current->mm != vcpu->kvm->mm))
3795 		return;
3796 
3797 	slots = kvm_memslots(vcpu->kvm);
3798 
3799 	if (unlikely(slots->generation != ghc->generation ||
3800 		     gpa != ghc->gpa ||
3801 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot)) {
3802 		/* We rely on the fact that it fits in a single page. */
3803 		BUILD_BUG_ON((sizeof(*st) - 1) & KVM_STEAL_VALID_BITS);
3804 
3805 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, gpa, sizeof(*st)) ||
3806 		    kvm_is_error_hva(ghc->hva) || !ghc->memslot)
3807 			return;
3808 	}
3809 
3810 	st = (struct kvm_steal_time __user *)ghc->hva;
3811 	/*
3812 	 * Doing a TLB flush here, on the guest's behalf, can avoid
3813 	 * expensive IPIs.
3814 	 */
3815 	if (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {
3816 		u8 st_preempted = 0;
3817 		int err = -EFAULT;
3818 
3819 		if (!user_access_begin(st, sizeof(*st)))
3820 			return;
3821 
3822 		asm volatile("1: xchgb %0, %2\n"
3823 			     "xor %1, %1\n"
3824 			     "2:\n"
3825 			     _ASM_EXTABLE_UA(1b, 2b)
3826 			     : "+q" (st_preempted),
3827 			       "+&r" (err),
3828 			       "+m" (st->preempted));
3829 		if (err)
3830 			goto out;
3831 
3832 		user_access_end();
3833 
3834 		vcpu->arch.st.preempted = 0;
3835 
3836 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
3837 				       st_preempted & KVM_VCPU_FLUSH_TLB);
3838 		if (st_preempted & KVM_VCPU_FLUSH_TLB)
3839 			kvm_vcpu_flush_tlb_guest(vcpu);
3840 
3841 		if (!user_access_begin(st, sizeof(*st)))
3842 			goto dirty;
3843 	} else {
3844 		if (!user_access_begin(st, sizeof(*st)))
3845 			return;
3846 
3847 		unsafe_put_user(0, &st->preempted, out);
3848 		vcpu->arch.st.preempted = 0;
3849 	}
3850 
3851 	unsafe_get_user(version, &st->version, out);
3852 	if (version & 1)
3853 		version += 1;  /* first time write, random junk */
3854 
3855 	version += 1;
3856 	unsafe_put_user(version, &st->version, out);
3857 
3858 	smp_wmb();
3859 
3860 	unsafe_get_user(steal, &st->steal, out);
3861 	steal += current->sched_info.run_delay -
3862 		vcpu->arch.st.last_steal;
3863 	vcpu->arch.st.last_steal = current->sched_info.run_delay;
3864 	unsafe_put_user(steal, &st->steal, out);
3865 
3866 	version += 1;
3867 	unsafe_put_user(version, &st->version, out);
3868 
3869  out:
3870 	user_access_end();
3871  dirty:
3872 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
3873 }
3874 
3875 /*
3876  * Returns true if the MSR in question is managed via XSTATE, i.e. is context
3877  * switched with the rest of guest FPU state.
3878  *
3879  * Note, S_CET is _not_ saved/restored via XSAVES/XRSTORS.
3880  */
is_xstate_managed_msr(struct kvm_vcpu * vcpu,u32 msr)3881 static bool is_xstate_managed_msr(struct kvm_vcpu *vcpu, u32 msr)
3882 {
3883 	if (!vcpu)
3884 		return false;
3885 
3886 	switch (msr) {
3887 	case MSR_IA32_U_CET:
3888 		return guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) ||
3889 		       guest_cpu_cap_has(vcpu, X86_FEATURE_IBT);
3890 	case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
3891 		return guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK);
3892 	default:
3893 		return false;
3894 	}
3895 }
3896 
3897 /*
3898  * Lock (and if necessary, re-load) the guest FPU, i.e. XSTATE, and access an
3899  * MSR that is managed via XSTATE.  Note, the caller is responsible for doing
3900  * the initial FPU load, this helper only ensures that guest state is resident
3901  * in hardware (the kernel can load its FPU state in IRQ context).
3902  *
3903  * Note, loading guest values for U_CET and PL[0-3]_SSP while executing in the
3904  * kernel is safe, as U_CET is specific to userspace, and PL[0-3]_SSP are only
3905  * consumed when transitioning to lower privilege levels, i.e. are effectively
3906  * only consumed by userspace as well.
3907  */
kvm_access_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info,int access)3908 static __always_inline void kvm_access_xstate_msr(struct kvm_vcpu *vcpu,
3909 						  struct msr_data *msr_info,
3910 						  int access)
3911 {
3912 	BUILD_BUG_ON(access != MSR_TYPE_R && access != MSR_TYPE_W);
3913 
3914 	KVM_BUG_ON(!is_xstate_managed_msr(vcpu, msr_info->index), vcpu->kvm);
3915 	KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm);
3916 
3917 	kvm_fpu_get();
3918 	if (access == MSR_TYPE_R)
3919 		rdmsrq(msr_info->index, msr_info->data);
3920 	else
3921 		wrmsrq(msr_info->index, msr_info->data);
3922 	kvm_fpu_put();
3923 }
3924 
kvm_set_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3925 static void kvm_set_xstate_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3926 {
3927 	kvm_access_xstate_msr(vcpu, msr_info, MSR_TYPE_W);
3928 }
3929 
kvm_get_xstate_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3930 static void kvm_get_xstate_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3931 {
3932 	kvm_access_xstate_msr(vcpu, msr_info, MSR_TYPE_R);
3933 }
3934 
kvm_set_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)3935 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3936 {
3937 	u32 msr = msr_info->index;
3938 	u64 data = msr_info->data;
3939 
3940 	/*
3941 	 * Do not allow host-initiated writes to trigger the Xen hypercall
3942 	 * page setup; it could incur locking paths which are not expected
3943 	 * if userspace sets the MSR in an unusual location.
3944 	 */
3945 	if (kvm_xen_is_hypercall_page_msr(vcpu->kvm, msr) &&
3946 	    !msr_info->host_initiated)
3947 		return kvm_xen_write_hypercall_page(vcpu, data);
3948 
3949 	switch (msr) {
3950 	case MSR_AMD64_NB_CFG:
3951 	case MSR_IA32_UCODE_WRITE:
3952 	case MSR_VM_HSAVE_PA:
3953 	case MSR_AMD64_PATCH_LOADER:
3954 	case MSR_AMD64_BU_CFG2:
3955 	case MSR_AMD64_DC_CFG:
3956 	case MSR_AMD64_TW_CFG:
3957 	case MSR_F15H_EX_CFG:
3958 		break;
3959 
3960 	case MSR_IA32_UCODE_REV:
3961 		if (msr_info->host_initiated)
3962 			vcpu->arch.microcode_version = data;
3963 		break;
3964 	case MSR_IA32_ARCH_CAPABILITIES:
3965 		if (!msr_info->host_initiated ||
3966 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
3967 			return KVM_MSR_RET_UNSUPPORTED;
3968 		vcpu->arch.arch_capabilities = data;
3969 		break;
3970 	case MSR_IA32_PERF_CAPABILITIES:
3971 		if (!msr_info->host_initiated ||
3972 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
3973 			return KVM_MSR_RET_UNSUPPORTED;
3974 
3975 		if (data & ~kvm_caps.supported_perf_cap)
3976 			return 1;
3977 
3978 		/*
3979 		 * Note, this is not just a performance optimization!  KVM
3980 		 * disallows changing feature MSRs after the vCPU has run; PMU
3981 		 * refresh will bug the VM if called after the vCPU has run.
3982 		 */
3983 		if (vcpu->arch.perf_capabilities == data)
3984 			break;
3985 
3986 		vcpu->arch.perf_capabilities = data;
3987 		kvm_pmu_refresh(vcpu);
3988 		break;
3989 	case MSR_IA32_PRED_CMD: {
3990 		u64 reserved_bits = ~(PRED_CMD_IBPB | PRED_CMD_SBPB);
3991 
3992 		if (!msr_info->host_initiated) {
3993 			if ((!guest_has_pred_cmd_msr(vcpu)))
3994 				return 1;
3995 
3996 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
3997 			    !guest_cpu_cap_has(vcpu, X86_FEATURE_AMD_IBPB))
3998 				reserved_bits |= PRED_CMD_IBPB;
3999 
4000 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SBPB))
4001 				reserved_bits |= PRED_CMD_SBPB;
4002 		}
4003 
4004 		if (!boot_cpu_has(X86_FEATURE_IBPB))
4005 			reserved_bits |= PRED_CMD_IBPB;
4006 
4007 		if (!boot_cpu_has(X86_FEATURE_SBPB))
4008 			reserved_bits |= PRED_CMD_SBPB;
4009 
4010 		if (data & reserved_bits)
4011 			return 1;
4012 
4013 		if (!data)
4014 			break;
4015 
4016 		wrmsrq(MSR_IA32_PRED_CMD, data);
4017 		break;
4018 	}
4019 	case MSR_IA32_FLUSH_CMD:
4020 		if (!msr_info->host_initiated &&
4021 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D))
4022 			return 1;
4023 
4024 		if (!boot_cpu_has(X86_FEATURE_FLUSH_L1D) || (data & ~L1D_FLUSH))
4025 			return 1;
4026 		if (!data)
4027 			break;
4028 
4029 		wrmsrq(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
4030 		break;
4031 	case MSR_EFER:
4032 		return set_efer(vcpu, msr_info);
4033 	case MSR_K7_HWCR:
4034 		data &= ~(u64)0x40;	/* ignore flush filter disable */
4035 		data &= ~(u64)0x100;	/* ignore ignne emulation enable */
4036 		data &= ~(u64)0x8;	/* ignore TLB cache disable */
4037 
4038 		/*
4039 		 * Allow McStatusWrEn and TscFreqSel. (Linux guests from v3.2
4040 		 * through at least v6.6 whine if TscFreqSel is clear,
4041 		 * depending on F/M/S.
4042 		 */
4043 		if (data & ~(BIT_ULL(18) | BIT_ULL(24))) {
4044 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4045 			return 1;
4046 		}
4047 		vcpu->arch.msr_hwcr = data;
4048 		break;
4049 	case MSR_FAM10H_MMIO_CONF_BASE:
4050 		if (data != 0) {
4051 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4052 			return 1;
4053 		}
4054 		break;
4055 	case MSR_IA32_CR_PAT:
4056 		if (!kvm_pat_valid(data))
4057 			return 1;
4058 
4059 		vcpu->arch.pat = data;
4060 		break;
4061 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4062 	case MSR_MTRRdefType:
4063 		return kvm_mtrr_set_msr(vcpu, msr, data);
4064 	case MSR_IA32_APICBASE:
4065 		return kvm_apic_set_base(vcpu, data, msr_info->host_initiated);
4066 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4067 		return kvm_x2apic_msr_write(vcpu, msr, data);
4068 	case MSR_IA32_TSC_DEADLINE:
4069 		kvm_set_lapic_tscdeadline_msr(vcpu, data);
4070 		break;
4071 	case MSR_IA32_TSC_ADJUST:
4072 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
4073 			if (!msr_info->host_initiated) {
4074 				s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
4075 				adjust_tsc_offset_guest(vcpu, adj);
4076 				/* Before back to guest, tsc_timestamp must be adjusted
4077 				 * as well, otherwise guest's percpu pvclock time could jump.
4078 				 */
4079 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
4080 			}
4081 			vcpu->arch.ia32_tsc_adjust_msr = data;
4082 		}
4083 		break;
4084 	case MSR_IA32_MISC_ENABLE: {
4085 		u64 old_val = vcpu->arch.ia32_misc_enable_msr;
4086 
4087 		if (!msr_info->host_initiated) {
4088 			/* RO bits */
4089 			if ((old_val ^ data) & MSR_IA32_MISC_ENABLE_PMU_RO_MASK)
4090 				return 1;
4091 
4092 			/* R bits, i.e. writes are ignored, but don't fault. */
4093 			data = data & ~MSR_IA32_MISC_ENABLE_EMON;
4094 			data |= old_val & MSR_IA32_MISC_ENABLE_EMON;
4095 		}
4096 
4097 		if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT) &&
4098 		    ((old_val ^ data)  & MSR_IA32_MISC_ENABLE_MWAIT)) {
4099 			if (!guest_cpu_cap_has(vcpu, X86_FEATURE_XMM3))
4100 				return 1;
4101 			vcpu->arch.ia32_misc_enable_msr = data;
4102 			vcpu->arch.cpuid_dynamic_bits_dirty = true;
4103 		} else {
4104 			vcpu->arch.ia32_misc_enable_msr = data;
4105 		}
4106 		break;
4107 	}
4108 	case MSR_IA32_SMBASE:
4109 		if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4110 			return 1;
4111 		vcpu->arch.smbase = data;
4112 		break;
4113 	case MSR_IA32_POWER_CTL:
4114 		vcpu->arch.msr_ia32_power_ctl = data;
4115 		break;
4116 	case MSR_IA32_TSC:
4117 		if (msr_info->host_initiated) {
4118 			kvm_synchronize_tsc(vcpu, &data);
4119 		} else if (!vcpu->arch.guest_tsc_protected) {
4120 			u64 adj = kvm_compute_l1_tsc_offset(vcpu, data) - vcpu->arch.l1_tsc_offset;
4121 			adjust_tsc_offset_guest(vcpu, adj);
4122 			vcpu->arch.ia32_tsc_adjust_msr += adj;
4123 		}
4124 		break;
4125 	case MSR_IA32_XSS:
4126 		if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4127 			return KVM_MSR_RET_UNSUPPORTED;
4128 
4129 		if (data & ~vcpu->arch.guest_supported_xss)
4130 			return 1;
4131 		if (vcpu->arch.ia32_xss == data)
4132 			break;
4133 		vcpu->arch.ia32_xss = data;
4134 		vcpu->arch.cpuid_dynamic_bits_dirty = true;
4135 		break;
4136 	case MSR_SMI_COUNT:
4137 		if (!msr_info->host_initiated)
4138 			return 1;
4139 		vcpu->arch.smi_count = data;
4140 		break;
4141 	case MSR_KVM_WALL_CLOCK_NEW:
4142 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4143 			return 1;
4144 
4145 		vcpu->kvm->arch.wall_clock = data;
4146 		kvm_write_wall_clock(vcpu->kvm, data, 0);
4147 		break;
4148 	case MSR_KVM_WALL_CLOCK:
4149 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4150 			return 1;
4151 
4152 		vcpu->kvm->arch.wall_clock = data;
4153 		kvm_write_wall_clock(vcpu->kvm, data, 0);
4154 		break;
4155 	case MSR_KVM_SYSTEM_TIME_NEW:
4156 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4157 			return 1;
4158 
4159 		kvm_write_system_time(vcpu, data, false, msr_info->host_initiated);
4160 		break;
4161 	case MSR_KVM_SYSTEM_TIME:
4162 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4163 			return 1;
4164 
4165 		kvm_write_system_time(vcpu, data, true,  msr_info->host_initiated);
4166 		break;
4167 	case MSR_KVM_ASYNC_PF_EN:
4168 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4169 			return 1;
4170 
4171 		if (kvm_pv_enable_async_pf(vcpu, data))
4172 			return 1;
4173 		break;
4174 	case MSR_KVM_ASYNC_PF_INT:
4175 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4176 			return 1;
4177 
4178 		if (kvm_pv_enable_async_pf_int(vcpu, data))
4179 			return 1;
4180 		break;
4181 	case MSR_KVM_ASYNC_PF_ACK:
4182 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4183 			return 1;
4184 		if (data & 0x1) {
4185 			vcpu->arch.apf.pageready_pending = false;
4186 			kvm_check_async_pf_completion(vcpu);
4187 		}
4188 		break;
4189 	case MSR_KVM_STEAL_TIME:
4190 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4191 			return 1;
4192 
4193 		if (unlikely(!sched_info_on()))
4194 			return 1;
4195 
4196 		if (data & KVM_STEAL_RESERVED_MASK)
4197 			return 1;
4198 
4199 		vcpu->arch.st.msr_val = data;
4200 
4201 		if (!(data & KVM_MSR_ENABLED))
4202 			break;
4203 
4204 		kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
4205 
4206 		break;
4207 	case MSR_KVM_PV_EOI_EN:
4208 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4209 			return 1;
4210 
4211 		if (kvm_lapic_set_pv_eoi(vcpu, data, sizeof(u8)))
4212 			return 1;
4213 		break;
4214 
4215 	case MSR_KVM_POLL_CONTROL:
4216 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4217 			return 1;
4218 
4219 		/* only enable bit supported */
4220 		if (data & (-1ULL << 1))
4221 			return 1;
4222 
4223 		vcpu->arch.msr_kvm_poll_control = data;
4224 		break;
4225 
4226 	case MSR_IA32_MCG_CTL:
4227 	case MSR_IA32_MCG_STATUS:
4228 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4229 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4230 		return set_msr_mce(vcpu, msr_info);
4231 
4232 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4233 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4234 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4235 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4236 		if (kvm_pmu_is_valid_msr(vcpu, msr))
4237 			return kvm_pmu_set_msr(vcpu, msr_info);
4238 
4239 		if (data)
4240 			kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4241 		break;
4242 	case MSR_K7_CLK_CTL:
4243 		/*
4244 		 * Ignore all writes to this no longer documented MSR.
4245 		 * Writes are only relevant for old K7 processors,
4246 		 * all pre-dating SVM, but a recommended workaround from
4247 		 * AMD for these chips. It is possible to specify the
4248 		 * affected processor models on the command line, hence
4249 		 * the need to ignore the workaround.
4250 		 */
4251 		break;
4252 #ifdef CONFIG_KVM_HYPERV
4253 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4254 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4255 	case HV_X64_MSR_SYNDBG_OPTIONS:
4256 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4257 	case HV_X64_MSR_CRASH_CTL:
4258 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4259 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4260 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4261 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4262 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4263 		return kvm_hv_set_msr_common(vcpu, msr, data,
4264 					     msr_info->host_initiated);
4265 #endif
4266 	case MSR_IA32_BBL_CR_CTL3:
4267 		/* Drop writes to this legacy MSR -- see rdmsr
4268 		 * counterpart for further detail.
4269 		 */
4270 		kvm_pr_unimpl_wrmsr(vcpu, msr, data);
4271 		break;
4272 	case MSR_AMD64_OSVW_ID_LENGTH:
4273 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4274 			return 1;
4275 		vcpu->arch.osvw.length = data;
4276 		break;
4277 	case MSR_AMD64_OSVW_STATUS:
4278 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4279 			return 1;
4280 		vcpu->arch.osvw.status = data;
4281 		break;
4282 	case MSR_PLATFORM_INFO:
4283 		if (!msr_info->host_initiated)
4284 			return 1;
4285 		vcpu->arch.msr_platform_info = data;
4286 		break;
4287 	case MSR_MISC_FEATURES_ENABLES:
4288 		if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
4289 		    (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
4290 		     !supports_cpuid_fault(vcpu)))
4291 			return 1;
4292 		vcpu->arch.msr_misc_features_enables = data;
4293 		break;
4294 #ifdef CONFIG_X86_64
4295 	case MSR_IA32_XFD:
4296 		if (!msr_info->host_initiated &&
4297 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4298 			return 1;
4299 
4300 		if (data & ~kvm_guest_supported_xfd(vcpu))
4301 			return 1;
4302 
4303 		fpu_update_guest_xfd(&vcpu->arch.guest_fpu, data);
4304 		break;
4305 	case MSR_IA32_XFD_ERR:
4306 		if (!msr_info->host_initiated &&
4307 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4308 			return 1;
4309 
4310 		if (data & ~kvm_guest_supported_xfd(vcpu))
4311 			return 1;
4312 
4313 		vcpu->arch.guest_fpu.xfd_err = data;
4314 		break;
4315 #endif
4316 	case MSR_IA32_U_CET:
4317 	case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
4318 		kvm_set_xstate_msr(vcpu, msr_info);
4319 		break;
4320 	default:
4321 		if (kvm_pmu_is_valid_msr(vcpu, msr))
4322 			return kvm_pmu_set_msr(vcpu, msr_info);
4323 
4324 		return KVM_MSR_RET_UNSUPPORTED;
4325 	}
4326 	return 0;
4327 }
4328 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_msr_common);
4329 
get_msr_mce(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)4330 static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
4331 {
4332 	u64 data;
4333 	u64 mcg_cap = vcpu->arch.mcg_cap;
4334 	unsigned bank_num = mcg_cap & 0xff;
4335 	u32 offset, last_msr;
4336 
4337 	switch (msr) {
4338 	case MSR_IA32_P5_MC_ADDR:
4339 	case MSR_IA32_P5_MC_TYPE:
4340 		data = 0;
4341 		break;
4342 	case MSR_IA32_MCG_CAP:
4343 		data = vcpu->arch.mcg_cap;
4344 		break;
4345 	case MSR_IA32_MCG_CTL:
4346 		if (!(mcg_cap & MCG_CTL_P) && !host)
4347 			return 1;
4348 		data = vcpu->arch.mcg_ctl;
4349 		break;
4350 	case MSR_IA32_MCG_STATUS:
4351 		data = vcpu->arch.mcg_status;
4352 		break;
4353 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4354 		last_msr = MSR_IA32_MCx_CTL2(bank_num) - 1;
4355 		if (msr > last_msr)
4356 			return 1;
4357 
4358 		if (!(mcg_cap & MCG_CMCI_P) && !host)
4359 			return 1;
4360 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL2,
4361 					    last_msr + 1 - MSR_IA32_MC0_CTL2);
4362 		data = vcpu->arch.mci_ctl2_banks[offset];
4363 		break;
4364 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4365 		last_msr = MSR_IA32_MCx_CTL(bank_num) - 1;
4366 		if (msr > last_msr)
4367 			return 1;
4368 
4369 		offset = array_index_nospec(msr - MSR_IA32_MC0_CTL,
4370 					    last_msr + 1 - MSR_IA32_MC0_CTL);
4371 		data = vcpu->arch.mce_banks[offset];
4372 		break;
4373 	default:
4374 		return 1;
4375 	}
4376 	*pdata = data;
4377 	return 0;
4378 }
4379 
kvm_get_msr_common(struct kvm_vcpu * vcpu,struct msr_data * msr_info)4380 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4381 {
4382 	switch (msr_info->index) {
4383 	case MSR_IA32_PLATFORM_ID:
4384 	case MSR_IA32_EBL_CR_POWERON:
4385 	case MSR_IA32_LASTBRANCHFROMIP:
4386 	case MSR_IA32_LASTBRANCHTOIP:
4387 	case MSR_IA32_LASTINTFROMIP:
4388 	case MSR_IA32_LASTINTTOIP:
4389 	case MSR_AMD64_SYSCFG:
4390 	case MSR_K8_TSEG_ADDR:
4391 	case MSR_K8_TSEG_MASK:
4392 	case MSR_VM_HSAVE_PA:
4393 	case MSR_K8_INT_PENDING_MSG:
4394 	case MSR_AMD64_NB_CFG:
4395 	case MSR_FAM10H_MMIO_CONF_BASE:
4396 	case MSR_AMD64_BU_CFG2:
4397 	case MSR_IA32_PERF_CTL:
4398 	case MSR_AMD64_DC_CFG:
4399 	case MSR_AMD64_TW_CFG:
4400 	case MSR_F15H_EX_CFG:
4401 	/*
4402 	 * Intel Sandy Bridge CPUs must support the RAPL (running average power
4403 	 * limit) MSRs. Just return 0, as we do not want to expose the host
4404 	 * data here. Do not conditionalize this on CPUID, as KVM does not do
4405 	 * so for existing CPU-specific MSRs.
4406 	 */
4407 	case MSR_RAPL_POWER_UNIT:
4408 	case MSR_PP0_ENERGY_STATUS:	/* Power plane 0 (core) */
4409 	case MSR_PP1_ENERGY_STATUS:	/* Power plane 1 (graphics uncore) */
4410 	case MSR_PKG_ENERGY_STATUS:	/* Total package */
4411 	case MSR_DRAM_ENERGY_STATUS:	/* DRAM controller */
4412 		msr_info->data = 0;
4413 		break;
4414 	case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
4415 	case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
4416 	case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
4417 	case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
4418 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4419 			return kvm_pmu_get_msr(vcpu, msr_info);
4420 		msr_info->data = 0;
4421 		break;
4422 	case MSR_IA32_UCODE_REV:
4423 		msr_info->data = vcpu->arch.microcode_version;
4424 		break;
4425 	case MSR_IA32_ARCH_CAPABILITIES:
4426 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_ARCH_CAPABILITIES))
4427 			return KVM_MSR_RET_UNSUPPORTED;
4428 		msr_info->data = vcpu->arch.arch_capabilities;
4429 		break;
4430 	case MSR_IA32_PERF_CAPABILITIES:
4431 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
4432 			return KVM_MSR_RET_UNSUPPORTED;
4433 		msr_info->data = vcpu->arch.perf_capabilities;
4434 		break;
4435 	case MSR_IA32_POWER_CTL:
4436 		msr_info->data = vcpu->arch.msr_ia32_power_ctl;
4437 		break;
4438 	case MSR_IA32_TSC: {
4439 		/*
4440 		 * Intel SDM states that MSR_IA32_TSC read adds the TSC offset
4441 		 * even when not intercepted. AMD manual doesn't explicitly
4442 		 * state this but appears to behave the same.
4443 		 *
4444 		 * On userspace reads and writes, however, we unconditionally
4445 		 * return L1's TSC value to ensure backwards-compatible
4446 		 * behavior for migration.
4447 		 */
4448 		u64 offset, ratio;
4449 
4450 		if (msr_info->host_initiated) {
4451 			offset = vcpu->arch.l1_tsc_offset;
4452 			ratio = vcpu->arch.l1_tsc_scaling_ratio;
4453 		} else {
4454 			offset = vcpu->arch.tsc_offset;
4455 			ratio = vcpu->arch.tsc_scaling_ratio;
4456 		}
4457 
4458 		msr_info->data = kvm_scale_tsc(rdtsc(), ratio) + offset;
4459 		break;
4460 	}
4461 	case MSR_IA32_CR_PAT:
4462 		msr_info->data = vcpu->arch.pat;
4463 		break;
4464 	case MSR_MTRRcap:
4465 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
4466 	case MSR_MTRRdefType:
4467 		return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
4468 	case 0xcd: /* fsb frequency */
4469 		msr_info->data = 3;
4470 		break;
4471 		/*
4472 		 * MSR_EBC_FREQUENCY_ID
4473 		 * Conservative value valid for even the basic CPU models.
4474 		 * Models 0,1: 000 in bits 23:21 indicating a bus speed of
4475 		 * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
4476 		 * and 266MHz for model 3, or 4. Set Core Clock
4477 		 * Frequency to System Bus Frequency Ratio to 1 (bits
4478 		 * 31:24) even though these are only valid for CPU
4479 		 * models > 2, however guests may end up dividing or
4480 		 * multiplying by zero otherwise.
4481 		 */
4482 	case MSR_EBC_FREQUENCY_ID:
4483 		msr_info->data = 1 << 24;
4484 		break;
4485 	case MSR_IA32_APICBASE:
4486 		msr_info->data = vcpu->arch.apic_base;
4487 		break;
4488 	case APIC_BASE_MSR ... APIC_BASE_MSR + 0xff:
4489 		return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
4490 	case MSR_IA32_TSC_DEADLINE:
4491 		msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
4492 		break;
4493 	case MSR_IA32_TSC_ADJUST:
4494 		msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
4495 		break;
4496 	case MSR_IA32_MISC_ENABLE:
4497 		msr_info->data = vcpu->arch.ia32_misc_enable_msr;
4498 		break;
4499 	case MSR_IA32_SMBASE:
4500 		if (!IS_ENABLED(CONFIG_KVM_SMM) || !msr_info->host_initiated)
4501 			return 1;
4502 		msr_info->data = vcpu->arch.smbase;
4503 		break;
4504 	case MSR_SMI_COUNT:
4505 		msr_info->data = vcpu->arch.smi_count;
4506 		break;
4507 	case MSR_IA32_PERF_STATUS:
4508 		/* TSC increment by tick */
4509 		msr_info->data = 1000ULL;
4510 		/* CPU multiplier */
4511 		msr_info->data |= (((uint64_t)4ULL) << 40);
4512 		break;
4513 	case MSR_EFER:
4514 		msr_info->data = vcpu->arch.efer;
4515 		break;
4516 	case MSR_KVM_WALL_CLOCK:
4517 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4518 			return 1;
4519 
4520 		msr_info->data = vcpu->kvm->arch.wall_clock;
4521 		break;
4522 	case MSR_KVM_WALL_CLOCK_NEW:
4523 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4524 			return 1;
4525 
4526 		msr_info->data = vcpu->kvm->arch.wall_clock;
4527 		break;
4528 	case MSR_KVM_SYSTEM_TIME:
4529 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE))
4530 			return 1;
4531 
4532 		msr_info->data = vcpu->arch.time;
4533 		break;
4534 	case MSR_KVM_SYSTEM_TIME_NEW:
4535 		if (!guest_pv_has(vcpu, KVM_FEATURE_CLOCKSOURCE2))
4536 			return 1;
4537 
4538 		msr_info->data = vcpu->arch.time;
4539 		break;
4540 	case MSR_KVM_ASYNC_PF_EN:
4541 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF))
4542 			return 1;
4543 
4544 		msr_info->data = vcpu->arch.apf.msr_en_val;
4545 		break;
4546 	case MSR_KVM_ASYNC_PF_INT:
4547 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4548 			return 1;
4549 
4550 		msr_info->data = vcpu->arch.apf.msr_int_val;
4551 		break;
4552 	case MSR_KVM_ASYNC_PF_ACK:
4553 		if (!guest_pv_has(vcpu, KVM_FEATURE_ASYNC_PF_INT))
4554 			return 1;
4555 
4556 		msr_info->data = 0;
4557 		break;
4558 	case MSR_KVM_STEAL_TIME:
4559 		if (!guest_pv_has(vcpu, KVM_FEATURE_STEAL_TIME))
4560 			return 1;
4561 
4562 		msr_info->data = vcpu->arch.st.msr_val;
4563 		break;
4564 	case MSR_KVM_PV_EOI_EN:
4565 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_EOI))
4566 			return 1;
4567 
4568 		msr_info->data = vcpu->arch.pv_eoi.msr_val;
4569 		break;
4570 	case MSR_KVM_POLL_CONTROL:
4571 		if (!guest_pv_has(vcpu, KVM_FEATURE_POLL_CONTROL))
4572 			return 1;
4573 
4574 		msr_info->data = vcpu->arch.msr_kvm_poll_control;
4575 		break;
4576 	case MSR_IA32_P5_MC_ADDR:
4577 	case MSR_IA32_P5_MC_TYPE:
4578 	case MSR_IA32_MCG_CAP:
4579 	case MSR_IA32_MCG_CTL:
4580 	case MSR_IA32_MCG_STATUS:
4581 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
4582 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
4583 		return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
4584 				   msr_info->host_initiated);
4585 	case MSR_IA32_XSS:
4586 		if (!msr_info->host_initiated &&
4587 		    !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4588 			return 1;
4589 		msr_info->data = vcpu->arch.ia32_xss;
4590 		break;
4591 	case MSR_K7_CLK_CTL:
4592 		/*
4593 		 * Provide expected ramp-up count for K7. All other
4594 		 * are set to zero, indicating minimum divisors for
4595 		 * every field.
4596 		 *
4597 		 * This prevents guest kernels on AMD host with CPU
4598 		 * type 6, model 8 and higher from exploding due to
4599 		 * the rdmsr failing.
4600 		 */
4601 		msr_info->data = 0x20000000;
4602 		break;
4603 #ifdef CONFIG_KVM_HYPERV
4604 	case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
4605 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
4606 	case HV_X64_MSR_SYNDBG_OPTIONS:
4607 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
4608 	case HV_X64_MSR_CRASH_CTL:
4609 	case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
4610 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
4611 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
4612 	case HV_X64_MSR_TSC_EMULATION_STATUS:
4613 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
4614 		return kvm_hv_get_msr_common(vcpu,
4615 					     msr_info->index, &msr_info->data,
4616 					     msr_info->host_initiated);
4617 #endif
4618 	case MSR_IA32_BBL_CR_CTL3:
4619 		/* This legacy MSR exists but isn't fully documented in current
4620 		 * silicon.  It is however accessed by winxp in very narrow
4621 		 * scenarios where it sets bit #19, itself documented as
4622 		 * a "reserved" bit.  Best effort attempt to source coherent
4623 		 * read data here should the balance of the register be
4624 		 * interpreted by the guest:
4625 		 *
4626 		 * L2 cache control register 3: 64GB range, 256KB size,
4627 		 * enabled, latency 0x1, configured
4628 		 */
4629 		msr_info->data = 0xbe702111;
4630 		break;
4631 	case MSR_AMD64_OSVW_ID_LENGTH:
4632 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4633 			return 1;
4634 		msr_info->data = vcpu->arch.osvw.length;
4635 		break;
4636 	case MSR_AMD64_OSVW_STATUS:
4637 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_OSVW))
4638 			return 1;
4639 		msr_info->data = vcpu->arch.osvw.status;
4640 		break;
4641 	case MSR_PLATFORM_INFO:
4642 		if (!msr_info->host_initiated &&
4643 		    !vcpu->kvm->arch.guest_can_read_msr_platform_info)
4644 			return 1;
4645 		msr_info->data = vcpu->arch.msr_platform_info;
4646 		break;
4647 	case MSR_MISC_FEATURES_ENABLES:
4648 		msr_info->data = vcpu->arch.msr_misc_features_enables;
4649 		break;
4650 	case MSR_K7_HWCR:
4651 		msr_info->data = vcpu->arch.msr_hwcr;
4652 		break;
4653 #ifdef CONFIG_X86_64
4654 	case MSR_IA32_XFD:
4655 		if (!msr_info->host_initiated &&
4656 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4657 			return 1;
4658 
4659 		msr_info->data = vcpu->arch.guest_fpu.fpstate->xfd;
4660 		break;
4661 	case MSR_IA32_XFD_ERR:
4662 		if (!msr_info->host_initiated &&
4663 		    !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD))
4664 			return 1;
4665 
4666 		msr_info->data = vcpu->arch.guest_fpu.xfd_err;
4667 		break;
4668 #endif
4669 	case MSR_IA32_U_CET:
4670 	case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
4671 		kvm_get_xstate_msr(vcpu, msr_info);
4672 		break;
4673 	default:
4674 		if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
4675 			return kvm_pmu_get_msr(vcpu, msr_info);
4676 
4677 		return KVM_MSR_RET_UNSUPPORTED;
4678 	}
4679 	return 0;
4680 }
4681 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_msr_common);
4682 
4683 /*
4684  * Read or write a bunch of msrs. All parameters are kernel addresses.
4685  *
4686  * @return number of msrs set successfully.
4687  */
__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))4688 static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
4689 		    struct kvm_msr_entry *entries,
4690 		    int (*do_msr)(struct kvm_vcpu *vcpu,
4691 				  unsigned index, u64 *data))
4692 {
4693 	bool fpu_loaded = false;
4694 	int i;
4695 
4696 	for (i = 0; i < msrs->nmsrs; ++i) {
4697 		/*
4698 		 * If userspace is accessing one or more XSTATE-managed MSRs,
4699 		 * temporarily load the guest's FPU state so that the guest's
4700 		 * MSR value(s) is resident in hardware and thus can be accessed
4701 		 * via RDMSR/WRMSR.
4702 		 */
4703 		if (!fpu_loaded && is_xstate_managed_msr(vcpu, entries[i].index)) {
4704 			kvm_load_guest_fpu(vcpu);
4705 			fpu_loaded = true;
4706 		}
4707 		if (do_msr(vcpu, entries[i].index, &entries[i].data))
4708 			break;
4709 	}
4710 	if (fpu_loaded)
4711 		kvm_put_guest_fpu(vcpu);
4712 
4713 	return i;
4714 }
4715 
4716 /*
4717  * Read or write a bunch of msrs. Parameters are user addresses.
4718  *
4719  * @return number of msrs set successfully.
4720  */
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)4721 static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
4722 		  int (*do_msr)(struct kvm_vcpu *vcpu,
4723 				unsigned index, u64 *data),
4724 		  int writeback)
4725 {
4726 	struct kvm_msrs msrs;
4727 	struct kvm_msr_entry *entries;
4728 	unsigned size;
4729 	int r;
4730 
4731 	r = -EFAULT;
4732 	if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
4733 		goto out;
4734 
4735 	r = -E2BIG;
4736 	if (msrs.nmsrs >= MAX_IO_MSRS)
4737 		goto out;
4738 
4739 	size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
4740 	entries = memdup_user(user_msrs->entries, size);
4741 	if (IS_ERR(entries)) {
4742 		r = PTR_ERR(entries);
4743 		goto out;
4744 	}
4745 
4746 	r = __msr_io(vcpu, &msrs, entries, do_msr);
4747 
4748 	if (writeback && copy_to_user(user_msrs->entries, entries, size))
4749 		r = -EFAULT;
4750 
4751 	kfree(entries);
4752 out:
4753 	return r;
4754 }
4755 
kvm_can_mwait_in_guest(void)4756 static inline bool kvm_can_mwait_in_guest(void)
4757 {
4758 	return boot_cpu_has(X86_FEATURE_MWAIT) &&
4759 		!boot_cpu_has_bug(X86_BUG_MONITOR) &&
4760 		boot_cpu_has(X86_FEATURE_ARAT);
4761 }
4762 
kvm_get_allowed_disable_exits(void)4763 static u64 kvm_get_allowed_disable_exits(void)
4764 {
4765 	u64 r = KVM_X86_DISABLE_EXITS_PAUSE;
4766 
4767 	if (boot_cpu_has(X86_FEATURE_APERFMPERF))
4768 		r |= KVM_X86_DISABLE_EXITS_APERFMPERF;
4769 
4770 	if (!mitigate_smt_rsb) {
4771 		r |= KVM_X86_DISABLE_EXITS_HLT |
4772 			KVM_X86_DISABLE_EXITS_CSTATE;
4773 
4774 		if (kvm_can_mwait_in_guest())
4775 			r |= KVM_X86_DISABLE_EXITS_MWAIT;
4776 	}
4777 	return r;
4778 }
4779 
4780 #ifdef CONFIG_KVM_HYPERV
kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 __user * cpuid_arg)4781 static int kvm_ioctl_get_supported_hv_cpuid(struct kvm_vcpu *vcpu,
4782 					    struct kvm_cpuid2 __user *cpuid_arg)
4783 {
4784 	struct kvm_cpuid2 cpuid;
4785 	int r;
4786 
4787 	r = -EFAULT;
4788 	if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
4789 		return r;
4790 
4791 	r = kvm_get_hv_cpuid(vcpu, &cpuid, cpuid_arg->entries);
4792 	if (r)
4793 		return r;
4794 
4795 	r = -EFAULT;
4796 	if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
4797 		return r;
4798 
4799 	return 0;
4800 }
4801 #endif
4802 
kvm_is_vm_type_supported(unsigned long type)4803 static bool kvm_is_vm_type_supported(unsigned long type)
4804 {
4805 	return type < 32 && (kvm_caps.supported_vm_types & BIT(type));
4806 }
4807 
kvm_sync_valid_fields(struct kvm * kvm)4808 static inline u64 kvm_sync_valid_fields(struct kvm *kvm)
4809 {
4810 	return kvm && kvm->arch.has_protected_state ? 0 : KVM_SYNC_X86_VALID_FIELDS;
4811 }
4812 
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)4813 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
4814 {
4815 	int r = 0;
4816 
4817 	switch (ext) {
4818 	case KVM_CAP_IRQCHIP:
4819 	case KVM_CAP_HLT:
4820 	case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
4821 	case KVM_CAP_SET_TSS_ADDR:
4822 	case KVM_CAP_EXT_CPUID:
4823 	case KVM_CAP_EXT_EMUL_CPUID:
4824 	case KVM_CAP_CLOCKSOURCE:
4825 #ifdef CONFIG_KVM_IOAPIC
4826 	case KVM_CAP_PIT:
4827 	case KVM_CAP_PIT2:
4828 	case KVM_CAP_PIT_STATE2:
4829 	case KVM_CAP_REINJECT_CONTROL:
4830 #endif
4831 	case KVM_CAP_NOP_IO_DELAY:
4832 	case KVM_CAP_MP_STATE:
4833 	case KVM_CAP_SYNC_MMU:
4834 	case KVM_CAP_USER_NMI:
4835 	case KVM_CAP_IRQ_INJECT_STATUS:
4836 	case KVM_CAP_IOEVENTFD:
4837 	case KVM_CAP_IOEVENTFD_NO_LENGTH:
4838 
4839 	case KVM_CAP_SET_IDENTITY_MAP_ADDR:
4840 	case KVM_CAP_VCPU_EVENTS:
4841 #ifdef CONFIG_KVM_HYPERV
4842 	case KVM_CAP_HYPERV:
4843 	case KVM_CAP_HYPERV_VAPIC:
4844 	case KVM_CAP_HYPERV_SPIN:
4845 	case KVM_CAP_HYPERV_TIME:
4846 	case KVM_CAP_HYPERV_SYNIC:
4847 	case KVM_CAP_HYPERV_SYNIC2:
4848 	case KVM_CAP_HYPERV_VP_INDEX:
4849 	case KVM_CAP_HYPERV_EVENTFD:
4850 	case KVM_CAP_HYPERV_TLBFLUSH:
4851 	case KVM_CAP_HYPERV_SEND_IPI:
4852 	case KVM_CAP_HYPERV_CPUID:
4853 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
4854 	case KVM_CAP_SYS_HYPERV_CPUID:
4855 #endif
4856 	case KVM_CAP_PCI_SEGMENT:
4857 	case KVM_CAP_DEBUGREGS:
4858 	case KVM_CAP_X86_ROBUST_SINGLESTEP:
4859 	case KVM_CAP_XSAVE:
4860 	case KVM_CAP_ASYNC_PF:
4861 	case KVM_CAP_ASYNC_PF_INT:
4862 	case KVM_CAP_GET_TSC_KHZ:
4863 	case KVM_CAP_KVMCLOCK_CTRL:
4864 	case KVM_CAP_IOAPIC_POLARITY_IGNORED:
4865 	case KVM_CAP_TSC_DEADLINE_TIMER:
4866 	case KVM_CAP_DISABLE_QUIRKS:
4867 	case KVM_CAP_SET_BOOT_CPU_ID:
4868  	case KVM_CAP_SPLIT_IRQCHIP:
4869 	case KVM_CAP_IMMEDIATE_EXIT:
4870 	case KVM_CAP_PMU_EVENT_FILTER:
4871 	case KVM_CAP_PMU_EVENT_MASKED_EVENTS:
4872 	case KVM_CAP_GET_MSR_FEATURES:
4873 	case KVM_CAP_MSR_PLATFORM_INFO:
4874 	case KVM_CAP_EXCEPTION_PAYLOAD:
4875 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
4876 	case KVM_CAP_SET_GUEST_DEBUG:
4877 	case KVM_CAP_LAST_CPU:
4878 	case KVM_CAP_X86_USER_SPACE_MSR:
4879 	case KVM_CAP_X86_MSR_FILTER:
4880 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
4881 #ifdef CONFIG_X86_SGX_KVM
4882 	case KVM_CAP_SGX_ATTRIBUTE:
4883 #endif
4884 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
4885 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
4886 	case KVM_CAP_SREGS2:
4887 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
4888 	case KVM_CAP_VCPU_ATTRIBUTES:
4889 	case KVM_CAP_SYS_ATTRIBUTES:
4890 	case KVM_CAP_VAPIC:
4891 	case KVM_CAP_ENABLE_CAP:
4892 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
4893 	case KVM_CAP_IRQFD_RESAMPLE:
4894 	case KVM_CAP_MEMORY_FAULT_INFO:
4895 	case KVM_CAP_X86_GUEST_MODE:
4896 	case KVM_CAP_ONE_REG:
4897 		r = 1;
4898 		break;
4899 	case KVM_CAP_PRE_FAULT_MEMORY:
4900 		r = tdp_enabled;
4901 		break;
4902 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
4903 		r = APIC_BUS_CYCLE_NS_DEFAULT;
4904 		break;
4905 	case KVM_CAP_EXIT_HYPERCALL:
4906 		r = KVM_EXIT_HYPERCALL_VALID_MASK;
4907 		break;
4908 	case KVM_CAP_SET_GUEST_DEBUG2:
4909 		return KVM_GUESTDBG_VALID_MASK;
4910 #ifdef CONFIG_KVM_XEN
4911 	case KVM_CAP_XEN_HVM:
4912 		r = KVM_XEN_HVM_CONFIG_HYPERCALL_MSR |
4913 		    KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
4914 		    KVM_XEN_HVM_CONFIG_SHARED_INFO |
4915 		    KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL |
4916 		    KVM_XEN_HVM_CONFIG_EVTCHN_SEND |
4917 		    KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE |
4918 		    KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA;
4919 		if (sched_info_on())
4920 			r |= KVM_XEN_HVM_CONFIG_RUNSTATE |
4921 			     KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG;
4922 		break;
4923 #endif
4924 	case KVM_CAP_SYNC_REGS:
4925 		r = kvm_sync_valid_fields(kvm);
4926 		break;
4927 	case KVM_CAP_ADJUST_CLOCK:
4928 		r = KVM_CLOCK_VALID_FLAGS;
4929 		break;
4930 	case KVM_CAP_X86_DISABLE_EXITS:
4931 		r = kvm_get_allowed_disable_exits();
4932 		break;
4933 	case KVM_CAP_X86_SMM:
4934 		if (!IS_ENABLED(CONFIG_KVM_SMM))
4935 			break;
4936 
4937 		/* SMBASE is usually relocated above 1M on modern chipsets,
4938 		 * and SMM handlers might indeed rely on 4G segment limits,
4939 		 * so do not report SMM to be available if real mode is
4940 		 * emulated via vm86 mode.  Still, do not go to great lengths
4941 		 * to avoid userspace's usage of the feature, because it is a
4942 		 * fringe case that is not enabled except via specific settings
4943 		 * of the module parameters.
4944 		 */
4945 		r = kvm_x86_call(has_emulated_msr)(kvm, MSR_IA32_SMBASE);
4946 		break;
4947 	case KVM_CAP_NR_VCPUS:
4948 		r = min_t(unsigned int, num_online_cpus(), KVM_MAX_VCPUS);
4949 		break;
4950 	case KVM_CAP_MAX_VCPUS:
4951 		r = KVM_MAX_VCPUS;
4952 		if (kvm)
4953 			r = kvm->max_vcpus;
4954 		break;
4955 	case KVM_CAP_MAX_VCPU_ID:
4956 		r = KVM_MAX_VCPU_IDS;
4957 		break;
4958 	case KVM_CAP_PV_MMU:	/* obsolete */
4959 		r = 0;
4960 		break;
4961 	case KVM_CAP_MCE:
4962 		r = KVM_MAX_MCE_BANKS;
4963 		break;
4964 	case KVM_CAP_XCRS:
4965 		r = boot_cpu_has(X86_FEATURE_XSAVE);
4966 		break;
4967 	case KVM_CAP_TSC_CONTROL:
4968 	case KVM_CAP_VM_TSC_CONTROL:
4969 		r = kvm_caps.has_tsc_control;
4970 		break;
4971 	case KVM_CAP_X2APIC_API:
4972 		r = KVM_X2APIC_API_VALID_FLAGS;
4973 		break;
4974 	case KVM_CAP_NESTED_STATE:
4975 		r = kvm_x86_ops.nested_ops->get_state ?
4976 			kvm_x86_ops.nested_ops->get_state(NULL, NULL, 0) : 0;
4977 		break;
4978 #ifdef CONFIG_KVM_HYPERV
4979 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
4980 		r = kvm_x86_ops.enable_l2_tlb_flush != NULL;
4981 		break;
4982 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
4983 		r = kvm_x86_ops.nested_ops->enable_evmcs != NULL;
4984 		break;
4985 #endif
4986 	case KVM_CAP_SMALLER_MAXPHYADDR:
4987 		r = (int) allow_smaller_maxphyaddr;
4988 		break;
4989 	case KVM_CAP_STEAL_TIME:
4990 		r = sched_info_on();
4991 		break;
4992 	case KVM_CAP_X86_BUS_LOCK_EXIT:
4993 		if (kvm_caps.has_bus_lock_exit)
4994 			r = KVM_BUS_LOCK_DETECTION_OFF |
4995 			    KVM_BUS_LOCK_DETECTION_EXIT;
4996 		else
4997 			r = 0;
4998 		break;
4999 	case KVM_CAP_XSAVE2: {
5000 		r = xstate_required_size(kvm_get_filtered_xcr0(), false);
5001 		if (r < sizeof(struct kvm_xsave))
5002 			r = sizeof(struct kvm_xsave);
5003 		break;
5004 	}
5005 	case KVM_CAP_PMU_CAPABILITY:
5006 		r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
5007 		break;
5008 	case KVM_CAP_DISABLE_QUIRKS2:
5009 		r = kvm_caps.supported_quirks;
5010 		break;
5011 	case KVM_CAP_X86_NOTIFY_VMEXIT:
5012 		r = kvm_caps.has_notify_vmexit;
5013 		break;
5014 	case KVM_CAP_VM_TYPES:
5015 		r = kvm_caps.supported_vm_types;
5016 		break;
5017 	case KVM_CAP_READONLY_MEM:
5018 		r = kvm ? kvm_arch_has_readonly_mem(kvm) : 1;
5019 		break;
5020 	default:
5021 		break;
5022 	}
5023 	return r;
5024 }
5025 
__kvm_x86_dev_get_attr(struct kvm_device_attr * attr,u64 * val)5026 static int __kvm_x86_dev_get_attr(struct kvm_device_attr *attr, u64 *val)
5027 {
5028 	if (attr->group) {
5029 		if (kvm_x86_ops.dev_get_attr)
5030 			return kvm_x86_call(dev_get_attr)(attr->group, attr->attr, val);
5031 		return -ENXIO;
5032 	}
5033 
5034 	switch (attr->attr) {
5035 	case KVM_X86_XCOMP_GUEST_SUPP:
5036 		*val = kvm_caps.supported_xcr0;
5037 		return 0;
5038 	default:
5039 		return -ENXIO;
5040 	}
5041 }
5042 
kvm_x86_dev_get_attr(struct kvm_device_attr * attr)5043 static int kvm_x86_dev_get_attr(struct kvm_device_attr *attr)
5044 {
5045 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5046 	int r;
5047 	u64 val;
5048 
5049 	r = __kvm_x86_dev_get_attr(attr, &val);
5050 	if (r < 0)
5051 		return r;
5052 
5053 	if (put_user(val, uaddr))
5054 		return -EFAULT;
5055 
5056 	return 0;
5057 }
5058 
kvm_x86_dev_has_attr(struct kvm_device_attr * attr)5059 static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
5060 {
5061 	u64 val;
5062 
5063 	return __kvm_x86_dev_get_attr(attr, &val);
5064 }
5065 
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)5066 long kvm_arch_dev_ioctl(struct file *filp,
5067 			unsigned int ioctl, unsigned long arg)
5068 {
5069 	void __user *argp = (void __user *)arg;
5070 	long r;
5071 
5072 	switch (ioctl) {
5073 	case KVM_GET_MSR_INDEX_LIST: {
5074 		struct kvm_msr_list __user *user_msr_list = argp;
5075 		struct kvm_msr_list msr_list;
5076 		unsigned n;
5077 
5078 		r = -EFAULT;
5079 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
5080 			goto out;
5081 		n = msr_list.nmsrs;
5082 		msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
5083 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
5084 			goto out;
5085 		r = -E2BIG;
5086 		if (n < msr_list.nmsrs)
5087 			goto out;
5088 		r = -EFAULT;
5089 		if (copy_to_user(user_msr_list->indices, &msrs_to_save,
5090 				 num_msrs_to_save * sizeof(u32)))
5091 			goto out;
5092 		if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
5093 				 &emulated_msrs,
5094 				 num_emulated_msrs * sizeof(u32)))
5095 			goto out;
5096 		r = 0;
5097 		break;
5098 	}
5099 	case KVM_GET_SUPPORTED_CPUID:
5100 	case KVM_GET_EMULATED_CPUID: {
5101 		struct kvm_cpuid2 __user *cpuid_arg = argp;
5102 		struct kvm_cpuid2 cpuid;
5103 
5104 		r = -EFAULT;
5105 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
5106 			goto out;
5107 
5108 		r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
5109 					    ioctl);
5110 		if (r)
5111 			goto out;
5112 
5113 		r = -EFAULT;
5114 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
5115 			goto out;
5116 		r = 0;
5117 		break;
5118 	}
5119 	case KVM_X86_GET_MCE_CAP_SUPPORTED:
5120 		r = -EFAULT;
5121 		if (copy_to_user(argp, &kvm_caps.supported_mce_cap,
5122 				 sizeof(kvm_caps.supported_mce_cap)))
5123 			goto out;
5124 		r = 0;
5125 		break;
5126 	case KVM_GET_MSR_FEATURE_INDEX_LIST: {
5127 		struct kvm_msr_list __user *user_msr_list = argp;
5128 		struct kvm_msr_list msr_list;
5129 		unsigned int n;
5130 
5131 		r = -EFAULT;
5132 		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
5133 			goto out;
5134 		n = msr_list.nmsrs;
5135 		msr_list.nmsrs = num_msr_based_features;
5136 		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
5137 			goto out;
5138 		r = -E2BIG;
5139 		if (n < msr_list.nmsrs)
5140 			goto out;
5141 		r = -EFAULT;
5142 		if (copy_to_user(user_msr_list->indices, &msr_based_features,
5143 				 num_msr_based_features * sizeof(u32)))
5144 			goto out;
5145 		r = 0;
5146 		break;
5147 	}
5148 	case KVM_GET_MSRS:
5149 		r = msr_io(NULL, argp, do_get_feature_msr, 1);
5150 		break;
5151 #ifdef CONFIG_KVM_HYPERV
5152 	case KVM_GET_SUPPORTED_HV_CPUID:
5153 		r = kvm_ioctl_get_supported_hv_cpuid(NULL, argp);
5154 		break;
5155 #endif
5156 	case KVM_GET_DEVICE_ATTR: {
5157 		struct kvm_device_attr attr;
5158 		r = -EFAULT;
5159 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
5160 			break;
5161 		r = kvm_x86_dev_get_attr(&attr);
5162 		break;
5163 	}
5164 	case KVM_HAS_DEVICE_ATTR: {
5165 		struct kvm_device_attr attr;
5166 		r = -EFAULT;
5167 		if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
5168 			break;
5169 		r = kvm_x86_dev_has_attr(&attr);
5170 		break;
5171 	}
5172 	default:
5173 		r = -EINVAL;
5174 		break;
5175 	}
5176 out:
5177 	return r;
5178 }
5179 
need_emulate_wbinvd(struct kvm_vcpu * vcpu)5180 static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
5181 {
5182 	return kvm_arch_has_noncoherent_dma(vcpu->kvm);
5183 }
5184 
5185 static DEFINE_PER_CPU(struct kvm_vcpu *, last_vcpu);
5186 
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)5187 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
5188 {
5189 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
5190 
5191 	vcpu->arch.l1tf_flush_l1d = true;
5192 
5193 	if (vcpu->scheduled_out && pmu->version && pmu->event_count) {
5194 		pmu->need_cleanup = true;
5195 		kvm_make_request(KVM_REQ_PMU, vcpu);
5196 	}
5197 
5198 	/* Address WBINVD may be executed by guest */
5199 	if (need_emulate_wbinvd(vcpu)) {
5200 		if (kvm_x86_call(has_wbinvd_exit)())
5201 			cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
5202 		else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
5203 			wbinvd_on_cpu(vcpu->cpu);
5204 	}
5205 
5206 	kvm_x86_call(vcpu_load)(vcpu, cpu);
5207 
5208 	if (vcpu != per_cpu(last_vcpu, cpu)) {
5209 		/*
5210 		 * Flush the branch predictor when switching vCPUs on the same
5211 		 * physical CPU, as each vCPU needs its own branch prediction
5212 		 * domain.  No IBPB is needed when switching between L1 and L2
5213 		 * on the same vCPU unless IBRS is advertised to the vCPU; that
5214 		 * is handled on the nested VM-Exit path.
5215 		 */
5216 		if (static_branch_likely(&switch_vcpu_ibpb))
5217 			indirect_branch_prediction_barrier();
5218 		per_cpu(last_vcpu, cpu) = vcpu;
5219 	}
5220 
5221 	/* Save host pkru register if supported */
5222 	vcpu->arch.host_pkru = read_pkru();
5223 
5224 	/* Apply any externally detected TSC adjustments (due to suspend) */
5225 	if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
5226 		adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
5227 		vcpu->arch.tsc_offset_adjustment = 0;
5228 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5229 	}
5230 
5231 	if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
5232 		s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
5233 				rdtsc() - vcpu->arch.last_host_tsc;
5234 		if (tsc_delta < 0)
5235 			mark_tsc_unstable("KVM discovered backwards TSC");
5236 
5237 		if (kvm_check_tsc_unstable()) {
5238 			u64 offset = kvm_compute_l1_tsc_offset(vcpu,
5239 						vcpu->arch.last_guest_tsc);
5240 			kvm_vcpu_write_tsc_offset(vcpu, offset);
5241 			if (!vcpu->arch.guest_tsc_protected)
5242 				vcpu->arch.tsc_catchup = 1;
5243 		}
5244 
5245 		if (kvm_lapic_hv_timer_in_use(vcpu))
5246 			kvm_lapic_restart_hv_timer(vcpu);
5247 
5248 		/*
5249 		 * On a host with synchronized TSC, there is no need to update
5250 		 * kvmclock on vcpu->cpu migration
5251 		 */
5252 		if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
5253 			kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
5254 		if (vcpu->cpu != cpu)
5255 			kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
5256 		vcpu->cpu = cpu;
5257 	}
5258 
5259 	kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
5260 }
5261 
kvm_steal_time_set_preempted(struct kvm_vcpu * vcpu)5262 static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
5263 {
5264 	struct gfn_to_hva_cache *ghc = &vcpu->arch.st.cache;
5265 	struct kvm_steal_time __user *st;
5266 	struct kvm_memslots *slots;
5267 	static const u8 preempted = KVM_VCPU_PREEMPTED;
5268 	gpa_t gpa = vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS;
5269 
5270 	/*
5271 	 * The vCPU can be marked preempted if and only if the VM-Exit was on
5272 	 * an instruction boundary and will not trigger guest emulation of any
5273 	 * kind (see vcpu_run).  Vendor specific code controls (conservatively)
5274 	 * when this is true, for example allowing the vCPU to be marked
5275 	 * preempted if and only if the VM-Exit was due to a host interrupt.
5276 	 */
5277 	if (!vcpu->arch.at_instruction_boundary) {
5278 		vcpu->stat.preemption_other++;
5279 		return;
5280 	}
5281 
5282 	vcpu->stat.preemption_reported++;
5283 	if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
5284 		return;
5285 
5286 	if (vcpu->arch.st.preempted)
5287 		return;
5288 
5289 	/* This happens on process exit */
5290 	if (unlikely(current->mm != vcpu->kvm->mm))
5291 		return;
5292 
5293 	slots = kvm_memslots(vcpu->kvm);
5294 
5295 	if (unlikely(slots->generation != ghc->generation ||
5296 		     gpa != ghc->gpa ||
5297 		     kvm_is_error_hva(ghc->hva) || !ghc->memslot))
5298 		return;
5299 
5300 	st = (struct kvm_steal_time __user *)ghc->hva;
5301 	BUILD_BUG_ON(sizeof(st->preempted) != sizeof(preempted));
5302 
5303 	if (!copy_to_user_nofault(&st->preempted, &preempted, sizeof(preempted)))
5304 		vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
5305 
5306 	mark_page_dirty_in_slot(vcpu->kvm, ghc->memslot, gpa_to_gfn(ghc->gpa));
5307 }
5308 
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)5309 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
5310 {
5311 	int idx;
5312 
5313 	if (vcpu->preempted) {
5314 		/*
5315 		 * Assume protected guests are in-kernel.  Inefficient yielding
5316 		 * due to false positives is preferable to never yielding due
5317 		 * to false negatives.
5318 		 */
5319 		vcpu->arch.preempted_in_kernel = vcpu->arch.guest_state_protected ||
5320 						 !kvm_x86_call(get_cpl_no_cache)(vcpu);
5321 
5322 		/*
5323 		 * Take the srcu lock as memslots will be accessed to check the gfn
5324 		 * cache generation against the memslots generation.
5325 		 */
5326 		idx = srcu_read_lock(&vcpu->kvm->srcu);
5327 		if (kvm_xen_msr_enabled(vcpu->kvm))
5328 			kvm_xen_runstate_set_preempted(vcpu);
5329 		else
5330 			kvm_steal_time_set_preempted(vcpu);
5331 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
5332 	}
5333 
5334 	kvm_x86_call(vcpu_put)(vcpu);
5335 	vcpu->arch.last_host_tsc = rdtsc();
5336 }
5337 
kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5338 static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
5339 				    struct kvm_lapic_state *s)
5340 {
5341 	if (vcpu->arch.apic->guest_apic_protected)
5342 		return -EINVAL;
5343 
5344 	kvm_x86_call(sync_pir_to_irr)(vcpu);
5345 
5346 	return kvm_apic_get_state(vcpu, s);
5347 }
5348 
kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)5349 static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
5350 				    struct kvm_lapic_state *s)
5351 {
5352 	int r;
5353 
5354 	if (vcpu->arch.apic->guest_apic_protected)
5355 		return -EINVAL;
5356 
5357 	r = kvm_apic_set_state(vcpu, s);
5358 	if (r)
5359 		return r;
5360 	update_cr8_intercept(vcpu);
5361 
5362 	return 0;
5363 }
5364 
kvm_cpu_accept_dm_intr(struct kvm_vcpu * vcpu)5365 static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
5366 {
5367 	/*
5368 	 * We can accept userspace's request for interrupt injection
5369 	 * as long as we have a place to store the interrupt number.
5370 	 * The actual injection will happen when the CPU is able to
5371 	 * deliver the interrupt.
5372 	 */
5373 	if (kvm_cpu_has_extint(vcpu))
5374 		return false;
5375 
5376 	/* Acknowledging ExtINT does not happen if LINT0 is masked.  */
5377 	return (!lapic_in_kernel(vcpu) ||
5378 		kvm_apic_accept_pic_intr(vcpu));
5379 }
5380 
kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu * vcpu)5381 static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
5382 {
5383 	/*
5384 	 * Do not cause an interrupt window exit if an exception
5385 	 * is pending or an event needs reinjection; userspace
5386 	 * might want to inject the interrupt manually using KVM_SET_REGS
5387 	 * or KVM_SET_SREGS.  For that to work, we must be at an
5388 	 * instruction boundary and with no events half-injected.
5389 	 */
5390 	return (kvm_arch_interrupt_allowed(vcpu) &&
5391 		kvm_cpu_accept_dm_intr(vcpu) &&
5392 		!kvm_event_needs_reinjection(vcpu) &&
5393 		!kvm_is_exception_pending(vcpu));
5394 }
5395 
kvm_vcpu_ioctl_interrupt(struct kvm_vcpu * vcpu,struct kvm_interrupt * irq)5396 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
5397 				    struct kvm_interrupt *irq)
5398 {
5399 	if (irq->irq >= KVM_NR_INTERRUPTS)
5400 		return -EINVAL;
5401 
5402 	if (!irqchip_in_kernel(vcpu->kvm)) {
5403 		kvm_queue_interrupt(vcpu, irq->irq, false);
5404 		kvm_make_request(KVM_REQ_EVENT, vcpu);
5405 		return 0;
5406 	}
5407 
5408 	/*
5409 	 * With in-kernel LAPIC, we only use this to inject EXTINT, so
5410 	 * fail for in-kernel 8259.
5411 	 */
5412 	if (pic_in_kernel(vcpu->kvm))
5413 		return -ENXIO;
5414 
5415 	if (vcpu->arch.pending_external_vector != -1)
5416 		return -EEXIST;
5417 
5418 	vcpu->arch.pending_external_vector = irq->irq;
5419 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5420 	return 0;
5421 }
5422 
kvm_vcpu_ioctl_nmi(struct kvm_vcpu * vcpu)5423 static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
5424 {
5425 	kvm_inject_nmi(vcpu);
5426 
5427 	return 0;
5428 }
5429 
vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu * vcpu,struct kvm_tpr_access_ctl * tac)5430 static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
5431 					   struct kvm_tpr_access_ctl *tac)
5432 {
5433 	if (tac->flags)
5434 		return -EINVAL;
5435 	vcpu->arch.tpr_access_reporting = !!tac->enabled;
5436 	return 0;
5437 }
5438 
kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu * vcpu,u64 mcg_cap)5439 static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
5440 					u64 mcg_cap)
5441 {
5442 	int r;
5443 	unsigned bank_num = mcg_cap & 0xff, bank;
5444 
5445 	r = -EINVAL;
5446 	if (!bank_num || bank_num > KVM_MAX_MCE_BANKS)
5447 		goto out;
5448 	if (mcg_cap & ~(kvm_caps.supported_mce_cap | 0xff | 0xff0000))
5449 		goto out;
5450 	r = 0;
5451 	vcpu->arch.mcg_cap = mcg_cap;
5452 	/* Init IA32_MCG_CTL to all 1s */
5453 	if (mcg_cap & MCG_CTL_P)
5454 		vcpu->arch.mcg_ctl = ~(u64)0;
5455 	/* Init IA32_MCi_CTL to all 1s, IA32_MCi_CTL2 to all 0s */
5456 	for (bank = 0; bank < bank_num; bank++) {
5457 		vcpu->arch.mce_banks[bank*4] = ~(u64)0;
5458 		if (mcg_cap & MCG_CMCI_P)
5459 			vcpu->arch.mci_ctl2_banks[bank] = 0;
5460 	}
5461 
5462 	kvm_apic_after_set_mcg_cap(vcpu);
5463 
5464 	kvm_x86_call(setup_mce)(vcpu);
5465 out:
5466 	return r;
5467 }
5468 
5469 /*
5470  * Validate this is an UCNA (uncorrectable no action) error by checking the
5471  * MCG_STATUS and MCi_STATUS registers:
5472  * - none of the bits for Machine Check Exceptions are set
5473  * - both the VAL (valid) and UC (uncorrectable) bits are set
5474  * MCI_STATUS_PCC - Processor Context Corrupted
5475  * MCI_STATUS_S - Signaled as a Machine Check Exception
5476  * MCI_STATUS_AR - Software recoverable Action Required
5477  */
is_ucna(struct kvm_x86_mce * mce)5478 static bool is_ucna(struct kvm_x86_mce *mce)
5479 {
5480 	return	!mce->mcg_status &&
5481 		!(mce->status & (MCI_STATUS_PCC | MCI_STATUS_S | MCI_STATUS_AR)) &&
5482 		(mce->status & MCI_STATUS_VAL) &&
5483 		(mce->status & MCI_STATUS_UC);
5484 }
5485 
kvm_vcpu_x86_set_ucna(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce,u64 * banks)5486 static int kvm_vcpu_x86_set_ucna(struct kvm_vcpu *vcpu, struct kvm_x86_mce *mce, u64* banks)
5487 {
5488 	u64 mcg_cap = vcpu->arch.mcg_cap;
5489 
5490 	banks[1] = mce->status;
5491 	banks[2] = mce->addr;
5492 	banks[3] = mce->misc;
5493 	vcpu->arch.mcg_status = mce->mcg_status;
5494 
5495 	if (!(mcg_cap & MCG_CMCI_P) ||
5496 	    !(vcpu->arch.mci_ctl2_banks[mce->bank] & MCI_CTL2_CMCI_EN))
5497 		return 0;
5498 
5499 	if (lapic_in_kernel(vcpu))
5500 		kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTCMCI);
5501 
5502 	return 0;
5503 }
5504 
kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu * vcpu,struct kvm_x86_mce * mce)5505 static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
5506 				      struct kvm_x86_mce *mce)
5507 {
5508 	u64 mcg_cap = vcpu->arch.mcg_cap;
5509 	unsigned bank_num = mcg_cap & 0xff;
5510 	u64 *banks = vcpu->arch.mce_banks;
5511 
5512 	if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
5513 		return -EINVAL;
5514 
5515 	banks += array_index_nospec(4 * mce->bank, 4 * bank_num);
5516 
5517 	if (is_ucna(mce))
5518 		return kvm_vcpu_x86_set_ucna(vcpu, mce, banks);
5519 
5520 	/*
5521 	 * if IA32_MCG_CTL is not all 1s, the uncorrected error
5522 	 * reporting is disabled
5523 	 */
5524 	if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
5525 	    vcpu->arch.mcg_ctl != ~(u64)0)
5526 		return 0;
5527 	/*
5528 	 * if IA32_MCi_CTL is not all 1s, the uncorrected error
5529 	 * reporting is disabled for the bank
5530 	 */
5531 	if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
5532 		return 0;
5533 	if (mce->status & MCI_STATUS_UC) {
5534 		if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
5535 		    !kvm_is_cr4_bit_set(vcpu, X86_CR4_MCE)) {
5536 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5537 			return 0;
5538 		}
5539 		if (banks[1] & MCI_STATUS_VAL)
5540 			mce->status |= MCI_STATUS_OVER;
5541 		banks[2] = mce->addr;
5542 		banks[3] = mce->misc;
5543 		vcpu->arch.mcg_status = mce->mcg_status;
5544 		banks[1] = mce->status;
5545 		kvm_queue_exception(vcpu, MC_VECTOR);
5546 	} else if (!(banks[1] & MCI_STATUS_VAL)
5547 		   || !(banks[1] & MCI_STATUS_UC)) {
5548 		if (banks[1] & MCI_STATUS_VAL)
5549 			mce->status |= MCI_STATUS_OVER;
5550 		banks[2] = mce->addr;
5551 		banks[3] = mce->misc;
5552 		banks[1] = mce->status;
5553 	} else
5554 		banks[1] |= MCI_STATUS_OVER;
5555 	return 0;
5556 }
5557 
kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5558 static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
5559 					       struct kvm_vcpu_events *events)
5560 {
5561 	struct kvm_queued_exception *ex;
5562 
5563 	process_nmi(vcpu);
5564 
5565 #ifdef CONFIG_KVM_SMM
5566 	if (kvm_check_request(KVM_REQ_SMI, vcpu))
5567 		process_smi(vcpu);
5568 #endif
5569 
5570 	/*
5571 	 * KVM's ABI only allows for one exception to be migrated.  Luckily,
5572 	 * the only time there can be two queued exceptions is if there's a
5573 	 * non-exiting _injected_ exception, and a pending exiting exception.
5574 	 * In that case, ignore the VM-Exiting exception as it's an extension
5575 	 * of the injected exception.
5576 	 */
5577 	if (vcpu->arch.exception_vmexit.pending &&
5578 	    !vcpu->arch.exception.pending &&
5579 	    !vcpu->arch.exception.injected)
5580 		ex = &vcpu->arch.exception_vmexit;
5581 	else
5582 		ex = &vcpu->arch.exception;
5583 
5584 	/*
5585 	 * In guest mode, payload delivery should be deferred if the exception
5586 	 * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1
5587 	 * intercepts #PF, ditto for DR6 and #DBs.  If the per-VM capability,
5588 	 * KVM_CAP_EXCEPTION_PAYLOAD, is not set, userspace may or may not
5589 	 * propagate the payload and so it cannot be safely deferred.  Deliver
5590 	 * the payload if the capability hasn't been requested.
5591 	 */
5592 	if (!vcpu->kvm->arch.exception_payload_enabled &&
5593 	    ex->pending && ex->has_payload)
5594 		kvm_deliver_exception_payload(vcpu, ex);
5595 
5596 	memset(events, 0, sizeof(*events));
5597 
5598 	/*
5599 	 * The API doesn't provide the instruction length for software
5600 	 * exceptions, so don't report them. As long as the guest RIP
5601 	 * isn't advanced, we should expect to encounter the exception
5602 	 * again.
5603 	 */
5604 	if (!kvm_exception_is_soft(ex->vector)) {
5605 		events->exception.injected = ex->injected;
5606 		events->exception.pending = ex->pending;
5607 		/*
5608 		 * For ABI compatibility, deliberately conflate
5609 		 * pending and injected exceptions when
5610 		 * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
5611 		 */
5612 		if (!vcpu->kvm->arch.exception_payload_enabled)
5613 			events->exception.injected |= ex->pending;
5614 	}
5615 	events->exception.nr = ex->vector;
5616 	events->exception.has_error_code = ex->has_error_code;
5617 	events->exception.error_code = ex->error_code;
5618 	events->exception_has_payload = ex->has_payload;
5619 	events->exception_payload = ex->payload;
5620 
5621 	events->interrupt.injected =
5622 		vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
5623 	events->interrupt.nr = vcpu->arch.interrupt.nr;
5624 	events->interrupt.shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
5625 
5626 	events->nmi.injected = vcpu->arch.nmi_injected;
5627 	events->nmi.pending = kvm_get_nr_pending_nmis(vcpu);
5628 	events->nmi.masked = kvm_x86_call(get_nmi_mask)(vcpu);
5629 
5630 	/* events->sipi_vector is never valid when reporting to user space */
5631 
5632 #ifdef CONFIG_KVM_SMM
5633 	events->smi.smm = is_smm(vcpu);
5634 	events->smi.pending = vcpu->arch.smi_pending;
5635 	events->smi.smm_inside_nmi =
5636 		!!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
5637 #endif
5638 	events->smi.latched_init = kvm_lapic_latched_init(vcpu);
5639 
5640 	events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
5641 			 | KVM_VCPUEVENT_VALID_SHADOW
5642 			 | KVM_VCPUEVENT_VALID_SMM);
5643 	if (vcpu->kvm->arch.exception_payload_enabled)
5644 		events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
5645 	if (vcpu->kvm->arch.triple_fault_event) {
5646 		events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5647 		events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
5648 	}
5649 }
5650 
kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)5651 static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
5652 					      struct kvm_vcpu_events *events)
5653 {
5654 	if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
5655 			      | KVM_VCPUEVENT_VALID_SIPI_VECTOR
5656 			      | KVM_VCPUEVENT_VALID_SHADOW
5657 			      | KVM_VCPUEVENT_VALID_SMM
5658 			      | KVM_VCPUEVENT_VALID_PAYLOAD
5659 			      | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
5660 		return -EINVAL;
5661 
5662 	if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
5663 		if (!vcpu->kvm->arch.exception_payload_enabled)
5664 			return -EINVAL;
5665 		if (events->exception.pending)
5666 			events->exception.injected = 0;
5667 		else
5668 			events->exception_has_payload = 0;
5669 	} else {
5670 		events->exception.pending = 0;
5671 		events->exception_has_payload = 0;
5672 	}
5673 
5674 	if ((events->exception.injected || events->exception.pending) &&
5675 	    (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
5676 		return -EINVAL;
5677 
5678 	process_nmi(vcpu);
5679 
5680 	/*
5681 	 * Flag that userspace is stuffing an exception, the next KVM_RUN will
5682 	 * morph the exception to a VM-Exit if appropriate.  Do this only for
5683 	 * pending exceptions, already-injected exceptions are not subject to
5684 	 * intercpetion.  Note, userspace that conflates pending and injected
5685 	 * is hosed, and will incorrectly convert an injected exception into a
5686 	 * pending exception, which in turn may cause a spurious VM-Exit.
5687 	 */
5688 	vcpu->arch.exception_from_userspace = events->exception.pending;
5689 
5690 	vcpu->arch.exception_vmexit.pending = false;
5691 
5692 	vcpu->arch.exception.injected = events->exception.injected;
5693 	vcpu->arch.exception.pending = events->exception.pending;
5694 	vcpu->arch.exception.vector = events->exception.nr;
5695 	vcpu->arch.exception.has_error_code = events->exception.has_error_code;
5696 	vcpu->arch.exception.error_code = events->exception.error_code;
5697 	vcpu->arch.exception.has_payload = events->exception_has_payload;
5698 	vcpu->arch.exception.payload = events->exception_payload;
5699 
5700 	vcpu->arch.interrupt.injected = events->interrupt.injected;
5701 	vcpu->arch.interrupt.nr = events->interrupt.nr;
5702 	vcpu->arch.interrupt.soft = events->interrupt.soft;
5703 	if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
5704 		kvm_x86_call(set_interrupt_shadow)(vcpu,
5705 						   events->interrupt.shadow);
5706 
5707 	vcpu->arch.nmi_injected = events->nmi.injected;
5708 	if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING) {
5709 		vcpu->arch.nmi_pending = 0;
5710 		atomic_set(&vcpu->arch.nmi_queued, events->nmi.pending);
5711 		if (events->nmi.pending)
5712 			kvm_make_request(KVM_REQ_NMI, vcpu);
5713 	}
5714 	kvm_x86_call(set_nmi_mask)(vcpu, events->nmi.masked);
5715 
5716 	if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
5717 	    lapic_in_kernel(vcpu))
5718 		vcpu->arch.apic->sipi_vector = events->sipi_vector;
5719 
5720 	if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
5721 #ifdef CONFIG_KVM_SMM
5722 		if (!!(vcpu->arch.hflags & HF_SMM_MASK) != events->smi.smm) {
5723 			kvm_leave_nested(vcpu);
5724 			kvm_smm_changed(vcpu, events->smi.smm);
5725 		}
5726 
5727 		vcpu->arch.smi_pending = events->smi.pending;
5728 
5729 		if (events->smi.smm) {
5730 			if (events->smi.smm_inside_nmi)
5731 				vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
5732 			else
5733 				vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
5734 		}
5735 
5736 #else
5737 		if (events->smi.smm || events->smi.pending ||
5738 		    events->smi.smm_inside_nmi)
5739 			return -EINVAL;
5740 #endif
5741 
5742 		if (lapic_in_kernel(vcpu)) {
5743 			if (events->smi.latched_init)
5744 				set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5745 			else
5746 				clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
5747 		}
5748 	}
5749 
5750 	if (events->flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT) {
5751 		if (!vcpu->kvm->arch.triple_fault_event)
5752 			return -EINVAL;
5753 		if (events->triple_fault.pending)
5754 			kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5755 		else
5756 			kvm_clear_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5757 	}
5758 
5759 	kvm_make_request(KVM_REQ_EVENT, vcpu);
5760 
5761 	return 0;
5762 }
5763 
kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5764 static int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
5765 					    struct kvm_debugregs *dbgregs)
5766 {
5767 	unsigned int i;
5768 
5769 	if (vcpu->kvm->arch.has_protected_state &&
5770 	    vcpu->arch.guest_state_protected)
5771 		return -EINVAL;
5772 
5773 	memset(dbgregs, 0, sizeof(*dbgregs));
5774 
5775 	BUILD_BUG_ON(ARRAY_SIZE(vcpu->arch.db) != ARRAY_SIZE(dbgregs->db));
5776 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5777 		dbgregs->db[i] = vcpu->arch.db[i];
5778 
5779 	dbgregs->dr6 = vcpu->arch.dr6;
5780 	dbgregs->dr7 = vcpu->arch.dr7;
5781 	return 0;
5782 }
5783 
kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu * vcpu,struct kvm_debugregs * dbgregs)5784 static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
5785 					    struct kvm_debugregs *dbgregs)
5786 {
5787 	unsigned int i;
5788 
5789 	if (vcpu->kvm->arch.has_protected_state &&
5790 	    vcpu->arch.guest_state_protected)
5791 		return -EINVAL;
5792 
5793 	if (dbgregs->flags)
5794 		return -EINVAL;
5795 
5796 	if (!kvm_dr6_valid(dbgregs->dr6))
5797 		return -EINVAL;
5798 	if (!kvm_dr7_valid(dbgregs->dr7))
5799 		return -EINVAL;
5800 
5801 	for (i = 0; i < ARRAY_SIZE(vcpu->arch.db); i++)
5802 		vcpu->arch.db[i] = dbgregs->db[i];
5803 
5804 	kvm_update_dr0123(vcpu);
5805 	vcpu->arch.dr6 = dbgregs->dr6;
5806 	vcpu->arch.dr7 = dbgregs->dr7;
5807 	kvm_update_dr7(vcpu);
5808 
5809 	return 0;
5810 }
5811 
5812 
kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu * vcpu,u8 * state,unsigned int size)5813 static int kvm_vcpu_ioctl_x86_get_xsave2(struct kvm_vcpu *vcpu,
5814 					 u8 *state, unsigned int size)
5815 {
5816 	/*
5817 	 * Only copy state for features that are enabled for the guest.  The
5818 	 * state itself isn't problematic, but setting bits in the header for
5819 	 * features that are supported in *this* host but not exposed to the
5820 	 * guest can result in KVM_SET_XSAVE failing when live migrating to a
5821 	 * compatible host without the features that are NOT exposed to the
5822 	 * guest.
5823 	 *
5824 	 * FP+SSE can always be saved/restored via KVM_{G,S}ET_XSAVE, even if
5825 	 * XSAVE/XCRO are not exposed to the guest, and even if XSAVE isn't
5826 	 * supported by the host.
5827 	 */
5828 	u64 supported_xcr0 = vcpu->arch.guest_supported_xcr0 |
5829 			     XFEATURE_MASK_FPSSE;
5830 
5831 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5832 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5833 
5834 	fpu_copy_guest_fpstate_to_uabi(&vcpu->arch.guest_fpu, state, size,
5835 				       supported_xcr0, vcpu->arch.pkru);
5836 	return 0;
5837 }
5838 
kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5839 static int kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
5840 					struct kvm_xsave *guest_xsave)
5841 {
5842 	return kvm_vcpu_ioctl_x86_get_xsave2(vcpu, (void *)guest_xsave->region,
5843 					     sizeof(guest_xsave->region));
5844 }
5845 
kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu * vcpu,struct kvm_xsave * guest_xsave)5846 static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
5847 					struct kvm_xsave *guest_xsave)
5848 {
5849 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
5850 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
5851 
5852 	return fpu_copy_uabi_to_guest_fpstate(&vcpu->arch.guest_fpu,
5853 					      guest_xsave->region,
5854 					      kvm_caps.supported_xcr0,
5855 					      &vcpu->arch.pkru);
5856 }
5857 
kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5858 static int kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
5859 				       struct kvm_xcrs *guest_xcrs)
5860 {
5861 	if (vcpu->kvm->arch.has_protected_state &&
5862 	    vcpu->arch.guest_state_protected)
5863 		return -EINVAL;
5864 
5865 	if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
5866 		guest_xcrs->nr_xcrs = 0;
5867 		return 0;
5868 	}
5869 
5870 	guest_xcrs->nr_xcrs = 1;
5871 	guest_xcrs->flags = 0;
5872 	guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
5873 	guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
5874 	return 0;
5875 }
5876 
kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu * vcpu,struct kvm_xcrs * guest_xcrs)5877 static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
5878 				       struct kvm_xcrs *guest_xcrs)
5879 {
5880 	int i, r = 0;
5881 
5882 	if (vcpu->kvm->arch.has_protected_state &&
5883 	    vcpu->arch.guest_state_protected)
5884 		return -EINVAL;
5885 
5886 	if (!boot_cpu_has(X86_FEATURE_XSAVE))
5887 		return -EINVAL;
5888 
5889 	if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
5890 		return -EINVAL;
5891 
5892 	for (i = 0; i < guest_xcrs->nr_xcrs; i++)
5893 		/* Only support XCR0 currently */
5894 		if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
5895 			r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
5896 				guest_xcrs->xcrs[i].value);
5897 			break;
5898 		}
5899 	if (r)
5900 		r = -EINVAL;
5901 	return r;
5902 }
5903 
5904 /*
5905  * kvm_set_guest_paused() indicates to the guest kernel that it has been
5906  * stopped by the hypervisor.  This function will be called from the host only.
5907  * EINVAL is returned when the host attempts to set the flag for a guest that
5908  * does not support pv clocks.
5909  */
kvm_set_guest_paused(struct kvm_vcpu * vcpu)5910 static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
5911 {
5912 	if (!vcpu->arch.pv_time.active)
5913 		return -EINVAL;
5914 	vcpu->arch.pvclock_set_guest_stopped_request = true;
5915 	kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
5916 	return 0;
5917 }
5918 
kvm_arch_tsc_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5919 static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcpu,
5920 				 struct kvm_device_attr *attr)
5921 {
5922 	int r;
5923 
5924 	switch (attr->attr) {
5925 	case KVM_VCPU_TSC_OFFSET:
5926 		r = 0;
5927 		break;
5928 	default:
5929 		r = -ENXIO;
5930 	}
5931 
5932 	return r;
5933 }
5934 
kvm_arch_tsc_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5935 static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vcpu,
5936 				 struct kvm_device_attr *attr)
5937 {
5938 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5939 	int r;
5940 
5941 	switch (attr->attr) {
5942 	case KVM_VCPU_TSC_OFFSET:
5943 		r = -EFAULT;
5944 		if (put_user(vcpu->arch.l1_tsc_offset, uaddr))
5945 			break;
5946 		r = 0;
5947 		break;
5948 	default:
5949 		r = -ENXIO;
5950 	}
5951 
5952 	return r;
5953 }
5954 
kvm_arch_tsc_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)5955 static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcpu,
5956 				 struct kvm_device_attr *attr)
5957 {
5958 	u64 __user *uaddr = u64_to_user_ptr(attr->addr);
5959 	struct kvm *kvm = vcpu->kvm;
5960 	int r;
5961 
5962 	switch (attr->attr) {
5963 	case KVM_VCPU_TSC_OFFSET: {
5964 		u64 offset, tsc, ns;
5965 		unsigned long flags;
5966 		bool matched;
5967 
5968 		r = -EFAULT;
5969 		if (get_user(offset, uaddr))
5970 			break;
5971 
5972 		raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
5973 
5974 		matched = (vcpu->arch.virtual_tsc_khz &&
5975 			   kvm->arch.last_tsc_khz == vcpu->arch.virtual_tsc_khz &&
5976 			   kvm->arch.last_tsc_offset == offset);
5977 
5978 		tsc = kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset;
5979 		ns = get_kvmclock_base_ns();
5980 
5981 		__kvm_synchronize_tsc(vcpu, offset, tsc, ns, matched, true);
5982 		raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
5983 
5984 		r = 0;
5985 		break;
5986 	}
5987 	default:
5988 		r = -ENXIO;
5989 	}
5990 
5991 	return r;
5992 }
5993 
kvm_vcpu_ioctl_device_attr(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)5994 static int kvm_vcpu_ioctl_device_attr(struct kvm_vcpu *vcpu,
5995 				      unsigned int ioctl,
5996 				      void __user *argp)
5997 {
5998 	struct kvm_device_attr attr;
5999 	int r;
6000 
6001 	if (copy_from_user(&attr, argp, sizeof(attr)))
6002 		return -EFAULT;
6003 
6004 	if (attr.group != KVM_VCPU_TSC_CTRL)
6005 		return -ENXIO;
6006 
6007 	switch (ioctl) {
6008 	case KVM_HAS_DEVICE_ATTR:
6009 		r = kvm_arch_tsc_has_attr(vcpu, &attr);
6010 		break;
6011 	case KVM_GET_DEVICE_ATTR:
6012 		r = kvm_arch_tsc_get_attr(vcpu, &attr);
6013 		break;
6014 	case KVM_SET_DEVICE_ATTR:
6015 		r = kvm_arch_tsc_set_attr(vcpu, &attr);
6016 		break;
6017 	}
6018 
6019 	return r;
6020 }
6021 
kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu * vcpu,struct kvm_enable_cap * cap)6022 static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
6023 				     struct kvm_enable_cap *cap)
6024 {
6025 	if (cap->flags)
6026 		return -EINVAL;
6027 
6028 	switch (cap->cap) {
6029 #ifdef CONFIG_KVM_HYPERV
6030 	case KVM_CAP_HYPERV_SYNIC2:
6031 		if (cap->args[0])
6032 			return -EINVAL;
6033 		fallthrough;
6034 
6035 	case KVM_CAP_HYPERV_SYNIC:
6036 		if (!irqchip_in_kernel(vcpu->kvm))
6037 			return -EINVAL;
6038 		return kvm_hv_activate_synic(vcpu, cap->cap ==
6039 					     KVM_CAP_HYPERV_SYNIC2);
6040 	case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
6041 		{
6042 			int r;
6043 			uint16_t vmcs_version;
6044 			void __user *user_ptr;
6045 
6046 			if (!kvm_x86_ops.nested_ops->enable_evmcs)
6047 				return -ENOTTY;
6048 			r = kvm_x86_ops.nested_ops->enable_evmcs(vcpu, &vmcs_version);
6049 			if (!r) {
6050 				user_ptr = (void __user *)(uintptr_t)cap->args[0];
6051 				if (copy_to_user(user_ptr, &vmcs_version,
6052 						 sizeof(vmcs_version)))
6053 					r = -EFAULT;
6054 			}
6055 			return r;
6056 		}
6057 	case KVM_CAP_HYPERV_DIRECT_TLBFLUSH:
6058 		if (!kvm_x86_ops.enable_l2_tlb_flush)
6059 			return -ENOTTY;
6060 
6061 		return kvm_x86_call(enable_l2_tlb_flush)(vcpu);
6062 
6063 	case KVM_CAP_HYPERV_ENFORCE_CPUID:
6064 		return kvm_hv_set_enforce_cpuid(vcpu, cap->args[0]);
6065 #endif
6066 
6067 	case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
6068 		vcpu->arch.pv_cpuid.enforce = cap->args[0];
6069 		return 0;
6070 	default:
6071 		return -EINVAL;
6072 	}
6073 }
6074 
6075 struct kvm_x86_reg_id {
6076 	__u32 index;
6077 	__u8  type;
6078 	__u8  rsvd1;
6079 	__u8  rsvd2:4;
6080 	__u8  size:4;
6081 	__u8  x86;
6082 };
6083 
kvm_translate_kvm_reg(struct kvm_vcpu * vcpu,struct kvm_x86_reg_id * reg)6084 static int kvm_translate_kvm_reg(struct kvm_vcpu *vcpu,
6085 				 struct kvm_x86_reg_id *reg)
6086 {
6087 	switch (reg->index) {
6088 	case KVM_REG_GUEST_SSP:
6089 		/*
6090 		 * FIXME: If host-initiated accesses are ever exempted from
6091 		 * ignore_msrs (in kvm_do_msr_access()), drop this manual check
6092 		 * and rely on KVM's standard checks to reject accesses to regs
6093 		 * that don't exist.
6094 		 */
6095 		if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK))
6096 			return -EINVAL;
6097 
6098 		reg->type = KVM_X86_REG_TYPE_MSR;
6099 		reg->index = MSR_KVM_INTERNAL_GUEST_SSP;
6100 		break;
6101 	default:
6102 		return -EINVAL;
6103 	}
6104 	return 0;
6105 }
6106 
kvm_get_one_msr(struct kvm_vcpu * vcpu,u32 msr,u64 __user * user_val)6107 static int kvm_get_one_msr(struct kvm_vcpu *vcpu, u32 msr, u64 __user *user_val)
6108 {
6109 	u64 val;
6110 
6111 	if (do_get_msr(vcpu, msr, &val))
6112 		return -EINVAL;
6113 
6114 	if (put_user(val, user_val))
6115 		return -EFAULT;
6116 
6117 	return 0;
6118 }
6119 
kvm_set_one_msr(struct kvm_vcpu * vcpu,u32 msr,u64 __user * user_val)6120 static int kvm_set_one_msr(struct kvm_vcpu *vcpu, u32 msr, u64 __user *user_val)
6121 {
6122 	u64 val;
6123 
6124 	if (get_user(val, user_val))
6125 		return -EFAULT;
6126 
6127 	if (do_set_msr(vcpu, msr, &val))
6128 		return -EINVAL;
6129 
6130 	return 0;
6131 }
6132 
kvm_get_set_one_reg(struct kvm_vcpu * vcpu,unsigned int ioctl,void __user * argp)6133 static int kvm_get_set_one_reg(struct kvm_vcpu *vcpu, unsigned int ioctl,
6134 			       void __user *argp)
6135 {
6136 	struct kvm_one_reg one_reg;
6137 	struct kvm_x86_reg_id *reg;
6138 	u64 __user *user_val;
6139 	bool load_fpu;
6140 	int r;
6141 
6142 	if (copy_from_user(&one_reg, argp, sizeof(one_reg)))
6143 		return -EFAULT;
6144 
6145 	if ((one_reg.id & KVM_REG_ARCH_MASK) != KVM_REG_X86)
6146 		return -EINVAL;
6147 
6148 	reg = (struct kvm_x86_reg_id *)&one_reg.id;
6149 	if (reg->rsvd1 || reg->rsvd2)
6150 		return -EINVAL;
6151 
6152 	if (reg->type == KVM_X86_REG_TYPE_KVM) {
6153 		r = kvm_translate_kvm_reg(vcpu, reg);
6154 		if (r)
6155 			return r;
6156 	}
6157 
6158 	if (reg->type != KVM_X86_REG_TYPE_MSR)
6159 		return -EINVAL;
6160 
6161 	if ((one_reg.id & KVM_REG_SIZE_MASK) != KVM_REG_SIZE_U64)
6162 		return -EINVAL;
6163 
6164 	guard(srcu)(&vcpu->kvm->srcu);
6165 
6166 	load_fpu = is_xstate_managed_msr(vcpu, reg->index);
6167 	if (load_fpu)
6168 		kvm_load_guest_fpu(vcpu);
6169 
6170 	user_val = u64_to_user_ptr(one_reg.addr);
6171 	if (ioctl == KVM_GET_ONE_REG)
6172 		r = kvm_get_one_msr(vcpu, reg->index, user_val);
6173 	else
6174 		r = kvm_set_one_msr(vcpu, reg->index, user_val);
6175 
6176 	if (load_fpu)
6177 		kvm_put_guest_fpu(vcpu);
6178 	return r;
6179 }
6180 
kvm_get_reg_list(struct kvm_vcpu * vcpu,struct kvm_reg_list __user * user_list)6181 static int kvm_get_reg_list(struct kvm_vcpu *vcpu,
6182 			    struct kvm_reg_list __user *user_list)
6183 {
6184 	u64 nr_regs = guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) ? 1 : 0;
6185 	u64 user_nr_regs;
6186 
6187 	if (get_user(user_nr_regs, &user_list->n))
6188 		return -EFAULT;
6189 
6190 	if (put_user(nr_regs, &user_list->n))
6191 		return -EFAULT;
6192 
6193 	if (user_nr_regs < nr_regs)
6194 		return -E2BIG;
6195 
6196 	if (nr_regs &&
6197 	    put_user(KVM_X86_REG_KVM(KVM_REG_GUEST_SSP), &user_list->reg[0]))
6198 		return -EFAULT;
6199 
6200 	return 0;
6201 }
6202 
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)6203 long kvm_arch_vcpu_ioctl(struct file *filp,
6204 			 unsigned int ioctl, unsigned long arg)
6205 {
6206 	struct kvm_vcpu *vcpu = filp->private_data;
6207 	void __user *argp = (void __user *)arg;
6208 	int r;
6209 	union {
6210 		struct kvm_sregs2 *sregs2;
6211 		struct kvm_lapic_state *lapic;
6212 		struct kvm_xsave *xsave;
6213 		struct kvm_xcrs *xcrs;
6214 		void *buffer;
6215 	} u;
6216 
6217 	vcpu_load(vcpu);
6218 
6219 	u.buffer = NULL;
6220 	switch (ioctl) {
6221 	case KVM_GET_LAPIC: {
6222 		r = -EINVAL;
6223 		if (!lapic_in_kernel(vcpu))
6224 			goto out;
6225 		u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
6226 
6227 		r = -ENOMEM;
6228 		if (!u.lapic)
6229 			goto out;
6230 		r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
6231 		if (r)
6232 			goto out;
6233 		r = -EFAULT;
6234 		if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
6235 			goto out;
6236 		r = 0;
6237 		break;
6238 	}
6239 	case KVM_SET_LAPIC: {
6240 		r = -EINVAL;
6241 		if (!lapic_in_kernel(vcpu))
6242 			goto out;
6243 		u.lapic = memdup_user(argp, sizeof(*u.lapic));
6244 		if (IS_ERR(u.lapic)) {
6245 			r = PTR_ERR(u.lapic);
6246 			goto out_nofree;
6247 		}
6248 
6249 		r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
6250 		break;
6251 	}
6252 	case KVM_INTERRUPT: {
6253 		struct kvm_interrupt irq;
6254 
6255 		r = -EFAULT;
6256 		if (copy_from_user(&irq, argp, sizeof(irq)))
6257 			goto out;
6258 		r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
6259 		break;
6260 	}
6261 	case KVM_NMI: {
6262 		r = kvm_vcpu_ioctl_nmi(vcpu);
6263 		break;
6264 	}
6265 	case KVM_SMI: {
6266 		r = kvm_inject_smi(vcpu);
6267 		break;
6268 	}
6269 	case KVM_SET_CPUID: {
6270 		struct kvm_cpuid __user *cpuid_arg = argp;
6271 		struct kvm_cpuid cpuid;
6272 
6273 		r = -EFAULT;
6274 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6275 			goto out;
6276 		r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
6277 		break;
6278 	}
6279 	case KVM_SET_CPUID2: {
6280 		struct kvm_cpuid2 __user *cpuid_arg = argp;
6281 		struct kvm_cpuid2 cpuid;
6282 
6283 		r = -EFAULT;
6284 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6285 			goto out;
6286 		r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
6287 					      cpuid_arg->entries);
6288 		break;
6289 	}
6290 	case KVM_GET_CPUID2: {
6291 		struct kvm_cpuid2 __user *cpuid_arg = argp;
6292 		struct kvm_cpuid2 cpuid;
6293 
6294 		r = -EFAULT;
6295 		if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
6296 			goto out;
6297 		r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
6298 					      cpuid_arg->entries);
6299 		if (r)
6300 			goto out;
6301 		r = -EFAULT;
6302 		if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
6303 			goto out;
6304 		r = 0;
6305 		break;
6306 	}
6307 	case KVM_GET_MSRS: {
6308 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
6309 		r = msr_io(vcpu, argp, do_get_msr, 1);
6310 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6311 		break;
6312 	}
6313 	case KVM_SET_MSRS: {
6314 		int idx = srcu_read_lock(&vcpu->kvm->srcu);
6315 		r = msr_io(vcpu, argp, do_set_msr, 0);
6316 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6317 		break;
6318 	}
6319 	case KVM_GET_ONE_REG:
6320 	case KVM_SET_ONE_REG:
6321 		r = kvm_get_set_one_reg(vcpu, ioctl, argp);
6322 		break;
6323 	case KVM_GET_REG_LIST:
6324 		r = kvm_get_reg_list(vcpu, argp);
6325 		break;
6326 	case KVM_TPR_ACCESS_REPORTING: {
6327 		struct kvm_tpr_access_ctl tac;
6328 
6329 		r = -EFAULT;
6330 		if (copy_from_user(&tac, argp, sizeof(tac)))
6331 			goto out;
6332 		r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
6333 		if (r)
6334 			goto out;
6335 		r = -EFAULT;
6336 		if (copy_to_user(argp, &tac, sizeof(tac)))
6337 			goto out;
6338 		r = 0;
6339 		break;
6340 	};
6341 	case KVM_SET_VAPIC_ADDR: {
6342 		struct kvm_vapic_addr va;
6343 		int idx;
6344 
6345 		r = -EINVAL;
6346 		if (!lapic_in_kernel(vcpu))
6347 			goto out;
6348 		r = -EFAULT;
6349 		if (copy_from_user(&va, argp, sizeof(va)))
6350 			goto out;
6351 		idx = srcu_read_lock(&vcpu->kvm->srcu);
6352 		r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
6353 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6354 		break;
6355 	}
6356 	case KVM_X86_SETUP_MCE: {
6357 		u64 mcg_cap;
6358 
6359 		r = -EFAULT;
6360 		if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
6361 			goto out;
6362 		r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
6363 		break;
6364 	}
6365 	case KVM_X86_SET_MCE: {
6366 		struct kvm_x86_mce mce;
6367 
6368 		r = -EFAULT;
6369 		if (copy_from_user(&mce, argp, sizeof(mce)))
6370 			goto out;
6371 		r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
6372 		break;
6373 	}
6374 	case KVM_GET_VCPU_EVENTS: {
6375 		struct kvm_vcpu_events events;
6376 
6377 		kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
6378 
6379 		r = -EFAULT;
6380 		if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
6381 			break;
6382 		r = 0;
6383 		break;
6384 	}
6385 	case KVM_SET_VCPU_EVENTS: {
6386 		struct kvm_vcpu_events events;
6387 
6388 		r = -EFAULT;
6389 		if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
6390 			break;
6391 
6392 		kvm_vcpu_srcu_read_lock(vcpu);
6393 		r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
6394 		kvm_vcpu_srcu_read_unlock(vcpu);
6395 		break;
6396 	}
6397 	case KVM_GET_DEBUGREGS: {
6398 		struct kvm_debugregs dbgregs;
6399 
6400 		r = kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
6401 		if (r < 0)
6402 			break;
6403 
6404 		r = -EFAULT;
6405 		if (copy_to_user(argp, &dbgregs,
6406 				 sizeof(struct kvm_debugregs)))
6407 			break;
6408 		r = 0;
6409 		break;
6410 	}
6411 	case KVM_SET_DEBUGREGS: {
6412 		struct kvm_debugregs dbgregs;
6413 
6414 		r = -EFAULT;
6415 		if (copy_from_user(&dbgregs, argp,
6416 				   sizeof(struct kvm_debugregs)))
6417 			break;
6418 
6419 		r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
6420 		break;
6421 	}
6422 	case KVM_GET_XSAVE: {
6423 		r = -EINVAL;
6424 		if (vcpu->arch.guest_fpu.uabi_size > sizeof(struct kvm_xsave))
6425 			break;
6426 
6427 		u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
6428 		r = -ENOMEM;
6429 		if (!u.xsave)
6430 			break;
6431 
6432 		r = kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
6433 		if (r < 0)
6434 			break;
6435 
6436 		r = -EFAULT;
6437 		if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
6438 			break;
6439 		r = 0;
6440 		break;
6441 	}
6442 	case KVM_SET_XSAVE: {
6443 		int size = vcpu->arch.guest_fpu.uabi_size;
6444 
6445 		u.xsave = memdup_user(argp, size);
6446 		if (IS_ERR(u.xsave)) {
6447 			r = PTR_ERR(u.xsave);
6448 			goto out_nofree;
6449 		}
6450 
6451 		r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
6452 		break;
6453 	}
6454 
6455 	case KVM_GET_XSAVE2: {
6456 		int size = vcpu->arch.guest_fpu.uabi_size;
6457 
6458 		u.xsave = kzalloc(size, GFP_KERNEL);
6459 		r = -ENOMEM;
6460 		if (!u.xsave)
6461 			break;
6462 
6463 		r = kvm_vcpu_ioctl_x86_get_xsave2(vcpu, u.buffer, size);
6464 		if (r < 0)
6465 			break;
6466 
6467 		r = -EFAULT;
6468 		if (copy_to_user(argp, u.xsave, size))
6469 			break;
6470 
6471 		r = 0;
6472 		break;
6473 	}
6474 
6475 	case KVM_GET_XCRS: {
6476 		u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
6477 		r = -ENOMEM;
6478 		if (!u.xcrs)
6479 			break;
6480 
6481 		r = kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
6482 		if (r < 0)
6483 			break;
6484 
6485 		r = -EFAULT;
6486 		if (copy_to_user(argp, u.xcrs,
6487 				 sizeof(struct kvm_xcrs)))
6488 			break;
6489 		r = 0;
6490 		break;
6491 	}
6492 	case KVM_SET_XCRS: {
6493 		u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
6494 		if (IS_ERR(u.xcrs)) {
6495 			r = PTR_ERR(u.xcrs);
6496 			goto out_nofree;
6497 		}
6498 
6499 		r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
6500 		break;
6501 	}
6502 	case KVM_SET_TSC_KHZ: {
6503 		u32 user_tsc_khz;
6504 
6505 		r = -EINVAL;
6506 
6507 		if (vcpu->arch.guest_tsc_protected)
6508 			goto out;
6509 
6510 		user_tsc_khz = (u32)arg;
6511 
6512 		if (kvm_caps.has_tsc_control &&
6513 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
6514 			goto out;
6515 
6516 		if (user_tsc_khz == 0)
6517 			user_tsc_khz = tsc_khz;
6518 
6519 		if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
6520 			r = 0;
6521 
6522 		goto out;
6523 	}
6524 	case KVM_GET_TSC_KHZ: {
6525 		r = vcpu->arch.virtual_tsc_khz;
6526 		goto out;
6527 	}
6528 	case KVM_KVMCLOCK_CTRL: {
6529 		r = kvm_set_guest_paused(vcpu);
6530 		goto out;
6531 	}
6532 	case KVM_ENABLE_CAP: {
6533 		struct kvm_enable_cap cap;
6534 
6535 		r = -EFAULT;
6536 		if (copy_from_user(&cap, argp, sizeof(cap)))
6537 			goto out;
6538 		r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
6539 		break;
6540 	}
6541 	case KVM_GET_NESTED_STATE: {
6542 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
6543 		u32 user_data_size;
6544 
6545 		r = -EINVAL;
6546 		if (!kvm_x86_ops.nested_ops->get_state)
6547 			break;
6548 
6549 		BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
6550 		r = -EFAULT;
6551 		if (get_user(user_data_size, &user_kvm_nested_state->size))
6552 			break;
6553 
6554 		r = kvm_x86_ops.nested_ops->get_state(vcpu, user_kvm_nested_state,
6555 						     user_data_size);
6556 		if (r < 0)
6557 			break;
6558 
6559 		if (r > user_data_size) {
6560 			if (put_user(r, &user_kvm_nested_state->size))
6561 				r = -EFAULT;
6562 			else
6563 				r = -E2BIG;
6564 			break;
6565 		}
6566 
6567 		r = 0;
6568 		break;
6569 	}
6570 	case KVM_SET_NESTED_STATE: {
6571 		struct kvm_nested_state __user *user_kvm_nested_state = argp;
6572 		struct kvm_nested_state kvm_state;
6573 		int idx;
6574 
6575 		r = -EINVAL;
6576 		if (!kvm_x86_ops.nested_ops->set_state)
6577 			break;
6578 
6579 		r = -EFAULT;
6580 		if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
6581 			break;
6582 
6583 		r = -EINVAL;
6584 		if (kvm_state.size < sizeof(kvm_state))
6585 			break;
6586 
6587 		if (kvm_state.flags &
6588 		    ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
6589 		      | KVM_STATE_NESTED_EVMCS | KVM_STATE_NESTED_MTF_PENDING
6590 		      | KVM_STATE_NESTED_GIF_SET))
6591 			break;
6592 
6593 		/* nested_run_pending implies guest_mode.  */
6594 		if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
6595 		    && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
6596 			break;
6597 
6598 		idx = srcu_read_lock(&vcpu->kvm->srcu);
6599 		r = kvm_x86_ops.nested_ops->set_state(vcpu, user_kvm_nested_state, &kvm_state);
6600 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
6601 		break;
6602 	}
6603 #ifdef CONFIG_KVM_HYPERV
6604 	case KVM_GET_SUPPORTED_HV_CPUID:
6605 		r = kvm_ioctl_get_supported_hv_cpuid(vcpu, argp);
6606 		break;
6607 #endif
6608 #ifdef CONFIG_KVM_XEN
6609 	case KVM_XEN_VCPU_GET_ATTR: {
6610 		struct kvm_xen_vcpu_attr xva;
6611 
6612 		r = -EFAULT;
6613 		if (copy_from_user(&xva, argp, sizeof(xva)))
6614 			goto out;
6615 		r = kvm_xen_vcpu_get_attr(vcpu, &xva);
6616 		if (!r && copy_to_user(argp, &xva, sizeof(xva)))
6617 			r = -EFAULT;
6618 		break;
6619 	}
6620 	case KVM_XEN_VCPU_SET_ATTR: {
6621 		struct kvm_xen_vcpu_attr xva;
6622 
6623 		r = -EFAULT;
6624 		if (copy_from_user(&xva, argp, sizeof(xva)))
6625 			goto out;
6626 		r = kvm_xen_vcpu_set_attr(vcpu, &xva);
6627 		break;
6628 	}
6629 #endif
6630 	case KVM_GET_SREGS2: {
6631 		r = -EINVAL;
6632 		if (vcpu->kvm->arch.has_protected_state &&
6633 		    vcpu->arch.guest_state_protected)
6634 			goto out;
6635 
6636 		u.sregs2 = kzalloc(sizeof(struct kvm_sregs2), GFP_KERNEL);
6637 		r = -ENOMEM;
6638 		if (!u.sregs2)
6639 			goto out;
6640 		__get_sregs2(vcpu, u.sregs2);
6641 		r = -EFAULT;
6642 		if (copy_to_user(argp, u.sregs2, sizeof(struct kvm_sregs2)))
6643 			goto out;
6644 		r = 0;
6645 		break;
6646 	}
6647 	case KVM_SET_SREGS2: {
6648 		r = -EINVAL;
6649 		if (vcpu->kvm->arch.has_protected_state &&
6650 		    vcpu->arch.guest_state_protected)
6651 			goto out;
6652 
6653 		u.sregs2 = memdup_user(argp, sizeof(struct kvm_sregs2));
6654 		if (IS_ERR(u.sregs2)) {
6655 			r = PTR_ERR(u.sregs2);
6656 			u.sregs2 = NULL;
6657 			goto out;
6658 		}
6659 		r = __set_sregs2(vcpu, u.sregs2);
6660 		break;
6661 	}
6662 	case KVM_HAS_DEVICE_ATTR:
6663 	case KVM_GET_DEVICE_ATTR:
6664 	case KVM_SET_DEVICE_ATTR:
6665 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
6666 		break;
6667 	case KVM_MEMORY_ENCRYPT_OP:
6668 		r = -ENOTTY;
6669 		if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
6670 			goto out;
6671 		r = kvm_x86_ops.vcpu_mem_enc_ioctl(vcpu, argp);
6672 		break;
6673 	default:
6674 		r = -EINVAL;
6675 	}
6676 out:
6677 	kfree(u.buffer);
6678 out_nofree:
6679 	vcpu_put(vcpu);
6680 	return r;
6681 }
6682 
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)6683 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
6684 {
6685 	return VM_FAULT_SIGBUS;
6686 }
6687 
kvm_vm_ioctl_set_tss_addr(struct kvm * kvm,unsigned long addr)6688 static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
6689 {
6690 	int ret;
6691 
6692 	if (addr > (unsigned int)(-3 * PAGE_SIZE))
6693 		return -EINVAL;
6694 	ret = kvm_x86_call(set_tss_addr)(kvm, addr);
6695 	return ret;
6696 }
6697 
kvm_vm_ioctl_set_identity_map_addr(struct kvm * kvm,u64 ident_addr)6698 static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
6699 					      u64 ident_addr)
6700 {
6701 	return kvm_x86_call(set_identity_map_addr)(kvm, ident_addr);
6702 }
6703 
kvm_vm_ioctl_set_nr_mmu_pages(struct kvm * kvm,unsigned long kvm_nr_mmu_pages)6704 static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
6705 					 unsigned long kvm_nr_mmu_pages)
6706 {
6707 	if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
6708 		return -EINVAL;
6709 
6710 	mutex_lock(&kvm->slots_lock);
6711 
6712 	kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
6713 	kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
6714 
6715 	mutex_unlock(&kvm->slots_lock);
6716 	return 0;
6717 }
6718 
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)6719 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
6720 {
6721 
6722 	/*
6723 	 * Flush all CPUs' dirty log buffers to the  dirty_bitmap.  Called
6724 	 * before reporting dirty_bitmap to userspace.  KVM flushes the buffers
6725 	 * on all VM-Exits, thus we only need to kick running vCPUs to force a
6726 	 * VM-Exit.
6727 	 */
6728 	struct kvm_vcpu *vcpu;
6729 	unsigned long i;
6730 
6731 	if (!kvm->arch.cpu_dirty_log_size)
6732 		return;
6733 
6734 	kvm_for_each_vcpu(i, vcpu, kvm)
6735 		kvm_vcpu_kick(vcpu);
6736 }
6737 
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)6738 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
6739 			    struct kvm_enable_cap *cap)
6740 {
6741 	int r;
6742 
6743 	if (cap->flags)
6744 		return -EINVAL;
6745 
6746 	switch (cap->cap) {
6747 	case KVM_CAP_DISABLE_QUIRKS2:
6748 		r = -EINVAL;
6749 		if (cap->args[0] & ~kvm_caps.supported_quirks)
6750 			break;
6751 		fallthrough;
6752 	case KVM_CAP_DISABLE_QUIRKS:
6753 		kvm->arch.disabled_quirks |= cap->args[0] & kvm_caps.supported_quirks;
6754 		r = 0;
6755 		break;
6756 	case KVM_CAP_SPLIT_IRQCHIP: {
6757 		mutex_lock(&kvm->lock);
6758 		r = -EINVAL;
6759 		if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
6760 			goto split_irqchip_unlock;
6761 		r = -EEXIST;
6762 		if (irqchip_in_kernel(kvm))
6763 			goto split_irqchip_unlock;
6764 		if (kvm->created_vcpus)
6765 			goto split_irqchip_unlock;
6766 		/* Pairs with irqchip_in_kernel. */
6767 		smp_wmb();
6768 		kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
6769 		kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
6770 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
6771 		r = 0;
6772 split_irqchip_unlock:
6773 		mutex_unlock(&kvm->lock);
6774 		break;
6775 	}
6776 	case KVM_CAP_X2APIC_API:
6777 		r = -EINVAL;
6778 		if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
6779 			break;
6780 
6781 		if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
6782 			kvm->arch.x2apic_format = true;
6783 		if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
6784 			kvm->arch.x2apic_broadcast_quirk_disabled = true;
6785 
6786 		r = 0;
6787 		break;
6788 	case KVM_CAP_X86_DISABLE_EXITS:
6789 		r = -EINVAL;
6790 		if (cap->args[0] & ~kvm_get_allowed_disable_exits())
6791 			break;
6792 
6793 		mutex_lock(&kvm->lock);
6794 		if (kvm->created_vcpus)
6795 			goto disable_exits_unlock;
6796 
6797 #define SMT_RSB_MSG "This processor is affected by the Cross-Thread Return Predictions vulnerability. " \
6798 		    "KVM_CAP_X86_DISABLE_EXITS should only be used with SMT disabled or trusted guests."
6799 
6800 		if (!mitigate_smt_rsb && boot_cpu_has_bug(X86_BUG_SMT_RSB) &&
6801 		    cpu_smt_possible() &&
6802 		    (cap->args[0] & ~(KVM_X86_DISABLE_EXITS_PAUSE |
6803 				      KVM_X86_DISABLE_EXITS_APERFMPERF)))
6804 			pr_warn_once(SMT_RSB_MSG);
6805 
6806 		kvm_disable_exits(kvm, cap->args[0]);
6807 		r = 0;
6808 disable_exits_unlock:
6809 		mutex_unlock(&kvm->lock);
6810 		break;
6811 	case KVM_CAP_MSR_PLATFORM_INFO:
6812 		kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
6813 		r = 0;
6814 		break;
6815 	case KVM_CAP_EXCEPTION_PAYLOAD:
6816 		kvm->arch.exception_payload_enabled = cap->args[0];
6817 		r = 0;
6818 		break;
6819 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
6820 		kvm->arch.triple_fault_event = cap->args[0];
6821 		r = 0;
6822 		break;
6823 	case KVM_CAP_X86_USER_SPACE_MSR:
6824 		r = -EINVAL;
6825 		if (cap->args[0] & ~KVM_MSR_EXIT_REASON_VALID_MASK)
6826 			break;
6827 		kvm->arch.user_space_msr_mask = cap->args[0];
6828 		r = 0;
6829 		break;
6830 	case KVM_CAP_X86_BUS_LOCK_EXIT:
6831 		r = -EINVAL;
6832 		if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
6833 			break;
6834 
6835 		if ((cap->args[0] & KVM_BUS_LOCK_DETECTION_OFF) &&
6836 		    (cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT))
6837 			break;
6838 
6839 		if (kvm_caps.has_bus_lock_exit &&
6840 		    cap->args[0] & KVM_BUS_LOCK_DETECTION_EXIT)
6841 			kvm->arch.bus_lock_detection_enabled = true;
6842 		r = 0;
6843 		break;
6844 #ifdef CONFIG_X86_SGX_KVM
6845 	case KVM_CAP_SGX_ATTRIBUTE: {
6846 		unsigned long allowed_attributes = 0;
6847 
6848 		r = sgx_set_attribute(&allowed_attributes, cap->args[0]);
6849 		if (r)
6850 			break;
6851 
6852 		/* KVM only supports the PROVISIONKEY privileged attribute. */
6853 		if ((allowed_attributes & SGX_ATTR_PROVISIONKEY) &&
6854 		    !(allowed_attributes & ~SGX_ATTR_PROVISIONKEY))
6855 			kvm->arch.sgx_provisioning_allowed = true;
6856 		else
6857 			r = -EINVAL;
6858 		break;
6859 	}
6860 #endif
6861 	case KVM_CAP_VM_COPY_ENC_CONTEXT_FROM:
6862 		r = -EINVAL;
6863 		if (!kvm_x86_ops.vm_copy_enc_context_from)
6864 			break;
6865 
6866 		r = kvm_x86_call(vm_copy_enc_context_from)(kvm, cap->args[0]);
6867 		break;
6868 	case KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM:
6869 		r = -EINVAL;
6870 		if (!kvm_x86_ops.vm_move_enc_context_from)
6871 			break;
6872 
6873 		r = kvm_x86_call(vm_move_enc_context_from)(kvm, cap->args[0]);
6874 		break;
6875 	case KVM_CAP_EXIT_HYPERCALL:
6876 		if (cap->args[0] & ~KVM_EXIT_HYPERCALL_VALID_MASK) {
6877 			r = -EINVAL;
6878 			break;
6879 		}
6880 		kvm->arch.hypercall_exit_enabled = cap->args[0];
6881 		r = 0;
6882 		break;
6883 	case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
6884 		r = -EINVAL;
6885 		if (cap->args[0] & ~1)
6886 			break;
6887 		kvm->arch.exit_on_emulation_error = cap->args[0];
6888 		r = 0;
6889 		break;
6890 	case KVM_CAP_PMU_CAPABILITY:
6891 		r = -EINVAL;
6892 		if (!enable_pmu || (cap->args[0] & ~KVM_CAP_PMU_VALID_MASK))
6893 			break;
6894 
6895 		mutex_lock(&kvm->lock);
6896 		if (!kvm->created_vcpus) {
6897 			kvm->arch.enable_pmu = !(cap->args[0] & KVM_PMU_CAP_DISABLE);
6898 			r = 0;
6899 		}
6900 		mutex_unlock(&kvm->lock);
6901 		break;
6902 	case KVM_CAP_MAX_VCPU_ID:
6903 		r = -EINVAL;
6904 		if (cap->args[0] > KVM_MAX_VCPU_IDS)
6905 			break;
6906 
6907 		mutex_lock(&kvm->lock);
6908 		if (kvm->arch.bsp_vcpu_id > cap->args[0]) {
6909 			;
6910 		} else if (kvm->arch.max_vcpu_ids == cap->args[0]) {
6911 			r = 0;
6912 		} else if (!kvm->arch.max_vcpu_ids) {
6913 			kvm->arch.max_vcpu_ids = cap->args[0];
6914 			r = 0;
6915 		}
6916 		mutex_unlock(&kvm->lock);
6917 		break;
6918 	case KVM_CAP_X86_NOTIFY_VMEXIT:
6919 		r = -EINVAL;
6920 		if ((u32)cap->args[0] & ~KVM_X86_NOTIFY_VMEXIT_VALID_BITS)
6921 			break;
6922 		if (!kvm_caps.has_notify_vmexit)
6923 			break;
6924 		if (!((u32)cap->args[0] & KVM_X86_NOTIFY_VMEXIT_ENABLED))
6925 			break;
6926 		mutex_lock(&kvm->lock);
6927 		if (!kvm->created_vcpus) {
6928 			kvm->arch.notify_window = cap->args[0] >> 32;
6929 			kvm->arch.notify_vmexit_flags = (u32)cap->args[0];
6930 			r = 0;
6931 		}
6932 		mutex_unlock(&kvm->lock);
6933 		break;
6934 	case KVM_CAP_VM_DISABLE_NX_HUGE_PAGES:
6935 		r = -EINVAL;
6936 
6937 		/*
6938 		 * Since the risk of disabling NX hugepages is a guest crashing
6939 		 * the system, ensure the userspace process has permission to
6940 		 * reboot the system.
6941 		 *
6942 		 * Note that unlike the reboot() syscall, the process must have
6943 		 * this capability in the root namespace because exposing
6944 		 * /dev/kvm into a container does not limit the scope of the
6945 		 * iTLB multihit bug to that container. In other words,
6946 		 * this must use capable(), not ns_capable().
6947 		 */
6948 		if (!capable(CAP_SYS_BOOT)) {
6949 			r = -EPERM;
6950 			break;
6951 		}
6952 
6953 		if (cap->args[0])
6954 			break;
6955 
6956 		mutex_lock(&kvm->lock);
6957 		if (!kvm->created_vcpus) {
6958 			kvm->arch.disable_nx_huge_pages = true;
6959 			r = 0;
6960 		}
6961 		mutex_unlock(&kvm->lock);
6962 		break;
6963 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS: {
6964 		u64 bus_cycle_ns = cap->args[0];
6965 		u64 unused;
6966 
6967 		/*
6968 		 * Guard against overflow in tmict_to_ns(). 128 is the highest
6969 		 * divide value that can be programmed in APIC_TDCR.
6970 		 */
6971 		r = -EINVAL;
6972 		if (!bus_cycle_ns ||
6973 		    check_mul_overflow((u64)U32_MAX * 128, bus_cycle_ns, &unused))
6974 			break;
6975 
6976 		r = 0;
6977 		mutex_lock(&kvm->lock);
6978 		if (!irqchip_in_kernel(kvm))
6979 			r = -ENXIO;
6980 		else if (kvm->created_vcpus)
6981 			r = -EINVAL;
6982 		else
6983 			kvm->arch.apic_bus_cycle_ns = bus_cycle_ns;
6984 		mutex_unlock(&kvm->lock);
6985 		break;
6986 	}
6987 	default:
6988 		r = -EINVAL;
6989 		break;
6990 	}
6991 	return r;
6992 }
6993 
kvm_alloc_msr_filter(bool default_allow)6994 static struct kvm_x86_msr_filter *kvm_alloc_msr_filter(bool default_allow)
6995 {
6996 	struct kvm_x86_msr_filter *msr_filter;
6997 
6998 	msr_filter = kzalloc(sizeof(*msr_filter), GFP_KERNEL_ACCOUNT);
6999 	if (!msr_filter)
7000 		return NULL;
7001 
7002 	msr_filter->default_allow = default_allow;
7003 	return msr_filter;
7004 }
7005 
kvm_free_msr_filter(struct kvm_x86_msr_filter * msr_filter)7006 static void kvm_free_msr_filter(struct kvm_x86_msr_filter *msr_filter)
7007 {
7008 	u32 i;
7009 
7010 	if (!msr_filter)
7011 		return;
7012 
7013 	for (i = 0; i < msr_filter->count; i++)
7014 		kfree(msr_filter->ranges[i].bitmap);
7015 
7016 	kfree(msr_filter);
7017 }
7018 
kvm_add_msr_filter(struct kvm_x86_msr_filter * msr_filter,struct kvm_msr_filter_range * user_range)7019 static int kvm_add_msr_filter(struct kvm_x86_msr_filter *msr_filter,
7020 			      struct kvm_msr_filter_range *user_range)
7021 {
7022 	unsigned long *bitmap;
7023 	size_t bitmap_size;
7024 
7025 	if (!user_range->nmsrs)
7026 		return 0;
7027 
7028 	if (user_range->flags & ~KVM_MSR_FILTER_RANGE_VALID_MASK)
7029 		return -EINVAL;
7030 
7031 	if (!user_range->flags)
7032 		return -EINVAL;
7033 
7034 	bitmap_size = BITS_TO_LONGS(user_range->nmsrs) * sizeof(long);
7035 	if (!bitmap_size || bitmap_size > KVM_MSR_FILTER_MAX_BITMAP_SIZE)
7036 		return -EINVAL;
7037 
7038 	bitmap = memdup_user((__user u8*)user_range->bitmap, bitmap_size);
7039 	if (IS_ERR(bitmap))
7040 		return PTR_ERR(bitmap);
7041 
7042 	msr_filter->ranges[msr_filter->count] = (struct msr_bitmap_range) {
7043 		.flags = user_range->flags,
7044 		.base = user_range->base,
7045 		.nmsrs = user_range->nmsrs,
7046 		.bitmap = bitmap,
7047 	};
7048 
7049 	msr_filter->count++;
7050 	return 0;
7051 }
7052 
kvm_vm_ioctl_set_msr_filter(struct kvm * kvm,struct kvm_msr_filter * filter)7053 static int kvm_vm_ioctl_set_msr_filter(struct kvm *kvm,
7054 				       struct kvm_msr_filter *filter)
7055 {
7056 	struct kvm_x86_msr_filter *new_filter, *old_filter;
7057 	bool default_allow;
7058 	bool empty = true;
7059 	int r;
7060 	u32 i;
7061 
7062 	if (filter->flags & ~KVM_MSR_FILTER_VALID_MASK)
7063 		return -EINVAL;
7064 
7065 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++)
7066 		empty &= !filter->ranges[i].nmsrs;
7067 
7068 	default_allow = !(filter->flags & KVM_MSR_FILTER_DEFAULT_DENY);
7069 	if (empty && !default_allow)
7070 		return -EINVAL;
7071 
7072 	new_filter = kvm_alloc_msr_filter(default_allow);
7073 	if (!new_filter)
7074 		return -ENOMEM;
7075 
7076 	for (i = 0; i < ARRAY_SIZE(filter->ranges); i++) {
7077 		r = kvm_add_msr_filter(new_filter, &filter->ranges[i]);
7078 		if (r) {
7079 			kvm_free_msr_filter(new_filter);
7080 			return r;
7081 		}
7082 	}
7083 
7084 	mutex_lock(&kvm->lock);
7085 	old_filter = rcu_replace_pointer(kvm->arch.msr_filter, new_filter,
7086 					 mutex_is_locked(&kvm->lock));
7087 	mutex_unlock(&kvm->lock);
7088 	synchronize_srcu(&kvm->srcu);
7089 
7090 	kvm_free_msr_filter(old_filter);
7091 
7092 	/*
7093 	 * Recalc MSR intercepts as userspace may want to intercept accesses to
7094 	 * MSRs that KVM would otherwise pass through to the guest.
7095 	 */
7096 	kvm_make_all_cpus_request(kvm, KVM_REQ_RECALC_INTERCEPTS);
7097 
7098 	return 0;
7099 }
7100 
7101 #ifdef CONFIG_KVM_COMPAT
7102 /* for KVM_X86_SET_MSR_FILTER */
7103 struct kvm_msr_filter_range_compat {
7104 	__u32 flags;
7105 	__u32 nmsrs;
7106 	__u32 base;
7107 	__u32 bitmap;
7108 };
7109 
7110 struct kvm_msr_filter_compat {
7111 	__u32 flags;
7112 	struct kvm_msr_filter_range_compat ranges[KVM_MSR_FILTER_MAX_RANGES];
7113 };
7114 
7115 #define KVM_X86_SET_MSR_FILTER_COMPAT _IOW(KVMIO, 0xc6, struct kvm_msr_filter_compat)
7116 
kvm_arch_vm_compat_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7117 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
7118 			      unsigned long arg)
7119 {
7120 	void __user *argp = (void __user *)arg;
7121 	struct kvm *kvm = filp->private_data;
7122 	long r = -ENOTTY;
7123 
7124 	switch (ioctl) {
7125 	case KVM_X86_SET_MSR_FILTER_COMPAT: {
7126 		struct kvm_msr_filter __user *user_msr_filter = argp;
7127 		struct kvm_msr_filter_compat filter_compat;
7128 		struct kvm_msr_filter filter;
7129 		int i;
7130 
7131 		if (copy_from_user(&filter_compat, user_msr_filter,
7132 				   sizeof(filter_compat)))
7133 			return -EFAULT;
7134 
7135 		filter.flags = filter_compat.flags;
7136 		for (i = 0; i < ARRAY_SIZE(filter.ranges); i++) {
7137 			struct kvm_msr_filter_range_compat *cr;
7138 
7139 			cr = &filter_compat.ranges[i];
7140 			filter.ranges[i] = (struct kvm_msr_filter_range) {
7141 				.flags = cr->flags,
7142 				.nmsrs = cr->nmsrs,
7143 				.base = cr->base,
7144 				.bitmap = (__u8 *)(ulong)cr->bitmap,
7145 			};
7146 		}
7147 
7148 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7149 		break;
7150 	}
7151 	}
7152 
7153 	return r;
7154 }
7155 #endif
7156 
7157 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
kvm_arch_suspend_notifier(struct kvm * kvm)7158 static int kvm_arch_suspend_notifier(struct kvm *kvm)
7159 {
7160 	struct kvm_vcpu *vcpu;
7161 	unsigned long i;
7162 
7163 	/*
7164 	 * Ignore the return, marking the guest paused only "fails" if the vCPU
7165 	 * isn't using kvmclock; continuing on is correct and desirable.
7166 	 */
7167 	kvm_for_each_vcpu(i, vcpu, kvm)
7168 		(void)kvm_set_guest_paused(vcpu);
7169 
7170 	return NOTIFY_DONE;
7171 }
7172 
kvm_arch_pm_notifier(struct kvm * kvm,unsigned long state)7173 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state)
7174 {
7175 	switch (state) {
7176 	case PM_HIBERNATION_PREPARE:
7177 	case PM_SUSPEND_PREPARE:
7178 		return kvm_arch_suspend_notifier(kvm);
7179 	}
7180 
7181 	return NOTIFY_DONE;
7182 }
7183 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
7184 
kvm_vm_ioctl_get_clock(struct kvm * kvm,void __user * argp)7185 static int kvm_vm_ioctl_get_clock(struct kvm *kvm, void __user *argp)
7186 {
7187 	struct kvm_clock_data data = { 0 };
7188 
7189 	get_kvmclock(kvm, &data);
7190 	if (copy_to_user(argp, &data, sizeof(data)))
7191 		return -EFAULT;
7192 
7193 	return 0;
7194 }
7195 
kvm_vm_ioctl_set_clock(struct kvm * kvm,void __user * argp)7196 static int kvm_vm_ioctl_set_clock(struct kvm *kvm, void __user *argp)
7197 {
7198 	struct kvm_arch *ka = &kvm->arch;
7199 	struct kvm_clock_data data;
7200 	u64 now_raw_ns;
7201 
7202 	if (copy_from_user(&data, argp, sizeof(data)))
7203 		return -EFAULT;
7204 
7205 	/*
7206 	 * Only KVM_CLOCK_REALTIME is used, but allow passing the
7207 	 * result of KVM_GET_CLOCK back to KVM_SET_CLOCK.
7208 	 */
7209 	if (data.flags & ~KVM_CLOCK_VALID_FLAGS)
7210 		return -EINVAL;
7211 
7212 	kvm_hv_request_tsc_page_update(kvm);
7213 	kvm_start_pvclock_update(kvm);
7214 	pvclock_update_vm_gtod_copy(kvm);
7215 
7216 	/*
7217 	 * This pairs with kvm_guest_time_update(): when masterclock is
7218 	 * in use, we use master_kernel_ns + kvmclock_offset to set
7219 	 * unsigned 'system_time' so if we use get_kvmclock_ns() (which
7220 	 * is slightly ahead) here we risk going negative on unsigned
7221 	 * 'system_time' when 'data.clock' is very small.
7222 	 */
7223 	if (data.flags & KVM_CLOCK_REALTIME) {
7224 		u64 now_real_ns = ktime_get_real_ns();
7225 
7226 		/*
7227 		 * Avoid stepping the kvmclock backwards.
7228 		 */
7229 		if (now_real_ns > data.realtime)
7230 			data.clock += now_real_ns - data.realtime;
7231 	}
7232 
7233 	if (ka->use_master_clock)
7234 		now_raw_ns = ka->master_kernel_ns;
7235 	else
7236 		now_raw_ns = get_kvmclock_base_ns();
7237 	ka->kvmclock_offset = data.clock - now_raw_ns;
7238 	kvm_end_pvclock_update(kvm);
7239 	return 0;
7240 }
7241 
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)7242 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
7243 {
7244 	struct kvm *kvm = filp->private_data;
7245 	void __user *argp = (void __user *)arg;
7246 	int r = -ENOTTY;
7247 
7248 #ifdef CONFIG_KVM_IOAPIC
7249 	/*
7250 	 * This union makes it completely explicit to gcc-3.x
7251 	 * that these three variables' stack usage should be
7252 	 * combined, not added together.
7253 	 */
7254 	union {
7255 		struct kvm_pit_state ps;
7256 		struct kvm_pit_state2 ps2;
7257 		struct kvm_pit_config pit_config;
7258 	} u;
7259 #endif
7260 
7261 	switch (ioctl) {
7262 	case KVM_SET_TSS_ADDR:
7263 		r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
7264 		break;
7265 	case KVM_SET_IDENTITY_MAP_ADDR: {
7266 		u64 ident_addr;
7267 
7268 		mutex_lock(&kvm->lock);
7269 		r = -EINVAL;
7270 		if (kvm->created_vcpus)
7271 			goto set_identity_unlock;
7272 		r = -EFAULT;
7273 		if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
7274 			goto set_identity_unlock;
7275 		r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
7276 set_identity_unlock:
7277 		mutex_unlock(&kvm->lock);
7278 		break;
7279 	}
7280 	case KVM_SET_NR_MMU_PAGES:
7281 		r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
7282 		break;
7283 #ifdef CONFIG_KVM_IOAPIC
7284 	case KVM_CREATE_IRQCHIP: {
7285 		mutex_lock(&kvm->lock);
7286 
7287 		r = -EEXIST;
7288 		if (irqchip_in_kernel(kvm))
7289 			goto create_irqchip_unlock;
7290 
7291 		/*
7292 		 * Disallow an in-kernel I/O APIC if the VM has protected EOIs,
7293 		 * i.e. if KVM can't intercept EOIs and thus can't properly
7294 		 * emulate level-triggered interrupts.
7295 		 */
7296 		r = -ENOTTY;
7297 		if (kvm->arch.has_protected_eoi)
7298 			goto create_irqchip_unlock;
7299 
7300 		r = -EINVAL;
7301 		if (kvm->created_vcpus)
7302 			goto create_irqchip_unlock;
7303 
7304 		r = kvm_pic_init(kvm);
7305 		if (r)
7306 			goto create_irqchip_unlock;
7307 
7308 		r = kvm_ioapic_init(kvm);
7309 		if (r) {
7310 			kvm_pic_destroy(kvm);
7311 			goto create_irqchip_unlock;
7312 		}
7313 
7314 		r = kvm_setup_default_ioapic_and_pic_routing(kvm);
7315 		if (r) {
7316 			kvm_ioapic_destroy(kvm);
7317 			kvm_pic_destroy(kvm);
7318 			goto create_irqchip_unlock;
7319 		}
7320 		/* Write kvm->irq_routing before enabling irqchip_in_kernel. */
7321 		smp_wmb();
7322 		kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
7323 		kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_ABSENT);
7324 	create_irqchip_unlock:
7325 		mutex_unlock(&kvm->lock);
7326 		break;
7327 	}
7328 	case KVM_CREATE_PIT:
7329 		u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
7330 		goto create_pit;
7331 	case KVM_CREATE_PIT2:
7332 		r = -EFAULT;
7333 		if (copy_from_user(&u.pit_config, argp,
7334 				   sizeof(struct kvm_pit_config)))
7335 			goto out;
7336 	create_pit:
7337 		mutex_lock(&kvm->lock);
7338 		r = -EEXIST;
7339 		if (kvm->arch.vpit)
7340 			goto create_pit_unlock;
7341 		r = -ENOENT;
7342 		if (!pic_in_kernel(kvm))
7343 			goto create_pit_unlock;
7344 		r = -ENOMEM;
7345 		kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
7346 		if (kvm->arch.vpit)
7347 			r = 0;
7348 	create_pit_unlock:
7349 		mutex_unlock(&kvm->lock);
7350 		break;
7351 	case KVM_GET_IRQCHIP: {
7352 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7353 		struct kvm_irqchip *chip;
7354 
7355 		chip = memdup_user(argp, sizeof(*chip));
7356 		if (IS_ERR(chip)) {
7357 			r = PTR_ERR(chip);
7358 			goto out;
7359 		}
7360 
7361 		r = -ENXIO;
7362 		if (!irqchip_full(kvm))
7363 			goto get_irqchip_out;
7364 		r = kvm_vm_ioctl_get_irqchip(kvm, chip);
7365 		if (r)
7366 			goto get_irqchip_out;
7367 		r = -EFAULT;
7368 		if (copy_to_user(argp, chip, sizeof(*chip)))
7369 			goto get_irqchip_out;
7370 		r = 0;
7371 	get_irqchip_out:
7372 		kfree(chip);
7373 		break;
7374 	}
7375 	case KVM_SET_IRQCHIP: {
7376 		/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
7377 		struct kvm_irqchip *chip;
7378 
7379 		chip = memdup_user(argp, sizeof(*chip));
7380 		if (IS_ERR(chip)) {
7381 			r = PTR_ERR(chip);
7382 			goto out;
7383 		}
7384 
7385 		r = -ENXIO;
7386 		if (!irqchip_full(kvm))
7387 			goto set_irqchip_out;
7388 		r = kvm_vm_ioctl_set_irqchip(kvm, chip);
7389 	set_irqchip_out:
7390 		kfree(chip);
7391 		break;
7392 	}
7393 	case KVM_GET_PIT: {
7394 		r = -EFAULT;
7395 		if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
7396 			goto out;
7397 		r = -ENXIO;
7398 		if (!kvm->arch.vpit)
7399 			goto out;
7400 		r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
7401 		if (r)
7402 			goto out;
7403 		r = -EFAULT;
7404 		if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
7405 			goto out;
7406 		r = 0;
7407 		break;
7408 	}
7409 	case KVM_SET_PIT: {
7410 		r = -EFAULT;
7411 		if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
7412 			goto out;
7413 		mutex_lock(&kvm->lock);
7414 		r = -ENXIO;
7415 		if (!kvm->arch.vpit)
7416 			goto set_pit_out;
7417 		r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
7418 set_pit_out:
7419 		mutex_unlock(&kvm->lock);
7420 		break;
7421 	}
7422 	case KVM_GET_PIT2: {
7423 		r = -ENXIO;
7424 		if (!kvm->arch.vpit)
7425 			goto out;
7426 		r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
7427 		if (r)
7428 			goto out;
7429 		r = -EFAULT;
7430 		if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
7431 			goto out;
7432 		r = 0;
7433 		break;
7434 	}
7435 	case KVM_SET_PIT2: {
7436 		r = -EFAULT;
7437 		if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
7438 			goto out;
7439 		mutex_lock(&kvm->lock);
7440 		r = -ENXIO;
7441 		if (!kvm->arch.vpit)
7442 			goto set_pit2_out;
7443 		r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
7444 set_pit2_out:
7445 		mutex_unlock(&kvm->lock);
7446 		break;
7447 	}
7448 	case KVM_REINJECT_CONTROL: {
7449 		struct kvm_reinject_control control;
7450 		r =  -EFAULT;
7451 		if (copy_from_user(&control, argp, sizeof(control)))
7452 			goto out;
7453 		r = -ENXIO;
7454 		if (!kvm->arch.vpit)
7455 			goto out;
7456 		r = kvm_vm_ioctl_reinject(kvm, &control);
7457 		break;
7458 	}
7459 #endif
7460 	case KVM_SET_BOOT_CPU_ID:
7461 		r = 0;
7462 		mutex_lock(&kvm->lock);
7463 		if (kvm->created_vcpus)
7464 			r = -EBUSY;
7465 		else if (arg > KVM_MAX_VCPU_IDS ||
7466 			 (kvm->arch.max_vcpu_ids && arg > kvm->arch.max_vcpu_ids))
7467 			r = -EINVAL;
7468 		else
7469 			kvm->arch.bsp_vcpu_id = arg;
7470 		mutex_unlock(&kvm->lock);
7471 		break;
7472 #ifdef CONFIG_KVM_XEN
7473 	case KVM_XEN_HVM_CONFIG: {
7474 		struct kvm_xen_hvm_config xhc;
7475 		r = -EFAULT;
7476 		if (copy_from_user(&xhc, argp, sizeof(xhc)))
7477 			goto out;
7478 		r = kvm_xen_hvm_config(kvm, &xhc);
7479 		break;
7480 	}
7481 	case KVM_XEN_HVM_GET_ATTR: {
7482 		struct kvm_xen_hvm_attr xha;
7483 
7484 		r = -EFAULT;
7485 		if (copy_from_user(&xha, argp, sizeof(xha)))
7486 			goto out;
7487 		r = kvm_xen_hvm_get_attr(kvm, &xha);
7488 		if (!r && copy_to_user(argp, &xha, sizeof(xha)))
7489 			r = -EFAULT;
7490 		break;
7491 	}
7492 	case KVM_XEN_HVM_SET_ATTR: {
7493 		struct kvm_xen_hvm_attr xha;
7494 
7495 		r = -EFAULT;
7496 		if (copy_from_user(&xha, argp, sizeof(xha)))
7497 			goto out;
7498 		r = kvm_xen_hvm_set_attr(kvm, &xha);
7499 		break;
7500 	}
7501 	case KVM_XEN_HVM_EVTCHN_SEND: {
7502 		struct kvm_irq_routing_xen_evtchn uxe;
7503 
7504 		r = -EFAULT;
7505 		if (copy_from_user(&uxe, argp, sizeof(uxe)))
7506 			goto out;
7507 		r = kvm_xen_hvm_evtchn_send(kvm, &uxe);
7508 		break;
7509 	}
7510 #endif
7511 	case KVM_SET_CLOCK:
7512 		r = kvm_vm_ioctl_set_clock(kvm, argp);
7513 		break;
7514 	case KVM_GET_CLOCK:
7515 		r = kvm_vm_ioctl_get_clock(kvm, argp);
7516 		break;
7517 	case KVM_SET_TSC_KHZ: {
7518 		u32 user_tsc_khz;
7519 
7520 		r = -EINVAL;
7521 		user_tsc_khz = (u32)arg;
7522 
7523 		if (kvm_caps.has_tsc_control &&
7524 		    user_tsc_khz >= kvm_caps.max_guest_tsc_khz)
7525 			goto out;
7526 
7527 		if (user_tsc_khz == 0)
7528 			user_tsc_khz = tsc_khz;
7529 
7530 		mutex_lock(&kvm->lock);
7531 		if (!kvm->created_vcpus) {
7532 			WRITE_ONCE(kvm->arch.default_tsc_khz, user_tsc_khz);
7533 			r = 0;
7534 		}
7535 		mutex_unlock(&kvm->lock);
7536 		goto out;
7537 	}
7538 	case KVM_GET_TSC_KHZ: {
7539 		r = READ_ONCE(kvm->arch.default_tsc_khz);
7540 		goto out;
7541 	}
7542 	case KVM_MEMORY_ENCRYPT_OP:
7543 		r = -ENOTTY;
7544 		if (!kvm_x86_ops.mem_enc_ioctl)
7545 			goto out;
7546 
7547 		r = kvm_x86_call(mem_enc_ioctl)(kvm, argp);
7548 		break;
7549 	case KVM_MEMORY_ENCRYPT_REG_REGION: {
7550 		struct kvm_enc_region region;
7551 
7552 		r = -EFAULT;
7553 		if (copy_from_user(&region, argp, sizeof(region)))
7554 			goto out;
7555 
7556 		r = -ENOTTY;
7557 		if (!kvm_x86_ops.mem_enc_register_region)
7558 			goto out;
7559 
7560 		r = kvm_x86_call(mem_enc_register_region)(kvm, &region);
7561 		break;
7562 	}
7563 	case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
7564 		struct kvm_enc_region region;
7565 
7566 		r = -EFAULT;
7567 		if (copy_from_user(&region, argp, sizeof(region)))
7568 			goto out;
7569 
7570 		r = -ENOTTY;
7571 		if (!kvm_x86_ops.mem_enc_unregister_region)
7572 			goto out;
7573 
7574 		r = kvm_x86_call(mem_enc_unregister_region)(kvm, &region);
7575 		break;
7576 	}
7577 #ifdef CONFIG_KVM_HYPERV
7578 	case KVM_HYPERV_EVENTFD: {
7579 		struct kvm_hyperv_eventfd hvevfd;
7580 
7581 		r = -EFAULT;
7582 		if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
7583 			goto out;
7584 		r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
7585 		break;
7586 	}
7587 #endif
7588 	case KVM_SET_PMU_EVENT_FILTER:
7589 		r = kvm_vm_ioctl_set_pmu_event_filter(kvm, argp);
7590 		break;
7591 	case KVM_X86_SET_MSR_FILTER: {
7592 		struct kvm_msr_filter __user *user_msr_filter = argp;
7593 		struct kvm_msr_filter filter;
7594 
7595 		if (copy_from_user(&filter, user_msr_filter, sizeof(filter)))
7596 			return -EFAULT;
7597 
7598 		r = kvm_vm_ioctl_set_msr_filter(kvm, &filter);
7599 		break;
7600 	}
7601 	default:
7602 		r = -ENOTTY;
7603 	}
7604 out:
7605 	return r;
7606 }
7607 
kvm_probe_feature_msr(u32 msr_index)7608 static void kvm_probe_feature_msr(u32 msr_index)
7609 {
7610 	u64 data;
7611 
7612 	if (kvm_get_feature_msr(NULL, msr_index, &data, true))
7613 		return;
7614 
7615 	msr_based_features[num_msr_based_features++] = msr_index;
7616 }
7617 
kvm_probe_msr_to_save(u32 msr_index)7618 static void kvm_probe_msr_to_save(u32 msr_index)
7619 {
7620 	u32 dummy[2];
7621 
7622 	if (rdmsr_safe(msr_index, &dummy[0], &dummy[1]))
7623 		return;
7624 
7625 	/*
7626 	 * Even MSRs that are valid in the host may not be exposed to guests in
7627 	 * some cases.
7628 	 */
7629 	switch (msr_index) {
7630 	case MSR_IA32_BNDCFGS:
7631 		if (!kvm_mpx_supported())
7632 			return;
7633 		break;
7634 	case MSR_TSC_AUX:
7635 		if (!kvm_cpu_cap_has(X86_FEATURE_RDTSCP) &&
7636 		    !kvm_cpu_cap_has(X86_FEATURE_RDPID))
7637 			return;
7638 		break;
7639 	case MSR_IA32_UMWAIT_CONTROL:
7640 		if (!kvm_cpu_cap_has(X86_FEATURE_WAITPKG))
7641 			return;
7642 		break;
7643 	case MSR_IA32_RTIT_CTL:
7644 	case MSR_IA32_RTIT_STATUS:
7645 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT))
7646 			return;
7647 		break;
7648 	case MSR_IA32_RTIT_CR3_MATCH:
7649 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7650 		    !intel_pt_validate_hw_cap(PT_CAP_cr3_filtering))
7651 			return;
7652 		break;
7653 	case MSR_IA32_RTIT_OUTPUT_BASE:
7654 	case MSR_IA32_RTIT_OUTPUT_MASK:
7655 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7656 		    (!intel_pt_validate_hw_cap(PT_CAP_topa_output) &&
7657 		     !intel_pt_validate_hw_cap(PT_CAP_single_range_output)))
7658 			return;
7659 		break;
7660 	case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
7661 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT) ||
7662 		    (msr_index - MSR_IA32_RTIT_ADDR0_A >=
7663 		     intel_pt_validate_hw_cap(PT_CAP_num_address_ranges) * 2))
7664 			return;
7665 		break;
7666 	case MSR_ARCH_PERFMON_PERFCTR0 ...
7667 	     MSR_ARCH_PERFMON_PERFCTR0 + KVM_MAX_NR_GP_COUNTERS - 1:
7668 		if (msr_index - MSR_ARCH_PERFMON_PERFCTR0 >=
7669 		    kvm_pmu_cap.num_counters_gp)
7670 			return;
7671 		break;
7672 	case MSR_ARCH_PERFMON_EVENTSEL0 ...
7673 	     MSR_ARCH_PERFMON_EVENTSEL0 + KVM_MAX_NR_GP_COUNTERS - 1:
7674 		if (msr_index - MSR_ARCH_PERFMON_EVENTSEL0 >=
7675 		    kvm_pmu_cap.num_counters_gp)
7676 			return;
7677 		break;
7678 	case MSR_ARCH_PERFMON_FIXED_CTR0 ...
7679 	     MSR_ARCH_PERFMON_FIXED_CTR0 + KVM_MAX_NR_FIXED_COUNTERS - 1:
7680 		if (msr_index - MSR_ARCH_PERFMON_FIXED_CTR0 >=
7681 		    kvm_pmu_cap.num_counters_fixed)
7682 			return;
7683 		break;
7684 	case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
7685 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
7686 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
7687 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET:
7688 		if (!kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2))
7689 			return;
7690 		break;
7691 	case MSR_IA32_XFD:
7692 	case MSR_IA32_XFD_ERR:
7693 		if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
7694 			return;
7695 		break;
7696 	case MSR_IA32_TSX_CTRL:
7697 		if (!(kvm_get_arch_capabilities() & ARCH_CAP_TSX_CTRL_MSR))
7698 			return;
7699 		break;
7700 	case MSR_IA32_XSS:
7701 		if (!kvm_caps.supported_xss)
7702 			return;
7703 		break;
7704 	case MSR_IA32_U_CET:
7705 	case MSR_IA32_S_CET:
7706 		if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
7707 		    !kvm_cpu_cap_has(X86_FEATURE_IBT))
7708 			return;
7709 		break;
7710 	case MSR_IA32_INT_SSP_TAB:
7711 		if (!kvm_cpu_cap_has(X86_FEATURE_LM))
7712 			return;
7713 		fallthrough;
7714 	case MSR_IA32_PL0_SSP ... MSR_IA32_PL3_SSP:
7715 		if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK))
7716 			return;
7717 		break;
7718 	default:
7719 		break;
7720 	}
7721 
7722 	msrs_to_save[num_msrs_to_save++] = msr_index;
7723 }
7724 
kvm_init_msr_lists(void)7725 static void kvm_init_msr_lists(void)
7726 {
7727 	unsigned i;
7728 
7729 	BUILD_BUG_ON_MSG(KVM_MAX_NR_FIXED_COUNTERS != 3,
7730 			 "Please update the fixed PMCs in msrs_to_save_pmu[]");
7731 
7732 	num_msrs_to_save = 0;
7733 	num_emulated_msrs = 0;
7734 	num_msr_based_features = 0;
7735 
7736 	for (i = 0; i < ARRAY_SIZE(msrs_to_save_base); i++)
7737 		kvm_probe_msr_to_save(msrs_to_save_base[i]);
7738 
7739 	if (enable_pmu) {
7740 		for (i = 0; i < ARRAY_SIZE(msrs_to_save_pmu); i++)
7741 			kvm_probe_msr_to_save(msrs_to_save_pmu[i]);
7742 	}
7743 
7744 	for (i = 0; i < ARRAY_SIZE(emulated_msrs_all); i++) {
7745 		if (!kvm_x86_call(has_emulated_msr)(NULL,
7746 						    emulated_msrs_all[i]))
7747 			continue;
7748 
7749 		emulated_msrs[num_emulated_msrs++] = emulated_msrs_all[i];
7750 	}
7751 
7752 	for (i = KVM_FIRST_EMULATED_VMX_MSR; i <= KVM_LAST_EMULATED_VMX_MSR; i++)
7753 		kvm_probe_feature_msr(i);
7754 
7755 	for (i = 0; i < ARRAY_SIZE(msr_based_features_all_except_vmx); i++)
7756 		kvm_probe_feature_msr(msr_based_features_all_except_vmx[i]);
7757 }
7758 
vcpu_mmio_write(struct kvm_vcpu * vcpu,gpa_t addr,int len,const void * v)7759 static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
7760 			   const void *v)
7761 {
7762 	int handled = 0;
7763 	int n;
7764 
7765 	do {
7766 		n = min(len, 8);
7767 		if (!(lapic_in_kernel(vcpu) &&
7768 		      !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
7769 		    && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
7770 			break;
7771 		handled += n;
7772 		addr += n;
7773 		len -= n;
7774 		v += n;
7775 	} while (len);
7776 
7777 	return handled;
7778 }
7779 
vcpu_mmio_read(struct kvm_vcpu * vcpu,gpa_t addr,int len,void * v)7780 static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
7781 {
7782 	int handled = 0;
7783 	int n;
7784 
7785 	do {
7786 		n = min(len, 8);
7787 		if (!(lapic_in_kernel(vcpu) &&
7788 		      !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
7789 					 addr, n, v))
7790 		    && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
7791 			break;
7792 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
7793 		handled += n;
7794 		addr += n;
7795 		len -= n;
7796 		v += n;
7797 	} while (len);
7798 
7799 	return handled;
7800 }
7801 
kvm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7802 void kvm_set_segment(struct kvm_vcpu *vcpu,
7803 		     struct kvm_segment *var, int seg)
7804 {
7805 	kvm_x86_call(set_segment)(vcpu, var, seg);
7806 }
7807 
kvm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)7808 void kvm_get_segment(struct kvm_vcpu *vcpu,
7809 		     struct kvm_segment *var, int seg)
7810 {
7811 	kvm_x86_call(get_segment)(vcpu, var, seg);
7812 }
7813 
translate_nested_gpa(struct kvm_vcpu * vcpu,gpa_t gpa,u64 access,struct x86_exception * exception)7814 gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access,
7815 			   struct x86_exception *exception)
7816 {
7817 	struct kvm_mmu *mmu = vcpu->arch.mmu;
7818 	gpa_t t_gpa;
7819 
7820 	BUG_ON(!mmu_is_nested(vcpu));
7821 
7822 	/* NPT walks are always user-walks */
7823 	access |= PFERR_USER_MASK;
7824 	t_gpa  = mmu->gva_to_gpa(vcpu, mmu, gpa, access, exception);
7825 
7826 	return t_gpa;
7827 }
7828 
kvm_mmu_gva_to_gpa_read(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7829 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
7830 			      struct x86_exception *exception)
7831 {
7832 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7833 
7834 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7835 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7836 }
7837 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_read);
7838 
kvm_mmu_gva_to_gpa_write(struct kvm_vcpu * vcpu,gva_t gva,struct x86_exception * exception)7839 gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
7840 			       struct x86_exception *exception)
7841 {
7842 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7843 
7844 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7845 	access |= PFERR_WRITE_MASK;
7846 	return mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
7847 }
7848 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_mmu_gva_to_gpa_write);
7849 
7850 /* 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)7851 gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
7852 				struct x86_exception *exception)
7853 {
7854 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7855 
7856 	return mmu->gva_to_gpa(vcpu, mmu, gva, 0, exception);
7857 }
7858 
kvm_read_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7859 static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7860 				      struct kvm_vcpu *vcpu, u64 access,
7861 				      struct x86_exception *exception)
7862 {
7863 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7864 	void *data = val;
7865 	int r = X86EMUL_CONTINUE;
7866 
7867 	while (bytes) {
7868 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7869 		unsigned offset = addr & (PAGE_SIZE-1);
7870 		unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
7871 		int ret;
7872 
7873 		if (gpa == INVALID_GPA)
7874 			return X86EMUL_PROPAGATE_FAULT;
7875 		ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
7876 					       offset, toread);
7877 		if (ret < 0) {
7878 			r = X86EMUL_IO_NEEDED;
7879 			goto out;
7880 		}
7881 
7882 		bytes -= toread;
7883 		data += toread;
7884 		addr += toread;
7885 	}
7886 out:
7887 	return r;
7888 }
7889 
7890 /* 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)7891 static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
7892 				gva_t addr, void *val, unsigned int bytes,
7893 				struct x86_exception *exception)
7894 {
7895 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7896 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7897 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7898 	unsigned offset;
7899 	int ret;
7900 
7901 	/* Inline kvm_read_guest_virt_helper for speed.  */
7902 	gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access|PFERR_FETCH_MASK,
7903 				    exception);
7904 	if (unlikely(gpa == INVALID_GPA))
7905 		return X86EMUL_PROPAGATE_FAULT;
7906 
7907 	offset = addr & (PAGE_SIZE-1);
7908 	if (WARN_ON(offset + bytes > PAGE_SIZE))
7909 		bytes = (unsigned)PAGE_SIZE - offset;
7910 	ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
7911 				       offset, bytes);
7912 	if (unlikely(ret < 0))
7913 		return X86EMUL_IO_NEEDED;
7914 
7915 	return X86EMUL_CONTINUE;
7916 }
7917 
kvm_read_guest_virt(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7918 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
7919 			       gva_t addr, void *val, unsigned int bytes,
7920 			       struct x86_exception *exception)
7921 {
7922 	u64 access = (kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0;
7923 
7924 	/*
7925 	 * FIXME: this should call handle_emulation_failure if X86EMUL_IO_NEEDED
7926 	 * is returned, but our callers are not ready for that and they blindly
7927 	 * call kvm_inject_page_fault.  Ensure that they at least do not leak
7928 	 * uninitialized kernel stack memory into cr2 and error code.
7929 	 */
7930 	memset(exception, 0, sizeof(*exception));
7931 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
7932 					  exception);
7933 }
7934 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_virt);
7935 
emulator_read_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7936 static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
7937 			     gva_t addr, void *val, unsigned int bytes,
7938 			     struct x86_exception *exception, bool system)
7939 {
7940 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7941 	u64 access = 0;
7942 
7943 	if (system)
7944 		access |= PFERR_IMPLICIT_ACCESS;
7945 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7946 		access |= PFERR_USER_MASK;
7947 
7948 	return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
7949 }
7950 
kvm_write_guest_virt_helper(gva_t addr,void * val,unsigned int bytes,struct kvm_vcpu * vcpu,u64 access,struct x86_exception * exception)7951 static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
7952 				      struct kvm_vcpu *vcpu, u64 access,
7953 				      struct x86_exception *exception)
7954 {
7955 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
7956 	void *data = val;
7957 	int r = X86EMUL_CONTINUE;
7958 
7959 	while (bytes) {
7960 		gpa_t gpa = mmu->gva_to_gpa(vcpu, mmu, addr, access, exception);
7961 		unsigned offset = addr & (PAGE_SIZE-1);
7962 		unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
7963 		int ret;
7964 
7965 		if (gpa == INVALID_GPA)
7966 			return X86EMUL_PROPAGATE_FAULT;
7967 		ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
7968 		if (ret < 0) {
7969 			r = X86EMUL_IO_NEEDED;
7970 			goto out;
7971 		}
7972 
7973 		bytes -= towrite;
7974 		data += towrite;
7975 		addr += towrite;
7976 	}
7977 out:
7978 	return r;
7979 }
7980 
emulator_write_std(struct x86_emulate_ctxt * ctxt,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception,bool system)7981 static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
7982 			      unsigned int bytes, struct x86_exception *exception,
7983 			      bool system)
7984 {
7985 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
7986 	u64 access = PFERR_WRITE_MASK;
7987 
7988 	if (system)
7989 		access |= PFERR_IMPLICIT_ACCESS;
7990 	else if (kvm_x86_call(get_cpl)(vcpu) == 3)
7991 		access |= PFERR_USER_MASK;
7992 
7993 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
7994 					   access, exception);
7995 }
7996 
kvm_write_guest_virt_system(struct kvm_vcpu * vcpu,gva_t addr,void * val,unsigned int bytes,struct x86_exception * exception)7997 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
7998 				unsigned int bytes, struct x86_exception *exception)
7999 {
8000 	/* kvm_write_guest_virt_system can pull in tons of pages. */
8001 	vcpu->arch.l1tf_flush_l1d = true;
8002 
8003 	return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
8004 					   PFERR_WRITE_MASK, exception);
8005 }
8006 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_write_guest_virt_system);
8007 
kvm_check_emulate_insn(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)8008 static int kvm_check_emulate_insn(struct kvm_vcpu *vcpu, int emul_type,
8009 				  void *insn, int insn_len)
8010 {
8011 	return kvm_x86_call(check_emulate_instruction)(vcpu, emul_type,
8012 						       insn, insn_len);
8013 }
8014 
handle_ud(struct kvm_vcpu * vcpu)8015 int handle_ud(struct kvm_vcpu *vcpu)
8016 {
8017 	static const char kvm_emulate_prefix[] = { __KVM_EMULATE_PREFIX };
8018 	int fep_flags = READ_ONCE(force_emulation_prefix);
8019 	int emul_type = EMULTYPE_TRAP_UD;
8020 	char sig[5]; /* ud2; .ascii "kvm" */
8021 	struct x86_exception e;
8022 	int r;
8023 
8024 	r = kvm_check_emulate_insn(vcpu, emul_type, NULL, 0);
8025 	if (r != X86EMUL_CONTINUE)
8026 		return 1;
8027 
8028 	if (fep_flags &&
8029 	    kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
8030 				sig, sizeof(sig), &e) == 0 &&
8031 	    memcmp(sig, kvm_emulate_prefix, sizeof(sig)) == 0) {
8032 		if (fep_flags & KVM_FEP_CLEAR_RFLAGS_RF)
8033 			kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) & ~X86_EFLAGS_RF);
8034 		kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
8035 		emul_type = EMULTYPE_TRAP_UD_FORCED;
8036 	}
8037 
8038 	return kvm_emulate_instruction(vcpu, emul_type);
8039 }
8040 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_ud);
8041 
vcpu_is_mmio_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t gpa,bool write)8042 static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
8043 			    gpa_t gpa, bool write)
8044 {
8045 	/* For APIC access vmexit */
8046 	if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8047 		return 1;
8048 
8049 	if (vcpu_match_mmio_gpa(vcpu, gpa)) {
8050 		trace_vcpu_match_mmio(gva, gpa, write, true);
8051 		return 1;
8052 	}
8053 
8054 	return 0;
8055 }
8056 
vcpu_mmio_gva_to_gpa(struct kvm_vcpu * vcpu,unsigned long gva,gpa_t * gpa,struct x86_exception * exception,bool write)8057 static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
8058 				gpa_t *gpa, struct x86_exception *exception,
8059 				bool write)
8060 {
8061 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8062 	u64 access = ((kvm_x86_call(get_cpl)(vcpu) == 3) ? PFERR_USER_MASK : 0)
8063 		     | (write ? PFERR_WRITE_MASK : 0);
8064 
8065 	/*
8066 	 * currently PKRU is only applied to ept enabled guest so
8067 	 * there is no pkey in EPT page table for L1 guest or EPT
8068 	 * shadow page table for L2 guest.
8069 	 */
8070 	if (vcpu_match_mmio_gva(vcpu, gva) && (!is_paging(vcpu) ||
8071 	    !permission_fault(vcpu, vcpu->arch.walk_mmu,
8072 			      vcpu->arch.mmio_access, 0, access))) {
8073 		*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
8074 					(gva & (PAGE_SIZE - 1));
8075 		trace_vcpu_match_mmio(gva, *gpa, write, false);
8076 		return 1;
8077 	}
8078 
8079 	*gpa = mmu->gva_to_gpa(vcpu, mmu, gva, access, exception);
8080 
8081 	if (*gpa == INVALID_GPA)
8082 		return -1;
8083 
8084 	return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
8085 }
8086 
emulator_write_phys(struct kvm_vcpu * vcpu,gpa_t gpa,const void * val,int bytes)8087 int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
8088 			const void *val, int bytes)
8089 {
8090 	int ret;
8091 
8092 	ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
8093 	if (ret < 0)
8094 		return 0;
8095 	kvm_page_track_write(vcpu, gpa, val, bytes);
8096 	return 1;
8097 }
8098 
8099 struct read_write_emulator_ops {
8100 	int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
8101 				  int bytes);
8102 	int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
8103 				  void *val, int bytes);
8104 	int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
8105 			       int bytes, void *val);
8106 	int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
8107 				    void *val, int bytes);
8108 	bool write;
8109 };
8110 
read_prepare(struct kvm_vcpu * vcpu,void * val,int bytes)8111 static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
8112 {
8113 	if (vcpu->mmio_read_completed) {
8114 		trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
8115 			       vcpu->mmio_fragments[0].gpa, val);
8116 		vcpu->mmio_read_completed = 0;
8117 		return 1;
8118 	}
8119 
8120 	return 0;
8121 }
8122 
read_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8123 static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
8124 			void *val, int bytes)
8125 {
8126 	return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
8127 }
8128 
write_emulate(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8129 static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
8130 			 void *val, int bytes)
8131 {
8132 	return emulator_write_phys(vcpu, gpa, val, bytes);
8133 }
8134 
write_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,int bytes,void * val)8135 static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
8136 {
8137 	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
8138 	return vcpu_mmio_write(vcpu, gpa, bytes, val);
8139 }
8140 
read_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8141 static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
8142 			  void *val, int bytes)
8143 {
8144 	trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
8145 	return X86EMUL_IO_NEEDED;
8146 }
8147 
write_exit_mmio(struct kvm_vcpu * vcpu,gpa_t gpa,void * val,int bytes)8148 static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
8149 			   void *val, int bytes)
8150 {
8151 	struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
8152 
8153 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
8154 	return X86EMUL_CONTINUE;
8155 }
8156 
8157 static const struct read_write_emulator_ops read_emultor = {
8158 	.read_write_prepare = read_prepare,
8159 	.read_write_emulate = read_emulate,
8160 	.read_write_mmio = vcpu_mmio_read,
8161 	.read_write_exit_mmio = read_exit_mmio,
8162 };
8163 
8164 static const struct read_write_emulator_ops write_emultor = {
8165 	.read_write_emulate = write_emulate,
8166 	.read_write_mmio = write_mmio,
8167 	.read_write_exit_mmio = write_exit_mmio,
8168 	.write = true,
8169 };
8170 
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)8171 static int emulator_read_write_onepage(unsigned long addr, void *val,
8172 				       unsigned int bytes,
8173 				       struct x86_exception *exception,
8174 				       struct kvm_vcpu *vcpu,
8175 				       const struct read_write_emulator_ops *ops)
8176 {
8177 	gpa_t gpa;
8178 	int handled, ret;
8179 	bool write = ops->write;
8180 	struct kvm_mmio_fragment *frag;
8181 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8182 
8183 	/*
8184 	 * If the exit was due to a NPF we may already have a GPA.
8185 	 * If the GPA is present, use it to avoid the GVA to GPA table walk.
8186 	 * Note, this cannot be used on string operations since string
8187 	 * operation using rep will only have the initial GPA from the NPF
8188 	 * occurred.
8189 	 */
8190 	if (ctxt->gpa_available && emulator_can_use_gpa(ctxt) &&
8191 	    (addr & ~PAGE_MASK) == (ctxt->gpa_val & ~PAGE_MASK)) {
8192 		gpa = ctxt->gpa_val;
8193 		ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
8194 	} else {
8195 		ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
8196 		if (ret < 0)
8197 			return X86EMUL_PROPAGATE_FAULT;
8198 	}
8199 
8200 	if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
8201 		return X86EMUL_CONTINUE;
8202 
8203 	/*
8204 	 * Is this MMIO handled locally?
8205 	 */
8206 	handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
8207 	if (handled == bytes)
8208 		return X86EMUL_CONTINUE;
8209 
8210 	gpa += handled;
8211 	bytes -= handled;
8212 	val += handled;
8213 
8214 	WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
8215 	frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
8216 	frag->gpa = gpa;
8217 	frag->data = val;
8218 	frag->len = bytes;
8219 	return X86EMUL_CONTINUE;
8220 }
8221 
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)8222 static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
8223 			unsigned long addr,
8224 			void *val, unsigned int bytes,
8225 			struct x86_exception *exception,
8226 			const struct read_write_emulator_ops *ops)
8227 {
8228 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8229 	gpa_t gpa;
8230 	int rc;
8231 
8232 	if (ops->read_write_prepare &&
8233 		  ops->read_write_prepare(vcpu, val, bytes))
8234 		return X86EMUL_CONTINUE;
8235 
8236 	vcpu->mmio_nr_fragments = 0;
8237 
8238 	/* Crossing a page boundary? */
8239 	if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
8240 		int now;
8241 
8242 		now = -addr & ~PAGE_MASK;
8243 		rc = emulator_read_write_onepage(addr, val, now, exception,
8244 						 vcpu, ops);
8245 
8246 		if (rc != X86EMUL_CONTINUE)
8247 			return rc;
8248 		addr += now;
8249 		if (ctxt->mode != X86EMUL_MODE_PROT64)
8250 			addr = (u32)addr;
8251 		val += now;
8252 		bytes -= now;
8253 	}
8254 
8255 	rc = emulator_read_write_onepage(addr, val, bytes, exception,
8256 					 vcpu, ops);
8257 	if (rc != X86EMUL_CONTINUE)
8258 		return rc;
8259 
8260 	if (!vcpu->mmio_nr_fragments)
8261 		return X86EMUL_CONTINUE;
8262 
8263 	gpa = vcpu->mmio_fragments[0].gpa;
8264 
8265 	vcpu->mmio_needed = 1;
8266 	vcpu->mmio_cur_fragment = 0;
8267 
8268 	vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
8269 	vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
8270 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
8271 	vcpu->run->mmio.phys_addr = gpa;
8272 
8273 	return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
8274 }
8275 
emulator_read_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,void * val,unsigned int bytes,struct x86_exception * exception)8276 static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
8277 				  unsigned long addr,
8278 				  void *val,
8279 				  unsigned int bytes,
8280 				  struct x86_exception *exception)
8281 {
8282 	return emulator_read_write(ctxt, addr, val, bytes,
8283 				   exception, &read_emultor);
8284 }
8285 
emulator_write_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * val,unsigned int bytes,struct x86_exception * exception)8286 static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
8287 			    unsigned long addr,
8288 			    const void *val,
8289 			    unsigned int bytes,
8290 			    struct x86_exception *exception)
8291 {
8292 	return emulator_read_write(ctxt, addr, (void *)val, bytes,
8293 				   exception, &write_emultor);
8294 }
8295 
8296 #define emulator_try_cmpxchg_user(t, ptr, old, new) \
8297 	(__try_cmpxchg_user((t __user *)(ptr), (t *)(old), *(t *)(new), efault ## t))
8298 
emulator_cmpxchg_emulated(struct x86_emulate_ctxt * ctxt,unsigned long addr,const void * old,const void * new,unsigned int bytes,struct x86_exception * exception)8299 static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
8300 				     unsigned long addr,
8301 				     const void *old,
8302 				     const void *new,
8303 				     unsigned int bytes,
8304 				     struct x86_exception *exception)
8305 {
8306 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8307 	u64 page_line_mask;
8308 	unsigned long hva;
8309 	gpa_t gpa;
8310 	int r;
8311 
8312 	/* guests cmpxchg8b have to be emulated atomically */
8313 	if (bytes > 8 || (bytes & (bytes - 1)))
8314 		goto emul_write;
8315 
8316 	gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
8317 
8318 	if (gpa == INVALID_GPA ||
8319 	    (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
8320 		goto emul_write;
8321 
8322 	/*
8323 	 * Emulate the atomic as a straight write to avoid #AC if SLD is
8324 	 * enabled in the host and the access splits a cache line.
8325 	 */
8326 	if (boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
8327 		page_line_mask = ~(cache_line_size() - 1);
8328 	else
8329 		page_line_mask = PAGE_MASK;
8330 
8331 	if (((gpa + bytes - 1) & page_line_mask) != (gpa & page_line_mask))
8332 		goto emul_write;
8333 
8334 	hva = kvm_vcpu_gfn_to_hva(vcpu, gpa_to_gfn(gpa));
8335 	if (kvm_is_error_hva(hva))
8336 		goto emul_write;
8337 
8338 	hva += offset_in_page(gpa);
8339 
8340 	switch (bytes) {
8341 	case 1:
8342 		r = emulator_try_cmpxchg_user(u8, hva, old, new);
8343 		break;
8344 	case 2:
8345 		r = emulator_try_cmpxchg_user(u16, hva, old, new);
8346 		break;
8347 	case 4:
8348 		r = emulator_try_cmpxchg_user(u32, hva, old, new);
8349 		break;
8350 	case 8:
8351 		r = emulator_try_cmpxchg_user(u64, hva, old, new);
8352 		break;
8353 	default:
8354 		BUG();
8355 	}
8356 
8357 	if (r < 0)
8358 		return X86EMUL_UNHANDLEABLE;
8359 
8360 	/*
8361 	 * Mark the page dirty _before_ checking whether or not the CMPXCHG was
8362 	 * successful, as the old value is written back on failure.  Note, for
8363 	 * live migration, this is unnecessarily conservative as CMPXCHG writes
8364 	 * back the original value and the access is atomic, but KVM's ABI is
8365 	 * that all writes are dirty logged, regardless of the value written.
8366 	 */
8367 	kvm_vcpu_mark_page_dirty(vcpu, gpa_to_gfn(gpa));
8368 
8369 	if (r)
8370 		return X86EMUL_CMPXCHG_FAILED;
8371 
8372 	kvm_page_track_write(vcpu, gpa, new, bytes);
8373 
8374 	return X86EMUL_CONTINUE;
8375 
8376 emul_write:
8377 	pr_warn_once("emulating exchange as write\n");
8378 
8379 	return emulator_write_emulated(ctxt, addr, new, bytes, exception);
8380 }
8381 
emulator_pio_in_out(struct kvm_vcpu * vcpu,int size,unsigned short port,void * data,unsigned int count,bool in)8382 static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
8383 			       unsigned short port, void *data,
8384 			       unsigned int count, bool in)
8385 {
8386 	unsigned i;
8387 	int r;
8388 
8389 	WARN_ON_ONCE(vcpu->arch.pio.count);
8390 	for (i = 0; i < count; i++) {
8391 		if (in)
8392 			r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, port, size, data);
8393 		else
8394 			r = kvm_io_bus_write(vcpu, KVM_PIO_BUS, port, size, data);
8395 
8396 		if (r) {
8397 			if (i == 0)
8398 				goto userspace_io;
8399 
8400 			/*
8401 			 * Userspace must have unregistered the device while PIO
8402 			 * was running.  Drop writes / read as 0.
8403 			 */
8404 			if (in)
8405 				memset(data, 0, size * (count - i));
8406 			break;
8407 		}
8408 
8409 		data += size;
8410 	}
8411 	return 1;
8412 
8413 userspace_io:
8414 	vcpu->arch.pio.port = port;
8415 	vcpu->arch.pio.in = in;
8416 	vcpu->arch.pio.count = count;
8417 	vcpu->arch.pio.size = size;
8418 
8419 	if (in)
8420 		memset(vcpu->arch.pio_data, 0, size * count);
8421 	else
8422 		memcpy(vcpu->arch.pio_data, data, size * count);
8423 
8424 	vcpu->run->exit_reason = KVM_EXIT_IO;
8425 	vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
8426 	vcpu->run->io.size = size;
8427 	vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
8428 	vcpu->run->io.count = count;
8429 	vcpu->run->io.port = port;
8430 	return 0;
8431 }
8432 
emulator_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port,void * val,unsigned int count)8433 static int emulator_pio_in(struct kvm_vcpu *vcpu, int size,
8434       			   unsigned short port, void *val, unsigned int count)
8435 {
8436 	int r = emulator_pio_in_out(vcpu, size, port, val, count, true);
8437 	if (r)
8438 		trace_kvm_pio(KVM_PIO_IN, port, size, count, val);
8439 
8440 	return r;
8441 }
8442 
complete_emulator_pio_in(struct kvm_vcpu * vcpu,void * val)8443 static void complete_emulator_pio_in(struct kvm_vcpu *vcpu, void *val)
8444 {
8445 	int size = vcpu->arch.pio.size;
8446 	unsigned int count = vcpu->arch.pio.count;
8447 	memcpy(val, vcpu->arch.pio_data, size * count);
8448 	trace_kvm_pio(KVM_PIO_IN, vcpu->arch.pio.port, size, count, vcpu->arch.pio_data);
8449 	vcpu->arch.pio.count = 0;
8450 }
8451 
emulator_pio_in_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,void * val,unsigned int count)8452 static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
8453 				    int size, unsigned short port, void *val,
8454 				    unsigned int count)
8455 {
8456 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8457 	if (vcpu->arch.pio.count) {
8458 		/*
8459 		 * Complete a previous iteration that required userspace I/O.
8460 		 * Note, @count isn't guaranteed to match pio.count as userspace
8461 		 * can modify ECX before rerunning the vCPU.  Ignore any such
8462 		 * shenanigans as KVM doesn't support modifying the rep count,
8463 		 * and the emulator ensures @count doesn't overflow the buffer.
8464 		 */
8465 		complete_emulator_pio_in(vcpu, val);
8466 		return 1;
8467 	}
8468 
8469 	return emulator_pio_in(vcpu, size, port, val, count);
8470 }
8471 
emulator_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port,const void * val,unsigned int count)8472 static int emulator_pio_out(struct kvm_vcpu *vcpu, int size,
8473 			    unsigned short port, const void *val,
8474 			    unsigned int count)
8475 {
8476 	trace_kvm_pio(KVM_PIO_OUT, port, size, count, val);
8477 	return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
8478 }
8479 
emulator_pio_out_emulated(struct x86_emulate_ctxt * ctxt,int size,unsigned short port,const void * val,unsigned int count)8480 static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
8481 				     int size, unsigned short port,
8482 				     const void *val, unsigned int count)
8483 {
8484 	return emulator_pio_out(emul_to_vcpu(ctxt), size, port, val, count);
8485 }
8486 
get_segment_base(struct kvm_vcpu * vcpu,int seg)8487 static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
8488 {
8489 	return kvm_x86_call(get_segment_base)(vcpu, seg);
8490 }
8491 
emulator_invlpg(struct x86_emulate_ctxt * ctxt,ulong address)8492 static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
8493 {
8494 	kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
8495 }
8496 
kvm_emulate_wbinvd_noskip(struct kvm_vcpu * vcpu)8497 static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
8498 {
8499 	if (!need_emulate_wbinvd(vcpu))
8500 		return X86EMUL_CONTINUE;
8501 
8502 	if (kvm_x86_call(has_wbinvd_exit)()) {
8503 		int cpu = get_cpu();
8504 
8505 		cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
8506 		wbinvd_on_cpus_mask(vcpu->arch.wbinvd_dirty_mask);
8507 		put_cpu();
8508 		cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
8509 	} else
8510 		wbinvd();
8511 	return X86EMUL_CONTINUE;
8512 }
8513 
kvm_emulate_wbinvd(struct kvm_vcpu * vcpu)8514 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
8515 {
8516 	kvm_emulate_wbinvd_noskip(vcpu);
8517 	return kvm_skip_emulated_instruction(vcpu);
8518 }
8519 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_wbinvd);
8520 
8521 
8522 
emulator_wbinvd(struct x86_emulate_ctxt * ctxt)8523 static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
8524 {
8525 	kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
8526 }
8527 
emulator_get_dr(struct x86_emulate_ctxt * ctxt,int dr)8528 static unsigned long emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr)
8529 {
8530 	return kvm_get_dr(emul_to_vcpu(ctxt), dr);
8531 }
8532 
emulator_set_dr(struct x86_emulate_ctxt * ctxt,int dr,unsigned long value)8533 static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
8534 			   unsigned long value)
8535 {
8536 
8537 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
8538 }
8539 
mk_cr_64(u64 curr_cr,u32 new_val)8540 static u64 mk_cr_64(u64 curr_cr, u32 new_val)
8541 {
8542 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
8543 }
8544 
emulator_get_cr(struct x86_emulate_ctxt * ctxt,int cr)8545 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
8546 {
8547 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8548 	unsigned long value;
8549 
8550 	switch (cr) {
8551 	case 0:
8552 		value = kvm_read_cr0(vcpu);
8553 		break;
8554 	case 2:
8555 		value = vcpu->arch.cr2;
8556 		break;
8557 	case 3:
8558 		value = kvm_read_cr3(vcpu);
8559 		break;
8560 	case 4:
8561 		value = kvm_read_cr4(vcpu);
8562 		break;
8563 	case 8:
8564 		value = kvm_get_cr8(vcpu);
8565 		break;
8566 	default:
8567 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
8568 		return 0;
8569 	}
8570 
8571 	return value;
8572 }
8573 
emulator_set_cr(struct x86_emulate_ctxt * ctxt,int cr,ulong val)8574 static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
8575 {
8576 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8577 	int res = 0;
8578 
8579 	switch (cr) {
8580 	case 0:
8581 		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
8582 		break;
8583 	case 2:
8584 		vcpu->arch.cr2 = val;
8585 		break;
8586 	case 3:
8587 		res = kvm_set_cr3(vcpu, val);
8588 		break;
8589 	case 4:
8590 		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
8591 		break;
8592 	case 8:
8593 		res = kvm_set_cr8(vcpu, val);
8594 		break;
8595 	default:
8596 		kvm_err("%s: unexpected cr %u\n", __func__, cr);
8597 		res = -1;
8598 	}
8599 
8600 	return res;
8601 }
8602 
emulator_get_cpl(struct x86_emulate_ctxt * ctxt)8603 static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
8604 {
8605 	return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
8606 }
8607 
emulator_get_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8608 static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8609 {
8610 	kvm_x86_call(get_gdt)(emul_to_vcpu(ctxt), dt);
8611 }
8612 
emulator_get_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8613 static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8614 {
8615 	kvm_x86_call(get_idt)(emul_to_vcpu(ctxt), dt);
8616 }
8617 
emulator_set_gdt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8618 static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8619 {
8620 	kvm_x86_call(set_gdt)(emul_to_vcpu(ctxt), dt);
8621 }
8622 
emulator_set_idt(struct x86_emulate_ctxt * ctxt,struct desc_ptr * dt)8623 static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
8624 {
8625 	kvm_x86_call(set_idt)(emul_to_vcpu(ctxt), dt);
8626 }
8627 
emulator_get_cached_segment_base(struct x86_emulate_ctxt * ctxt,int seg)8628 static unsigned long emulator_get_cached_segment_base(
8629 	struct x86_emulate_ctxt *ctxt, int seg)
8630 {
8631 	return get_segment_base(emul_to_vcpu(ctxt), seg);
8632 }
8633 
emulator_get_segment(struct x86_emulate_ctxt * ctxt,u16 * selector,struct desc_struct * desc,u32 * base3,int seg)8634 static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
8635 				 struct desc_struct *desc, u32 *base3,
8636 				 int seg)
8637 {
8638 	struct kvm_segment var;
8639 
8640 	kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
8641 	*selector = var.selector;
8642 
8643 	if (var.unusable) {
8644 		memset(desc, 0, sizeof(*desc));
8645 		if (base3)
8646 			*base3 = 0;
8647 		return false;
8648 	}
8649 
8650 	if (var.g)
8651 		var.limit >>= 12;
8652 	set_desc_limit(desc, var.limit);
8653 	set_desc_base(desc, (unsigned long)var.base);
8654 #ifdef CONFIG_X86_64
8655 	if (base3)
8656 		*base3 = var.base >> 32;
8657 #endif
8658 	desc->type = var.type;
8659 	desc->s = var.s;
8660 	desc->dpl = var.dpl;
8661 	desc->p = var.present;
8662 	desc->avl = var.avl;
8663 	desc->l = var.l;
8664 	desc->d = var.db;
8665 	desc->g = var.g;
8666 
8667 	return true;
8668 }
8669 
emulator_set_segment(struct x86_emulate_ctxt * ctxt,u16 selector,struct desc_struct * desc,u32 base3,int seg)8670 static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
8671 				 struct desc_struct *desc, u32 base3,
8672 				 int seg)
8673 {
8674 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8675 	struct kvm_segment var;
8676 
8677 	var.selector = selector;
8678 	var.base = get_desc_base(desc);
8679 #ifdef CONFIG_X86_64
8680 	var.base |= ((u64)base3) << 32;
8681 #endif
8682 	var.limit = get_desc_limit(desc);
8683 	if (desc->g)
8684 		var.limit = (var.limit << 12) | 0xfff;
8685 	var.type = desc->type;
8686 	var.dpl = desc->dpl;
8687 	var.db = desc->d;
8688 	var.s = desc->s;
8689 	var.l = desc->l;
8690 	var.g = desc->g;
8691 	var.avl = desc->avl;
8692 	var.present = desc->p;
8693 	var.unusable = !var.present;
8694 	var.padding = 0;
8695 
8696 	kvm_set_segment(vcpu, &var, seg);
8697 	return;
8698 }
8699 
emulator_get_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8700 static int emulator_get_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8701 					u32 msr_index, u64 *pdata)
8702 {
8703 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8704 	int r;
8705 
8706 	r = kvm_emulate_msr_read(vcpu, msr_index, pdata);
8707 	if (r < 0)
8708 		return X86EMUL_UNHANDLEABLE;
8709 
8710 	if (r) {
8711 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_RDMSR, 0,
8712 				       complete_emulated_rdmsr, r))
8713 			return X86EMUL_IO_NEEDED;
8714 
8715 		trace_kvm_msr_read_ex(msr_index);
8716 		return X86EMUL_PROPAGATE_FAULT;
8717 	}
8718 
8719 	trace_kvm_msr_read(msr_index, *pdata);
8720 	return X86EMUL_CONTINUE;
8721 }
8722 
emulator_set_msr_with_filter(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 data)8723 static int emulator_set_msr_with_filter(struct x86_emulate_ctxt *ctxt,
8724 					u32 msr_index, u64 data)
8725 {
8726 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
8727 	int r;
8728 
8729 	r = kvm_emulate_msr_write(vcpu, msr_index, data);
8730 	if (r < 0)
8731 		return X86EMUL_UNHANDLEABLE;
8732 
8733 	if (r) {
8734 		if (kvm_msr_user_space(vcpu, msr_index, KVM_EXIT_X86_WRMSR, data,
8735 				       complete_emulated_msr_access, r))
8736 			return X86EMUL_IO_NEEDED;
8737 
8738 		trace_kvm_msr_write_ex(msr_index, data);
8739 		return X86EMUL_PROPAGATE_FAULT;
8740 	}
8741 
8742 	trace_kvm_msr_write(msr_index, data);
8743 	return X86EMUL_CONTINUE;
8744 }
8745 
emulator_get_msr(struct x86_emulate_ctxt * ctxt,u32 msr_index,u64 * pdata)8746 static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
8747 			    u32 msr_index, u64 *pdata)
8748 {
8749 	/*
8750 	 * Treat emulator accesses to the current shadow stack pointer as host-
8751 	 * initiated, as they aren't true MSR accesses (SSP is a "just a reg"),
8752 	 * and this API is used only for implicit accesses, i.e. not RDMSR, and
8753 	 * so the index is fully KVM-controlled.
8754 	 */
8755 	if (unlikely(msr_index == MSR_KVM_INTERNAL_GUEST_SSP))
8756 		return kvm_msr_read(emul_to_vcpu(ctxt), msr_index, pdata);
8757 
8758 	return __kvm_emulate_msr_read(emul_to_vcpu(ctxt), msr_index, pdata);
8759 }
8760 
emulator_check_rdpmc_early(struct x86_emulate_ctxt * ctxt,u32 pmc)8761 static int emulator_check_rdpmc_early(struct x86_emulate_ctxt *ctxt, u32 pmc)
8762 {
8763 	return kvm_pmu_check_rdpmc_early(emul_to_vcpu(ctxt), pmc);
8764 }
8765 
emulator_read_pmc(struct x86_emulate_ctxt * ctxt,u32 pmc,u64 * pdata)8766 static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
8767 			     u32 pmc, u64 *pdata)
8768 {
8769 	return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
8770 }
8771 
emulator_halt(struct x86_emulate_ctxt * ctxt)8772 static void emulator_halt(struct x86_emulate_ctxt *ctxt)
8773 {
8774 	emul_to_vcpu(ctxt)->arch.halt_request = 1;
8775 }
8776 
emulator_intercept(struct x86_emulate_ctxt * ctxt,struct x86_instruction_info * info,enum x86_intercept_stage stage)8777 static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
8778 			      struct x86_instruction_info *info,
8779 			      enum x86_intercept_stage stage)
8780 {
8781 	return kvm_x86_call(check_intercept)(emul_to_vcpu(ctxt), info, stage,
8782 					     &ctxt->exception);
8783 }
8784 
emulator_get_cpuid(struct x86_emulate_ctxt * ctxt,u32 * eax,u32 * ebx,u32 * ecx,u32 * edx,bool exact_only)8785 static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
8786 			      u32 *eax, u32 *ebx, u32 *ecx, u32 *edx,
8787 			      bool exact_only)
8788 {
8789 	return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, exact_only);
8790 }
8791 
emulator_guest_has_movbe(struct x86_emulate_ctxt * ctxt)8792 static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
8793 {
8794 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
8795 }
8796 
emulator_guest_has_fxsr(struct x86_emulate_ctxt * ctxt)8797 static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
8798 {
8799 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
8800 }
8801 
emulator_guest_has_rdpid(struct x86_emulate_ctxt * ctxt)8802 static bool emulator_guest_has_rdpid(struct x86_emulate_ctxt *ctxt)
8803 {
8804 	return guest_cpu_cap_has(emul_to_vcpu(ctxt), X86_FEATURE_RDPID);
8805 }
8806 
emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt * ctxt)8807 static bool emulator_guest_cpuid_is_intel_compatible(struct x86_emulate_ctxt *ctxt)
8808 {
8809 	return guest_cpuid_is_intel_compatible(emul_to_vcpu(ctxt));
8810 }
8811 
emulator_read_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg)8812 static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
8813 {
8814 	return kvm_register_read_raw(emul_to_vcpu(ctxt), reg);
8815 }
8816 
emulator_write_gpr(struct x86_emulate_ctxt * ctxt,unsigned reg,ulong val)8817 static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
8818 {
8819 	kvm_register_write_raw(emul_to_vcpu(ctxt), reg, val);
8820 }
8821 
emulator_set_nmi_mask(struct x86_emulate_ctxt * ctxt,bool masked)8822 static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
8823 {
8824 	kvm_x86_call(set_nmi_mask)(emul_to_vcpu(ctxt), masked);
8825 }
8826 
emulator_is_smm(struct x86_emulate_ctxt * ctxt)8827 static bool emulator_is_smm(struct x86_emulate_ctxt *ctxt)
8828 {
8829 	return is_smm(emul_to_vcpu(ctxt));
8830 }
8831 
8832 #ifndef CONFIG_KVM_SMM
emulator_leave_smm(struct x86_emulate_ctxt * ctxt)8833 static int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
8834 {
8835 	WARN_ON_ONCE(1);
8836 	return X86EMUL_UNHANDLEABLE;
8837 }
8838 #endif
8839 
emulator_triple_fault(struct x86_emulate_ctxt * ctxt)8840 static void emulator_triple_fault(struct x86_emulate_ctxt *ctxt)
8841 {
8842 	kvm_make_request(KVM_REQ_TRIPLE_FAULT, emul_to_vcpu(ctxt));
8843 }
8844 
emulator_set_xcr(struct x86_emulate_ctxt * ctxt,u32 index,u64 xcr)8845 static int emulator_set_xcr(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr)
8846 {
8847 	return __kvm_set_xcr(emul_to_vcpu(ctxt), index, xcr);
8848 }
8849 
emulator_vm_bugged(struct x86_emulate_ctxt * ctxt)8850 static void emulator_vm_bugged(struct x86_emulate_ctxt *ctxt)
8851 {
8852 	struct kvm *kvm = emul_to_vcpu(ctxt)->kvm;
8853 
8854 	if (!kvm->vm_bugged)
8855 		kvm_vm_bugged(kvm);
8856 }
8857 
emulator_get_untagged_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8858 static gva_t emulator_get_untagged_addr(struct x86_emulate_ctxt *ctxt,
8859 					gva_t addr, unsigned int flags)
8860 {
8861 	if (!kvm_x86_ops.get_untagged_addr)
8862 		return addr;
8863 
8864 	return kvm_x86_call(get_untagged_addr)(emul_to_vcpu(ctxt),
8865 					       addr, flags);
8866 }
8867 
emulator_is_canonical_addr(struct x86_emulate_ctxt * ctxt,gva_t addr,unsigned int flags)8868 static bool emulator_is_canonical_addr(struct x86_emulate_ctxt *ctxt,
8869 				       gva_t addr, unsigned int flags)
8870 {
8871 	return !is_noncanonical_address(addr, emul_to_vcpu(ctxt), flags);
8872 }
8873 
8874 static const struct x86_emulate_ops emulate_ops = {
8875 	.vm_bugged           = emulator_vm_bugged,
8876 	.read_gpr            = emulator_read_gpr,
8877 	.write_gpr           = emulator_write_gpr,
8878 	.read_std            = emulator_read_std,
8879 	.write_std           = emulator_write_std,
8880 	.fetch               = kvm_fetch_guest_virt,
8881 	.read_emulated       = emulator_read_emulated,
8882 	.write_emulated      = emulator_write_emulated,
8883 	.cmpxchg_emulated    = emulator_cmpxchg_emulated,
8884 	.invlpg              = emulator_invlpg,
8885 	.pio_in_emulated     = emulator_pio_in_emulated,
8886 	.pio_out_emulated    = emulator_pio_out_emulated,
8887 	.get_segment         = emulator_get_segment,
8888 	.set_segment         = emulator_set_segment,
8889 	.get_cached_segment_base = emulator_get_cached_segment_base,
8890 	.get_gdt             = emulator_get_gdt,
8891 	.get_idt	     = emulator_get_idt,
8892 	.set_gdt             = emulator_set_gdt,
8893 	.set_idt	     = emulator_set_idt,
8894 	.get_cr              = emulator_get_cr,
8895 	.set_cr              = emulator_set_cr,
8896 	.cpl                 = emulator_get_cpl,
8897 	.get_dr              = emulator_get_dr,
8898 	.set_dr              = emulator_set_dr,
8899 	.set_msr_with_filter = emulator_set_msr_with_filter,
8900 	.get_msr_with_filter = emulator_get_msr_with_filter,
8901 	.get_msr             = emulator_get_msr,
8902 	.check_rdpmc_early   = emulator_check_rdpmc_early,
8903 	.read_pmc            = emulator_read_pmc,
8904 	.halt                = emulator_halt,
8905 	.wbinvd              = emulator_wbinvd,
8906 	.fix_hypercall       = emulator_fix_hypercall,
8907 	.intercept           = emulator_intercept,
8908 	.get_cpuid           = emulator_get_cpuid,
8909 	.guest_has_movbe     = emulator_guest_has_movbe,
8910 	.guest_has_fxsr      = emulator_guest_has_fxsr,
8911 	.guest_has_rdpid     = emulator_guest_has_rdpid,
8912 	.guest_cpuid_is_intel_compatible = emulator_guest_cpuid_is_intel_compatible,
8913 	.set_nmi_mask        = emulator_set_nmi_mask,
8914 	.is_smm              = emulator_is_smm,
8915 	.leave_smm           = emulator_leave_smm,
8916 	.triple_fault        = emulator_triple_fault,
8917 	.set_xcr             = emulator_set_xcr,
8918 	.get_untagged_addr   = emulator_get_untagged_addr,
8919 	.is_canonical_addr   = emulator_is_canonical_addr,
8920 };
8921 
toggle_interruptibility(struct kvm_vcpu * vcpu,u32 mask)8922 static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
8923 {
8924 	u32 int_shadow = kvm_x86_call(get_interrupt_shadow)(vcpu);
8925 	/*
8926 	 * an sti; sti; sequence only disable interrupts for the first
8927 	 * instruction. So, if the last instruction, be it emulated or
8928 	 * not, left the system with the INT_STI flag enabled, it
8929 	 * means that the last instruction is an sti. We should not
8930 	 * leave the flag on in this case. The same goes for mov ss
8931 	 */
8932 	if (int_shadow & mask)
8933 		mask = 0;
8934 	if (unlikely(int_shadow || mask)) {
8935 		kvm_x86_call(set_interrupt_shadow)(vcpu, mask);
8936 		if (!mask)
8937 			kvm_make_request(KVM_REQ_EVENT, vcpu);
8938 	}
8939 }
8940 
inject_emulated_exception(struct kvm_vcpu * vcpu)8941 static void inject_emulated_exception(struct kvm_vcpu *vcpu)
8942 {
8943 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8944 
8945 	if (ctxt->exception.vector == PF_VECTOR)
8946 		kvm_inject_emulated_page_fault(vcpu, &ctxt->exception);
8947 	else if (ctxt->exception.error_code_valid)
8948 		kvm_queue_exception_e(vcpu, ctxt->exception.vector,
8949 				      ctxt->exception.error_code);
8950 	else
8951 		kvm_queue_exception(vcpu, ctxt->exception.vector);
8952 }
8953 
alloc_emulate_ctxt(struct kvm_vcpu * vcpu)8954 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)
8955 {
8956 	struct x86_emulate_ctxt *ctxt;
8957 
8958 	ctxt = kmem_cache_zalloc(x86_emulator_cache, GFP_KERNEL_ACCOUNT);
8959 	if (!ctxt) {
8960 		pr_err("failed to allocate vcpu's emulator\n");
8961 		return NULL;
8962 	}
8963 
8964 	ctxt->vcpu = vcpu;
8965 	ctxt->ops = &emulate_ops;
8966 	vcpu->arch.emulate_ctxt = ctxt;
8967 
8968 	return ctxt;
8969 }
8970 
init_emulate_ctxt(struct kvm_vcpu * vcpu)8971 static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
8972 {
8973 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
8974 	int cs_db, cs_l;
8975 
8976 	kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
8977 
8978 	ctxt->gpa_available = false;
8979 	ctxt->eflags = kvm_get_rflags(vcpu);
8980 	ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
8981 
8982 	ctxt->eip = kvm_rip_read(vcpu);
8983 	ctxt->mode = (!is_protmode(vcpu))		? X86EMUL_MODE_REAL :
8984 		     (ctxt->eflags & X86_EFLAGS_VM)	? X86EMUL_MODE_VM86 :
8985 		     (cs_l && is_long_mode(vcpu))	? X86EMUL_MODE_PROT64 :
8986 		     cs_db				? X86EMUL_MODE_PROT32 :
8987 							  X86EMUL_MODE_PROT16;
8988 	ctxt->interruptibility = 0;
8989 	ctxt->have_exception = false;
8990 	ctxt->exception.vector = -1;
8991 	ctxt->perm_ok = false;
8992 
8993 	init_decode_cache(ctxt);
8994 	vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
8995 }
8996 
kvm_inject_realmode_interrupt(struct kvm_vcpu * vcpu,int irq,int inc_eip)8997 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
8998 {
8999 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9000 	int ret;
9001 
9002 	init_emulate_ctxt(vcpu);
9003 
9004 	ctxt->op_bytes = 2;
9005 	ctxt->ad_bytes = 2;
9006 	ctxt->_eip = ctxt->eip + inc_eip;
9007 	ret = emulate_int_real(ctxt, irq);
9008 
9009 	if (ret != X86EMUL_CONTINUE) {
9010 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
9011 	} else {
9012 		ctxt->eip = ctxt->_eip;
9013 		kvm_rip_write(vcpu, ctxt->eip);
9014 		kvm_set_rflags(vcpu, ctxt->eflags);
9015 	}
9016 }
9017 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_inject_realmode_interrupt);
9018 
prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata,u8 * insn_bytes,u8 insn_size)9019 static void prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
9020 					   u8 ndata, u8 *insn_bytes, u8 insn_size)
9021 {
9022 	struct kvm_run *run = vcpu->run;
9023 	u64 info[5];
9024 	u8 info_start;
9025 
9026 	/*
9027 	 * Zero the whole array used to retrieve the exit info, as casting to
9028 	 * u32 for select entries will leave some chunks uninitialized.
9029 	 */
9030 	memset(&info, 0, sizeof(info));
9031 
9032 	kvm_x86_call(get_exit_info)(vcpu, (u32 *)&info[0], &info[1], &info[2],
9033 				    (u32 *)&info[3], (u32 *)&info[4]);
9034 
9035 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9036 	run->emulation_failure.suberror = KVM_INTERNAL_ERROR_EMULATION;
9037 
9038 	/*
9039 	 * There's currently space for 13 entries, but 5 are used for the exit
9040 	 * reason and info.  Restrict to 4 to reduce the maintenance burden
9041 	 * when expanding kvm_run.emulation_failure in the future.
9042 	 */
9043 	if (WARN_ON_ONCE(ndata > 4))
9044 		ndata = 4;
9045 
9046 	/* Always include the flags as a 'data' entry. */
9047 	info_start = 1;
9048 	run->emulation_failure.flags = 0;
9049 
9050 	if (insn_size) {
9051 		BUILD_BUG_ON((sizeof(run->emulation_failure.insn_size) +
9052 			      sizeof(run->emulation_failure.insn_bytes) != 16));
9053 		info_start += 2;
9054 		run->emulation_failure.flags |=
9055 			KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES;
9056 		run->emulation_failure.insn_size = insn_size;
9057 		memset(run->emulation_failure.insn_bytes, 0x90,
9058 		       sizeof(run->emulation_failure.insn_bytes));
9059 		memcpy(run->emulation_failure.insn_bytes, insn_bytes, insn_size);
9060 	}
9061 
9062 	memcpy(&run->internal.data[info_start], info, sizeof(info));
9063 	memcpy(&run->internal.data[info_start + ARRAY_SIZE(info)], data,
9064 	       ndata * sizeof(data[0]));
9065 
9066 	run->emulation_failure.ndata = info_start + ARRAY_SIZE(info) + ndata;
9067 }
9068 
prepare_emulation_ctxt_failure_exit(struct kvm_vcpu * vcpu)9069 static void prepare_emulation_ctxt_failure_exit(struct kvm_vcpu *vcpu)
9070 {
9071 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9072 
9073 	prepare_emulation_failure_exit(vcpu, NULL, 0, ctxt->fetch.data,
9074 				       ctxt->fetch.end - ctxt->fetch.data);
9075 }
9076 
__kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu,u64 * data,u8 ndata)9077 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu, u64 *data,
9078 					  u8 ndata)
9079 {
9080 	prepare_emulation_failure_exit(vcpu, data, ndata, NULL, 0);
9081 }
9082 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_prepare_emulation_failure_exit);
9083 
kvm_prepare_emulation_failure_exit(struct kvm_vcpu * vcpu)9084 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu)
9085 {
9086 	__kvm_prepare_emulation_failure_exit(vcpu, NULL, 0);
9087 }
9088 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_emulation_failure_exit);
9089 
kvm_prepare_event_vectoring_exit(struct kvm_vcpu * vcpu,gpa_t gpa)9090 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa)
9091 {
9092 	u32 reason, intr_info, error_code;
9093 	struct kvm_run *run = vcpu->run;
9094 	u64 info1, info2;
9095 	int ndata = 0;
9096 
9097 	kvm_x86_call(get_exit_info)(vcpu, &reason, &info1, &info2,
9098 				    &intr_info, &error_code);
9099 
9100 	run->internal.data[ndata++] = info2;
9101 	run->internal.data[ndata++] = reason;
9102 	run->internal.data[ndata++] = info1;
9103 	run->internal.data[ndata++] = gpa;
9104 	run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
9105 
9106 	run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9107 	run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
9108 	run->internal.ndata = ndata;
9109 }
9110 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_prepare_event_vectoring_exit);
9111 
handle_emulation_failure(struct kvm_vcpu * vcpu,int emulation_type)9112 static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
9113 {
9114 	struct kvm *kvm = vcpu->kvm;
9115 
9116 	++vcpu->stat.insn_emulation_fail;
9117 	trace_kvm_emulate_insn_failed(vcpu);
9118 
9119 	if (emulation_type & EMULTYPE_VMWARE_GP) {
9120 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9121 		return 1;
9122 	}
9123 
9124 	if (kvm->arch.exit_on_emulation_error ||
9125 	    (emulation_type & EMULTYPE_SKIP)) {
9126 		prepare_emulation_ctxt_failure_exit(vcpu);
9127 		return 0;
9128 	}
9129 
9130 	kvm_queue_exception(vcpu, UD_VECTOR);
9131 
9132 	if (!is_guest_mode(vcpu) && kvm_x86_call(get_cpl)(vcpu) == 0) {
9133 		prepare_emulation_ctxt_failure_exit(vcpu);
9134 		return 0;
9135 	}
9136 
9137 	return 1;
9138 }
9139 
kvm_unprotect_and_retry_on_failure(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type)9140 static bool kvm_unprotect_and_retry_on_failure(struct kvm_vcpu *vcpu,
9141 					       gpa_t cr2_or_gpa,
9142 					       int emulation_type)
9143 {
9144 	if (!(emulation_type & EMULTYPE_ALLOW_RETRY_PF))
9145 		return false;
9146 
9147 	/*
9148 	 * If the failed instruction faulted on an access to page tables that
9149 	 * are used to translate any part of the instruction, KVM can't resolve
9150 	 * the issue by unprotecting the gfn, as zapping the shadow page will
9151 	 * result in the instruction taking a !PRESENT page fault and thus put
9152 	 * the vCPU into an infinite loop of page faults.  E.g. KVM will create
9153 	 * a SPTE and write-protect the gfn to resolve the !PRESENT fault, and
9154 	 * then zap the SPTE to unprotect the gfn, and then do it all over
9155 	 * again.  Report the error to userspace.
9156 	 */
9157 	if (emulation_type & EMULTYPE_WRITE_PF_TO_SP)
9158 		return false;
9159 
9160 	/*
9161 	 * If emulation may have been triggered by a write to a shadowed page
9162 	 * table, unprotect the gfn (zap any relevant SPTEs) and re-enter the
9163 	 * guest to let the CPU re-execute the instruction in the hope that the
9164 	 * CPU can cleanly execute the instruction that KVM failed to emulate.
9165 	 */
9166 	__kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, true);
9167 
9168 	/*
9169 	 * Retry even if _this_ vCPU didn't unprotect the gfn, as it's possible
9170 	 * all SPTEs were already zapped by a different task.  The alternative
9171 	 * is to report the error to userspace and likely terminate the guest,
9172 	 * and the last_retry_{eip,addr} checks will prevent retrying the page
9173 	 * fault indefinitely, i.e. there's nothing to lose by retrying.
9174 	 */
9175 	return true;
9176 }
9177 
9178 static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
9179 static int complete_emulated_pio(struct kvm_vcpu *vcpu);
9180 
kvm_vcpu_check_hw_bp(unsigned long addr,u32 type,u32 dr7,unsigned long * db)9181 static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
9182 				unsigned long *db)
9183 {
9184 	u32 dr6 = 0;
9185 	int i;
9186 	u32 enable, rwlen;
9187 
9188 	enable = dr7;
9189 	rwlen = dr7 >> 16;
9190 	for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
9191 		if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
9192 			dr6 |= (1 << i);
9193 	return dr6;
9194 }
9195 
kvm_vcpu_do_singlestep(struct kvm_vcpu * vcpu)9196 static int kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu)
9197 {
9198 	struct kvm_run *kvm_run = vcpu->run;
9199 
9200 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
9201 		kvm_run->debug.arch.dr6 = DR6_BS | DR6_ACTIVE_LOW;
9202 		kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
9203 		kvm_run->debug.arch.exception = DB_VECTOR;
9204 		kvm_run->exit_reason = KVM_EXIT_DEBUG;
9205 		return 0;
9206 	}
9207 	kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
9208 	return 1;
9209 }
9210 
kvm_skip_emulated_instruction(struct kvm_vcpu * vcpu)9211 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
9212 {
9213 	unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9214 	int r;
9215 
9216 	r = kvm_x86_call(skip_emulated_instruction)(vcpu);
9217 	if (unlikely(!r))
9218 		return 0;
9219 
9220 	kvm_pmu_instruction_retired(vcpu);
9221 
9222 	/*
9223 	 * rflags is the old, "raw" value of the flags.  The new value has
9224 	 * not been saved yet.
9225 	 *
9226 	 * This is correct even for TF set by the guest, because "the
9227 	 * processor will not generate this exception after the instruction
9228 	 * that sets the TF flag".
9229 	 */
9230 	if (unlikely(rflags & X86_EFLAGS_TF))
9231 		r = kvm_vcpu_do_singlestep(vcpu);
9232 	return r;
9233 }
9234 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_skip_emulated_instruction);
9235 
kvm_is_code_breakpoint_inhibited(struct kvm_vcpu * vcpu)9236 static bool kvm_is_code_breakpoint_inhibited(struct kvm_vcpu *vcpu)
9237 {
9238 	if (kvm_get_rflags(vcpu) & X86_EFLAGS_RF)
9239 		return true;
9240 
9241 	/*
9242 	 * Intel compatible CPUs inhibit code #DBs when MOV/POP SS blocking is
9243 	 * active, but AMD compatible CPUs do not.
9244 	 */
9245 	if (!guest_cpuid_is_intel_compatible(vcpu))
9246 		return false;
9247 
9248 	return kvm_x86_call(get_interrupt_shadow)(vcpu) & KVM_X86_SHADOW_INT_MOV_SS;
9249 }
9250 
kvm_vcpu_check_code_breakpoint(struct kvm_vcpu * vcpu,int emulation_type,int * r)9251 static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
9252 					   int emulation_type, int *r)
9253 {
9254 	WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
9255 
9256 	/*
9257 	 * Do not check for code breakpoints if hardware has already done the
9258 	 * checks, as inferred from the emulation type.  On NO_DECODE and SKIP,
9259 	 * the instruction has passed all exception checks, and all intercepted
9260 	 * exceptions that trigger emulation have lower priority than code
9261 	 * breakpoints, i.e. the fact that the intercepted exception occurred
9262 	 * means any code breakpoints have already been serviced.
9263 	 *
9264 	 * Note, KVM needs to check for code #DBs on EMULTYPE_TRAP_UD_FORCED as
9265 	 * hardware has checked the RIP of the magic prefix, but not the RIP of
9266 	 * the instruction being emulated.  The intent of forced emulation is
9267 	 * to behave as if KVM intercepted the instruction without an exception
9268 	 * and without a prefix.
9269 	 */
9270 	if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
9271 			      EMULTYPE_TRAP_UD | EMULTYPE_VMWARE_GP | EMULTYPE_PF))
9272 		return false;
9273 
9274 	if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
9275 	    (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
9276 		struct kvm_run *kvm_run = vcpu->run;
9277 		unsigned long eip = kvm_get_linear_rip(vcpu);
9278 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9279 					   vcpu->arch.guest_debug_dr7,
9280 					   vcpu->arch.eff_db);
9281 
9282 		if (dr6 != 0) {
9283 			kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
9284 			kvm_run->debug.arch.pc = eip;
9285 			kvm_run->debug.arch.exception = DB_VECTOR;
9286 			kvm_run->exit_reason = KVM_EXIT_DEBUG;
9287 			*r = 0;
9288 			return true;
9289 		}
9290 	}
9291 
9292 	if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
9293 	    !kvm_is_code_breakpoint_inhibited(vcpu)) {
9294 		unsigned long eip = kvm_get_linear_rip(vcpu);
9295 		u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
9296 					   vcpu->arch.dr7,
9297 					   vcpu->arch.db);
9298 
9299 		if (dr6 != 0) {
9300 			kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
9301 			*r = 1;
9302 			return true;
9303 		}
9304 	}
9305 
9306 	return false;
9307 }
9308 
is_vmware_backdoor_opcode(struct x86_emulate_ctxt * ctxt)9309 static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
9310 {
9311 	switch (ctxt->opcode_len) {
9312 	case 1:
9313 		switch (ctxt->b) {
9314 		case 0xe4:	/* IN */
9315 		case 0xe5:
9316 		case 0xec:
9317 		case 0xed:
9318 		case 0xe6:	/* OUT */
9319 		case 0xe7:
9320 		case 0xee:
9321 		case 0xef:
9322 		case 0x6c:	/* INS */
9323 		case 0x6d:
9324 		case 0x6e:	/* OUTS */
9325 		case 0x6f:
9326 			return true;
9327 		}
9328 		break;
9329 	case 2:
9330 		switch (ctxt->b) {
9331 		case 0x33:	/* RDPMC */
9332 			return true;
9333 		}
9334 		break;
9335 	}
9336 
9337 	return false;
9338 }
9339 
9340 /*
9341  * Decode an instruction for emulation.  The caller is responsible for handling
9342  * code breakpoints.  Note, manually detecting code breakpoints is unnecessary
9343  * (and wrong) when emulating on an intercepted fault-like exception[*], as
9344  * code breakpoints have higher priority and thus have already been done by
9345  * hardware.
9346  *
9347  * [*] Except #MC, which is higher priority, but KVM should never emulate in
9348  *     response to a machine check.
9349  */
x86_decode_emulated_instruction(struct kvm_vcpu * vcpu,int emulation_type,void * insn,int insn_len)9350 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
9351 				    void *insn, int insn_len)
9352 {
9353 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9354 	int r;
9355 
9356 	init_emulate_ctxt(vcpu);
9357 
9358 	r = x86_decode_insn(ctxt, insn, insn_len, emulation_type);
9359 
9360 	trace_kvm_emulate_insn_start(vcpu);
9361 	++vcpu->stat.insn_emulation;
9362 
9363 	return r;
9364 }
9365 EXPORT_SYMBOL_FOR_KVM_INTERNAL(x86_decode_emulated_instruction);
9366 
x86_emulate_instruction(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,int emulation_type,void * insn,int insn_len)9367 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
9368 			    int emulation_type, void *insn, int insn_len)
9369 {
9370 	int r;
9371 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
9372 	bool writeback = true;
9373 
9374 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9375 	    (WARN_ON_ONCE(is_guest_mode(vcpu)) ||
9376 	     WARN_ON_ONCE(!(emulation_type & EMULTYPE_PF))))
9377 		emulation_type &= ~EMULTYPE_ALLOW_RETRY_PF;
9378 
9379 	r = kvm_check_emulate_insn(vcpu, emulation_type, insn, insn_len);
9380 	if (r != X86EMUL_CONTINUE) {
9381 		if (r == X86EMUL_RETRY_INSTR || r == X86EMUL_PROPAGATE_FAULT)
9382 			return 1;
9383 
9384 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9385 						       emulation_type))
9386 			return 1;
9387 
9388 		if (r == X86EMUL_UNHANDLEABLE_VECTORING) {
9389 			kvm_prepare_event_vectoring_exit(vcpu, cr2_or_gpa);
9390 			return 0;
9391 		}
9392 
9393 		WARN_ON_ONCE(r != X86EMUL_UNHANDLEABLE);
9394 		return handle_emulation_failure(vcpu, emulation_type);
9395 	}
9396 
9397 	vcpu->arch.l1tf_flush_l1d = true;
9398 
9399 	if (!(emulation_type & EMULTYPE_NO_DECODE)) {
9400 		kvm_clear_exception_queue(vcpu);
9401 
9402 		/*
9403 		 * Return immediately if RIP hits a code breakpoint, such #DBs
9404 		 * are fault-like and are higher priority than any faults on
9405 		 * the code fetch itself.
9406 		 */
9407 		if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
9408 			return r;
9409 
9410 		r = x86_decode_emulated_instruction(vcpu, emulation_type,
9411 						    insn, insn_len);
9412 		if (r != EMULATION_OK)  {
9413 			if ((emulation_type & EMULTYPE_TRAP_UD) ||
9414 			    (emulation_type & EMULTYPE_TRAP_UD_FORCED)) {
9415 				kvm_queue_exception(vcpu, UD_VECTOR);
9416 				return 1;
9417 			}
9418 			if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9419 							       emulation_type))
9420 				return 1;
9421 
9422 			if (ctxt->have_exception &&
9423 			    !(emulation_type & EMULTYPE_SKIP)) {
9424 				/*
9425 				 * #UD should result in just EMULATION_FAILED, and trap-like
9426 				 * exception should not be encountered during decode.
9427 				 */
9428 				WARN_ON_ONCE(ctxt->exception.vector == UD_VECTOR ||
9429 					     exception_type(ctxt->exception.vector) == EXCPT_TRAP);
9430 				inject_emulated_exception(vcpu);
9431 				return 1;
9432 			}
9433 			return handle_emulation_failure(vcpu, emulation_type);
9434 		}
9435 	}
9436 
9437 	if ((emulation_type & EMULTYPE_VMWARE_GP) &&
9438 	    !is_vmware_backdoor_opcode(ctxt)) {
9439 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
9440 		return 1;
9441 	}
9442 
9443 	/*
9444 	 * EMULTYPE_SKIP without EMULTYPE_COMPLETE_USER_EXIT is intended for
9445 	 * use *only* by vendor callbacks for kvm_skip_emulated_instruction().
9446 	 * The caller is responsible for updating interruptibility state and
9447 	 * injecting single-step #DBs.
9448 	 */
9449 	if (emulation_type & EMULTYPE_SKIP) {
9450 		if (ctxt->mode != X86EMUL_MODE_PROT64)
9451 			ctxt->eip = (u32)ctxt->_eip;
9452 		else
9453 			ctxt->eip = ctxt->_eip;
9454 
9455 		if (emulation_type & EMULTYPE_COMPLETE_USER_EXIT) {
9456 			r = 1;
9457 			goto writeback;
9458 		}
9459 
9460 		kvm_rip_write(vcpu, ctxt->eip);
9461 		if (ctxt->eflags & X86_EFLAGS_RF)
9462 			kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
9463 		return 1;
9464 	}
9465 
9466 	/*
9467 	 * If emulation was caused by a write-protection #PF on a non-page_table
9468 	 * writing instruction, try to unprotect the gfn, i.e. zap shadow pages,
9469 	 * and retry the instruction, as the vCPU is likely no longer using the
9470 	 * gfn as a page table.
9471 	 */
9472 	if ((emulation_type & EMULTYPE_ALLOW_RETRY_PF) &&
9473 	    !x86_page_table_writing_insn(ctxt) &&
9474 	    kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
9475 		return 1;
9476 
9477 	/* this is needed for vmware backdoor interface to work since it
9478 	   changes registers values  during IO operation */
9479 	if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
9480 		vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
9481 		emulator_invalidate_register_cache(ctxt);
9482 	}
9483 
9484 restart:
9485 	if (emulation_type & EMULTYPE_PF) {
9486 		/* Save the faulting GPA (cr2) in the address field */
9487 		ctxt->exception.address = cr2_or_gpa;
9488 
9489 		/* With shadow page tables, cr2 contains a GVA or nGPA. */
9490 		if (vcpu->arch.mmu->root_role.direct) {
9491 			ctxt->gpa_available = true;
9492 			ctxt->gpa_val = cr2_or_gpa;
9493 		}
9494 	} else {
9495 		/* Sanitize the address out of an abundance of paranoia. */
9496 		ctxt->exception.address = 0;
9497 	}
9498 
9499 	/*
9500 	 * Check L1's instruction intercepts when emulating instructions for
9501 	 * L2, unless KVM is re-emulating a previously decoded instruction,
9502 	 * e.g. to complete userspace I/O, in which case KVM has already
9503 	 * checked the intercepts.
9504 	 */
9505 	r = x86_emulate_insn(ctxt, is_guest_mode(vcpu) &&
9506 				   !(emulation_type & EMULTYPE_NO_DECODE));
9507 
9508 	if (r == EMULATION_INTERCEPTED)
9509 		return 1;
9510 
9511 	if (r == EMULATION_FAILED) {
9512 		if (kvm_unprotect_and_retry_on_failure(vcpu, cr2_or_gpa,
9513 						       emulation_type))
9514 			return 1;
9515 
9516 		return handle_emulation_failure(vcpu, emulation_type);
9517 	}
9518 
9519 	if (ctxt->have_exception) {
9520 		WARN_ON_ONCE(vcpu->mmio_needed && !vcpu->mmio_is_write);
9521 		vcpu->mmio_needed = false;
9522 		r = 1;
9523 		inject_emulated_exception(vcpu);
9524 	} else if (vcpu->arch.pio.count) {
9525 		if (!vcpu->arch.pio.in) {
9526 			/* FIXME: return into emulator if single-stepping.  */
9527 			vcpu->arch.pio.count = 0;
9528 		} else {
9529 			writeback = false;
9530 			vcpu->arch.complete_userspace_io = complete_emulated_pio;
9531 		}
9532 		r = 0;
9533 	} else if (vcpu->mmio_needed) {
9534 		++vcpu->stat.mmio_exits;
9535 
9536 		if (!vcpu->mmio_is_write)
9537 			writeback = false;
9538 		r = 0;
9539 		vcpu->arch.complete_userspace_io = complete_emulated_mmio;
9540 	} else if (vcpu->arch.complete_userspace_io) {
9541 		writeback = false;
9542 		r = 0;
9543 	} else if (r == EMULATION_RESTART)
9544 		goto restart;
9545 	else
9546 		r = 1;
9547 
9548 writeback:
9549 	if (writeback) {
9550 		unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
9551 		toggle_interruptibility(vcpu, ctxt->interruptibility);
9552 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
9553 
9554 		/*
9555 		 * Note, EXCPT_DB is assumed to be fault-like as the emulator
9556 		 * only supports code breakpoints and general detect #DB, both
9557 		 * of which are fault-like.
9558 		 */
9559 		if (!ctxt->have_exception ||
9560 		    exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
9561 			kvm_pmu_instruction_retired(vcpu);
9562 			if (ctxt->is_branch)
9563 				kvm_pmu_branch_retired(vcpu);
9564 			kvm_rip_write(vcpu, ctxt->eip);
9565 			if (r && (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
9566 				r = kvm_vcpu_do_singlestep(vcpu);
9567 			kvm_x86_call(update_emulated_instruction)(vcpu);
9568 			__kvm_set_rflags(vcpu, ctxt->eflags);
9569 		}
9570 
9571 		/*
9572 		 * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
9573 		 * do nothing, and it will be requested again as soon as
9574 		 * the shadow expires.  But we still need to check here,
9575 		 * because POPF has no interrupt shadow.
9576 		 */
9577 		if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
9578 			kvm_make_request(KVM_REQ_EVENT, vcpu);
9579 	} else
9580 		vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
9581 
9582 	return r;
9583 }
9584 
kvm_emulate_instruction(struct kvm_vcpu * vcpu,int emulation_type)9585 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
9586 {
9587 	return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
9588 }
9589 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction);
9590 
kvm_emulate_instruction_from_buffer(struct kvm_vcpu * vcpu,void * insn,int insn_len)9591 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
9592 					void *insn, int insn_len)
9593 {
9594 	return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
9595 }
9596 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_instruction_from_buffer);
9597 
complete_fast_pio_out_port_0x7e(struct kvm_vcpu * vcpu)9598 static int complete_fast_pio_out_port_0x7e(struct kvm_vcpu *vcpu)
9599 {
9600 	vcpu->arch.pio.count = 0;
9601 	return 1;
9602 }
9603 
complete_fast_pio_out(struct kvm_vcpu * vcpu)9604 static int complete_fast_pio_out(struct kvm_vcpu *vcpu)
9605 {
9606 	vcpu->arch.pio.count = 0;
9607 
9608 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip)))
9609 		return 1;
9610 
9611 	return kvm_skip_emulated_instruction(vcpu);
9612 }
9613 
kvm_fast_pio_out(struct kvm_vcpu * vcpu,int size,unsigned short port)9614 static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
9615 			    unsigned short port)
9616 {
9617 	unsigned long val = kvm_rax_read(vcpu);
9618 	int ret = emulator_pio_out(vcpu, size, port, &val, 1);
9619 
9620 	if (ret)
9621 		return ret;
9622 
9623 	/*
9624 	 * Workaround userspace that relies on old KVM behavior of %rip being
9625 	 * incremented prior to exiting to userspace to handle "OUT 0x7e".
9626 	 */
9627 	if (port == 0x7e &&
9628 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_OUT_7E_INC_RIP)) {
9629 		vcpu->arch.complete_userspace_io =
9630 			complete_fast_pio_out_port_0x7e;
9631 		kvm_skip_emulated_instruction(vcpu);
9632 	} else {
9633 		vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9634 		vcpu->arch.complete_userspace_io = complete_fast_pio_out;
9635 	}
9636 	return 0;
9637 }
9638 
complete_fast_pio_in(struct kvm_vcpu * vcpu)9639 static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
9640 {
9641 	unsigned long val;
9642 
9643 	/* We should only ever be called with arch.pio.count equal to 1 */
9644 	BUG_ON(vcpu->arch.pio.count != 1);
9645 
9646 	if (unlikely(!kvm_is_linear_rip(vcpu, vcpu->arch.cui_linear_rip))) {
9647 		vcpu->arch.pio.count = 0;
9648 		return 1;
9649 	}
9650 
9651 	/* For size less than 4 we merge, else we zero extend */
9652 	val = (vcpu->arch.pio.size < 4) ? kvm_rax_read(vcpu) : 0;
9653 
9654 	complete_emulator_pio_in(vcpu, &val);
9655 	kvm_rax_write(vcpu, val);
9656 
9657 	return kvm_skip_emulated_instruction(vcpu);
9658 }
9659 
kvm_fast_pio_in(struct kvm_vcpu * vcpu,int size,unsigned short port)9660 static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
9661 			   unsigned short port)
9662 {
9663 	unsigned long val;
9664 	int ret;
9665 
9666 	/* For size less than 4 we merge, else we zero extend */
9667 	val = (size < 4) ? kvm_rax_read(vcpu) : 0;
9668 
9669 	ret = emulator_pio_in(vcpu, size, port, &val, 1);
9670 	if (ret) {
9671 		kvm_rax_write(vcpu, val);
9672 		return ret;
9673 	}
9674 
9675 	vcpu->arch.cui_linear_rip = kvm_get_linear_rip(vcpu);
9676 	vcpu->arch.complete_userspace_io = complete_fast_pio_in;
9677 
9678 	return 0;
9679 }
9680 
kvm_fast_pio(struct kvm_vcpu * vcpu,int size,unsigned short port,int in)9681 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
9682 {
9683 	int ret;
9684 
9685 	if (in)
9686 		ret = kvm_fast_pio_in(vcpu, size, port);
9687 	else
9688 		ret = kvm_fast_pio_out(vcpu, size, port);
9689 	return ret && kvm_skip_emulated_instruction(vcpu);
9690 }
9691 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fast_pio);
9692 
kvmclock_cpu_down_prep(unsigned int cpu)9693 static int kvmclock_cpu_down_prep(unsigned int cpu)
9694 {
9695 	__this_cpu_write(cpu_tsc_khz, 0);
9696 	return 0;
9697 }
9698 
tsc_khz_changed(void * data)9699 static void tsc_khz_changed(void *data)
9700 {
9701 	struct cpufreq_freqs *freq = data;
9702 	unsigned long khz;
9703 
9704 	WARN_ON_ONCE(boot_cpu_has(X86_FEATURE_CONSTANT_TSC));
9705 
9706 	if (data)
9707 		khz = freq->new;
9708 	else
9709 		khz = cpufreq_quick_get(raw_smp_processor_id());
9710 	if (!khz)
9711 		khz = tsc_khz;
9712 	__this_cpu_write(cpu_tsc_khz, khz);
9713 }
9714 
9715 #ifdef CONFIG_X86_64
kvm_hyperv_tsc_notifier(void)9716 static void kvm_hyperv_tsc_notifier(void)
9717 {
9718 	struct kvm *kvm;
9719 	int cpu;
9720 
9721 	mutex_lock(&kvm_lock);
9722 	list_for_each_entry(kvm, &vm_list, vm_list)
9723 		kvm_make_mclock_inprogress_request(kvm);
9724 
9725 	/* no guest entries from this point */
9726 	hyperv_stop_tsc_emulation();
9727 
9728 	/* TSC frequency always matches when on Hyper-V */
9729 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9730 		for_each_present_cpu(cpu)
9731 			per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
9732 	}
9733 	kvm_caps.max_guest_tsc_khz = tsc_khz;
9734 
9735 	list_for_each_entry(kvm, &vm_list, vm_list) {
9736 		__kvm_start_pvclock_update(kvm);
9737 		pvclock_update_vm_gtod_copy(kvm);
9738 		kvm_end_pvclock_update(kvm);
9739 	}
9740 
9741 	mutex_unlock(&kvm_lock);
9742 }
9743 #endif
9744 
__kvmclock_cpufreq_notifier(struct cpufreq_freqs * freq,int cpu)9745 static void __kvmclock_cpufreq_notifier(struct cpufreq_freqs *freq, int cpu)
9746 {
9747 	struct kvm *kvm;
9748 	struct kvm_vcpu *vcpu;
9749 	int send_ipi = 0;
9750 	unsigned long i;
9751 
9752 	/*
9753 	 * We allow guests to temporarily run on slowing clocks,
9754 	 * provided we notify them after, or to run on accelerating
9755 	 * clocks, provided we notify them before.  Thus time never
9756 	 * goes backwards.
9757 	 *
9758 	 * However, we have a problem.  We can't atomically update
9759 	 * the frequency of a given CPU from this function; it is
9760 	 * merely a notifier, which can be called from any CPU.
9761 	 * Changing the TSC frequency at arbitrary points in time
9762 	 * requires a recomputation of local variables related to
9763 	 * the TSC for each VCPU.  We must flag these local variables
9764 	 * to be updated and be sure the update takes place with the
9765 	 * new frequency before any guests proceed.
9766 	 *
9767 	 * Unfortunately, the combination of hotplug CPU and frequency
9768 	 * change creates an intractable locking scenario; the order
9769 	 * of when these callouts happen is undefined with respect to
9770 	 * CPU hotplug, and they can race with each other.  As such,
9771 	 * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
9772 	 * undefined; you can actually have a CPU frequency change take
9773 	 * place in between the computation of X and the setting of the
9774 	 * variable.  To protect against this problem, all updates of
9775 	 * the per_cpu tsc_khz variable are done in an interrupt
9776 	 * protected IPI, and all callers wishing to update the value
9777 	 * must wait for a synchronous IPI to complete (which is trivial
9778 	 * if the caller is on the CPU already).  This establishes the
9779 	 * necessary total order on variable updates.
9780 	 *
9781 	 * Note that because a guest time update may take place
9782 	 * anytime after the setting of the VCPU's request bit, the
9783 	 * correct TSC value must be set before the request.  However,
9784 	 * to ensure the update actually makes it to any guest which
9785 	 * starts running in hardware virtualization between the set
9786 	 * and the acquisition of the spinlock, we must also ping the
9787 	 * CPU after setting the request bit.
9788 	 *
9789 	 */
9790 
9791 	smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9792 
9793 	mutex_lock(&kvm_lock);
9794 	list_for_each_entry(kvm, &vm_list, vm_list) {
9795 		kvm_for_each_vcpu(i, vcpu, kvm) {
9796 			if (vcpu->cpu != cpu)
9797 				continue;
9798 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
9799 			if (vcpu->cpu != raw_smp_processor_id())
9800 				send_ipi = 1;
9801 		}
9802 	}
9803 	mutex_unlock(&kvm_lock);
9804 
9805 	if (freq->old < freq->new && send_ipi) {
9806 		/*
9807 		 * We upscale the frequency.  Must make the guest
9808 		 * doesn't see old kvmclock values while running with
9809 		 * the new frequency, otherwise we risk the guest sees
9810 		 * time go backwards.
9811 		 *
9812 		 * In case we update the frequency for another cpu
9813 		 * (which might be in guest context) send an interrupt
9814 		 * to kick the cpu out of guest context.  Next time
9815 		 * guest context is entered kvmclock will be updated,
9816 		 * so the guest will not see stale values.
9817 		 */
9818 		smp_call_function_single(cpu, tsc_khz_changed, freq, 1);
9819 	}
9820 }
9821 
kvmclock_cpufreq_notifier(struct notifier_block * nb,unsigned long val,void * data)9822 static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
9823 				     void *data)
9824 {
9825 	struct cpufreq_freqs *freq = data;
9826 	int cpu;
9827 
9828 	if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
9829 		return 0;
9830 	if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
9831 		return 0;
9832 
9833 	for_each_cpu(cpu, freq->policy->cpus)
9834 		__kvmclock_cpufreq_notifier(freq, cpu);
9835 
9836 	return 0;
9837 }
9838 
9839 static struct notifier_block kvmclock_cpufreq_notifier_block = {
9840 	.notifier_call  = kvmclock_cpufreq_notifier
9841 };
9842 
kvmclock_cpu_online(unsigned int cpu)9843 static int kvmclock_cpu_online(unsigned int cpu)
9844 {
9845 	tsc_khz_changed(NULL);
9846 	return 0;
9847 }
9848 
kvm_timer_init(void)9849 static void kvm_timer_init(void)
9850 {
9851 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9852 		max_tsc_khz = tsc_khz;
9853 
9854 		if (IS_ENABLED(CONFIG_CPU_FREQ)) {
9855 			struct cpufreq_policy *policy;
9856 			int cpu;
9857 
9858 			cpu = get_cpu();
9859 			policy = cpufreq_cpu_get(cpu);
9860 			if (policy) {
9861 				if (policy->cpuinfo.max_freq)
9862 					max_tsc_khz = policy->cpuinfo.max_freq;
9863 				cpufreq_cpu_put(policy);
9864 			}
9865 			put_cpu();
9866 		}
9867 		cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
9868 					  CPUFREQ_TRANSITION_NOTIFIER);
9869 
9870 		cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
9871 				  kvmclock_cpu_online, kvmclock_cpu_down_prep);
9872 	}
9873 }
9874 
9875 #ifdef CONFIG_X86_64
pvclock_gtod_update_fn(struct work_struct * work)9876 static void pvclock_gtod_update_fn(struct work_struct *work)
9877 {
9878 	struct kvm *kvm;
9879 	struct kvm_vcpu *vcpu;
9880 	unsigned long i;
9881 
9882 	mutex_lock(&kvm_lock);
9883 	list_for_each_entry(kvm, &vm_list, vm_list)
9884 		kvm_for_each_vcpu(i, vcpu, kvm)
9885 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
9886 	atomic_set(&kvm_guest_has_master_clock, 0);
9887 	mutex_unlock(&kvm_lock);
9888 }
9889 
9890 static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
9891 
9892 /*
9893  * Indirection to move queue_work() out of the tk_core.seq write held
9894  * region to prevent possible deadlocks against time accessors which
9895  * are invoked with work related locks held.
9896  */
pvclock_irq_work_fn(struct irq_work * w)9897 static void pvclock_irq_work_fn(struct irq_work *w)
9898 {
9899 	queue_work(system_long_wq, &pvclock_gtod_work);
9900 }
9901 
9902 static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_irq_work_fn);
9903 
9904 /*
9905  * Notification about pvclock gtod data update.
9906  */
pvclock_gtod_notify(struct notifier_block * nb,unsigned long unused,void * priv)9907 static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
9908 			       void *priv)
9909 {
9910 	struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
9911 	struct timekeeper *tk = priv;
9912 
9913 	update_pvclock_gtod(tk);
9914 
9915 	/*
9916 	 * Disable master clock if host does not trust, or does not use,
9917 	 * TSC based clocksource. Delegate queue_work() to irq_work as
9918 	 * this is invoked with tk_core.seq write held.
9919 	 */
9920 	if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
9921 	    atomic_read(&kvm_guest_has_master_clock) != 0)
9922 		irq_work_queue(&pvclock_irq_work);
9923 	return 0;
9924 }
9925 
9926 static struct notifier_block pvclock_gtod_notifier = {
9927 	.notifier_call = pvclock_gtod_notify,
9928 };
9929 #endif
9930 
kvm_ops_update(struct kvm_x86_init_ops * ops)9931 static inline void kvm_ops_update(struct kvm_x86_init_ops *ops)
9932 {
9933 	memcpy(&kvm_x86_ops, ops->runtime_ops, sizeof(kvm_x86_ops));
9934 
9935 #define __KVM_X86_OP(func) \
9936 	static_call_update(kvm_x86_##func, kvm_x86_ops.func);
9937 #define KVM_X86_OP(func) \
9938 	WARN_ON(!kvm_x86_ops.func); __KVM_X86_OP(func)
9939 #define KVM_X86_OP_OPTIONAL __KVM_X86_OP
9940 #define KVM_X86_OP_OPTIONAL_RET0(func) \
9941 	static_call_update(kvm_x86_##func, (void *)kvm_x86_ops.func ? : \
9942 					   (void *)__static_call_return0);
9943 #include <asm/kvm-x86-ops.h>
9944 #undef __KVM_X86_OP
9945 
9946 	kvm_pmu_ops_update(ops->pmu_ops);
9947 }
9948 
kvm_x86_check_processor_compatibility(void)9949 static int kvm_x86_check_processor_compatibility(void)
9950 {
9951 	int cpu = smp_processor_id();
9952 	struct cpuinfo_x86 *c = &cpu_data(cpu);
9953 
9954 	/*
9955 	 * Compatibility checks are done when loading KVM and when enabling
9956 	 * hardware, e.g. during CPU hotplug, to ensure all online CPUs are
9957 	 * compatible, i.e. KVM should never perform a compatibility check on
9958 	 * an offline CPU.
9959 	 */
9960 	WARN_ON(!cpu_online(cpu));
9961 
9962 	if (__cr4_reserved_bits(cpu_has, c) !=
9963 	    __cr4_reserved_bits(cpu_has, &boot_cpu_data))
9964 		return -EIO;
9965 
9966 	return kvm_x86_call(check_processor_compatibility)();
9967 }
9968 
kvm_x86_check_cpu_compat(void * ret)9969 static void kvm_x86_check_cpu_compat(void *ret)
9970 {
9971 	*(int *)ret = kvm_x86_check_processor_compatibility();
9972 }
9973 
kvm_x86_vendor_init(struct kvm_x86_init_ops * ops)9974 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
9975 {
9976 	u64 host_pat;
9977 	int r, cpu;
9978 
9979 	guard(mutex)(&vendor_module_lock);
9980 
9981 	if (kvm_x86_ops.enable_virtualization_cpu) {
9982 		pr_err("already loaded vendor module '%s'\n", kvm_x86_ops.name);
9983 		return -EEXIST;
9984 	}
9985 
9986 	/*
9987 	 * KVM explicitly assumes that the guest has an FPU and
9988 	 * FXSAVE/FXRSTOR. For example, the KVM_GET_FPU explicitly casts the
9989 	 * vCPU's FPU state as a fxregs_state struct.
9990 	 */
9991 	if (!boot_cpu_has(X86_FEATURE_FPU) || !boot_cpu_has(X86_FEATURE_FXSR)) {
9992 		pr_err("inadequate fpu\n");
9993 		return -EOPNOTSUPP;
9994 	}
9995 
9996 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
9997 		pr_err("RT requires X86_FEATURE_CONSTANT_TSC\n");
9998 		return -EOPNOTSUPP;
9999 	}
10000 
10001 	/*
10002 	 * KVM assumes that PAT entry '0' encodes WB memtype and simply zeroes
10003 	 * the PAT bits in SPTEs.  Bail if PAT[0] is programmed to something
10004 	 * other than WB.  Note, EPT doesn't utilize the PAT, but don't bother
10005 	 * with an exception.  PAT[0] is set to WB on RESET and also by the
10006 	 * kernel, i.e. failure indicates a kernel bug or broken firmware.
10007 	 */
10008 	if (rdmsrq_safe(MSR_IA32_CR_PAT, &host_pat) ||
10009 	    (host_pat & GENMASK(2, 0)) != 6) {
10010 		pr_err("host PAT[0] is not WB\n");
10011 		return -EIO;
10012 	}
10013 
10014 	if (boot_cpu_has(X86_FEATURE_SHSTK) || boot_cpu_has(X86_FEATURE_IBT)) {
10015 		rdmsrq(MSR_IA32_S_CET, kvm_host.s_cet);
10016 		/*
10017 		 * Linux doesn't yet support supervisor shadow stacks (SSS), so
10018 		 * KVM doesn't save/restore the associated MSRs, i.e. KVM may
10019 		 * clobber the host values.  Yell and refuse to load if SSS is
10020 		 * unexpectedly enabled, e.g. to avoid crashing the host.
10021 		 */
10022 		if (WARN_ON_ONCE(kvm_host.s_cet & CET_SHSTK_EN))
10023 			return -EIO;
10024 	}
10025 
10026 	memset(&kvm_caps, 0, sizeof(kvm_caps));
10027 
10028 	x86_emulator_cache = kvm_alloc_emulator_cache();
10029 	if (!x86_emulator_cache) {
10030 		pr_err("failed to allocate cache for x86 emulator\n");
10031 		return -ENOMEM;
10032 	}
10033 
10034 	user_return_msrs = alloc_percpu(struct kvm_user_return_msrs);
10035 	if (!user_return_msrs) {
10036 		pr_err("failed to allocate percpu kvm_user_return_msrs\n");
10037 		r = -ENOMEM;
10038 		goto out_free_x86_emulator_cache;
10039 	}
10040 	kvm_nr_uret_msrs = 0;
10041 
10042 	r = kvm_mmu_vendor_module_init();
10043 	if (r)
10044 		goto out_free_percpu;
10045 
10046 	kvm_caps.supported_vm_types = BIT(KVM_X86_DEFAULT_VM);
10047 	kvm_caps.supported_mce_cap = MCG_CTL_P | MCG_SER_P;
10048 
10049 	if (boot_cpu_has(X86_FEATURE_XSAVE)) {
10050 		kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
10051 		kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
10052 	}
10053 
10054 	if (boot_cpu_has(X86_FEATURE_XSAVES)) {
10055 		rdmsrq(MSR_IA32_XSS, kvm_host.xss);
10056 		kvm_caps.supported_xss = kvm_host.xss & KVM_SUPPORTED_XSS;
10057 	}
10058 
10059 	kvm_caps.supported_quirks = KVM_X86_VALID_QUIRKS;
10060 	kvm_caps.inapplicable_quirks = KVM_X86_CONDITIONAL_QUIRKS;
10061 
10062 	rdmsrq_safe(MSR_EFER, &kvm_host.efer);
10063 
10064 	kvm_init_pmu_capability(ops->pmu_ops);
10065 
10066 	if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
10067 		rdmsrq(MSR_IA32_ARCH_CAPABILITIES, kvm_host.arch_capabilities);
10068 
10069 	r = ops->hardware_setup();
10070 	if (r != 0)
10071 		goto out_mmu_exit;
10072 
10073 	enable_device_posted_irqs &= enable_apicv &&
10074 				     irq_remapping_cap(IRQ_POSTING_CAP);
10075 
10076 	kvm_ops_update(ops);
10077 
10078 	for_each_online_cpu(cpu) {
10079 		smp_call_function_single(cpu, kvm_x86_check_cpu_compat, &r, 1);
10080 		if (r < 0)
10081 			goto out_unwind_ops;
10082 	}
10083 
10084 	/*
10085 	 * Point of no return!  DO NOT add error paths below this point unless
10086 	 * absolutely necessary, as most operations from this point forward
10087 	 * require unwinding.
10088 	 */
10089 	kvm_timer_init();
10090 
10091 	if (pi_inject_timer == -1)
10092 		pi_inject_timer = housekeeping_enabled(HK_TYPE_TIMER);
10093 #ifdef CONFIG_X86_64
10094 	pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
10095 
10096 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
10097 		set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
10098 #endif
10099 
10100 	kvm_register_perf_callbacks(ops->handle_intel_pt_intr);
10101 
10102 	if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
10103 		kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
10104 
10105 	/* KVM always ignores guest PAT for shadow paging.  */
10106 	if (!tdp_enabled)
10107 		kvm_caps.supported_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT;
10108 
10109 	if (!kvm_cpu_cap_has(X86_FEATURE_XSAVES))
10110 		kvm_caps.supported_xss = 0;
10111 
10112 	if (!kvm_cpu_cap_has(X86_FEATURE_SHSTK) &&
10113 	    !kvm_cpu_cap_has(X86_FEATURE_IBT))
10114 		kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
10115 
10116 	if ((kvm_caps.supported_xss & XFEATURE_MASK_CET_ALL) != XFEATURE_MASK_CET_ALL) {
10117 		kvm_cpu_cap_clear(X86_FEATURE_SHSTK);
10118 		kvm_cpu_cap_clear(X86_FEATURE_IBT);
10119 		kvm_caps.supported_xss &= ~XFEATURE_MASK_CET_ALL;
10120 	}
10121 
10122 	if (kvm_caps.has_tsc_control) {
10123 		/*
10124 		 * Make sure the user can only configure tsc_khz values that
10125 		 * fit into a signed integer.
10126 		 * A min value is not calculated because it will always
10127 		 * be 1 on all machines.
10128 		 */
10129 		u64 max = min(0x7fffffffULL,
10130 			      __scale_tsc(kvm_caps.max_tsc_scaling_ratio, tsc_khz));
10131 		kvm_caps.max_guest_tsc_khz = max;
10132 	}
10133 	kvm_caps.default_tsc_scaling_ratio = 1ULL << kvm_caps.tsc_scaling_ratio_frac_bits;
10134 	kvm_init_msr_lists();
10135 	return 0;
10136 
10137 out_unwind_ops:
10138 	kvm_x86_ops.enable_virtualization_cpu = NULL;
10139 	kvm_x86_call(hardware_unsetup)();
10140 out_mmu_exit:
10141 	kvm_mmu_vendor_module_exit();
10142 out_free_percpu:
10143 	free_percpu(user_return_msrs);
10144 out_free_x86_emulator_cache:
10145 	kmem_cache_destroy(x86_emulator_cache);
10146 	return r;
10147 }
10148 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_init);
10149 
kvm_x86_vendor_exit(void)10150 void kvm_x86_vendor_exit(void)
10151 {
10152 	kvm_unregister_perf_callbacks();
10153 
10154 #ifdef CONFIG_X86_64
10155 	if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
10156 		clear_hv_tscchange_cb();
10157 #endif
10158 	kvm_lapic_exit();
10159 
10160 	if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
10161 		cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
10162 					    CPUFREQ_TRANSITION_NOTIFIER);
10163 		cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
10164 	}
10165 #ifdef CONFIG_X86_64
10166 	pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
10167 	irq_work_sync(&pvclock_irq_work);
10168 	cancel_work_sync(&pvclock_gtod_work);
10169 #endif
10170 	kvm_x86_call(hardware_unsetup)();
10171 	kvm_mmu_vendor_module_exit();
10172 	free_percpu(user_return_msrs);
10173 	kmem_cache_destroy(x86_emulator_cache);
10174 #ifdef CONFIG_KVM_XEN
10175 	static_key_deferred_flush(&kvm_xen_enabled);
10176 	WARN_ON(static_branch_unlikely(&kvm_xen_enabled.key));
10177 #endif
10178 	mutex_lock(&vendor_module_lock);
10179 	kvm_x86_ops.enable_virtualization_cpu = NULL;
10180 	mutex_unlock(&vendor_module_lock);
10181 }
10182 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_x86_vendor_exit);
10183 
10184 #ifdef CONFIG_X86_64
kvm_pv_clock_pairing(struct kvm_vcpu * vcpu,gpa_t paddr,unsigned long clock_type)10185 static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
10186 			        unsigned long clock_type)
10187 {
10188 	struct kvm_clock_pairing clock_pairing;
10189 	struct timespec64 ts;
10190 	u64 cycle;
10191 	int ret;
10192 
10193 	if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
10194 		return -KVM_EOPNOTSUPP;
10195 
10196 	/*
10197 	 * When tsc is in permanent catchup mode guests won't be able to use
10198 	 * pvclock_read_retry loop to get consistent view of pvclock
10199 	 */
10200 	if (vcpu->arch.tsc_always_catchup)
10201 		return -KVM_EOPNOTSUPP;
10202 
10203 	if (!kvm_get_walltime_and_clockread(&ts, &cycle))
10204 		return -KVM_EOPNOTSUPP;
10205 
10206 	clock_pairing.sec = ts.tv_sec;
10207 	clock_pairing.nsec = ts.tv_nsec;
10208 	clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
10209 	clock_pairing.flags = 0;
10210 	memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
10211 
10212 	ret = 0;
10213 	if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
10214 			    sizeof(struct kvm_clock_pairing)))
10215 		ret = -KVM_EFAULT;
10216 
10217 	return ret;
10218 }
10219 #endif
10220 
10221 /*
10222  * kvm_pv_kick_cpu_op:  Kick a vcpu.
10223  *
10224  * @apicid - apicid of vcpu to be kicked.
10225  */
kvm_pv_kick_cpu_op(struct kvm * kvm,int apicid)10226 static void kvm_pv_kick_cpu_op(struct kvm *kvm, int apicid)
10227 {
10228 	/*
10229 	 * All other fields are unused for APIC_DM_REMRD, but may be consumed by
10230 	 * common code, e.g. for tracing. Defer initialization to the compiler.
10231 	 */
10232 	struct kvm_lapic_irq lapic_irq = {
10233 		.delivery_mode = APIC_DM_REMRD,
10234 		.dest_mode = APIC_DEST_PHYSICAL,
10235 		.shorthand = APIC_DEST_NOSHORT,
10236 		.dest_id = apicid,
10237 	};
10238 
10239 	kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
10240 }
10241 
kvm_apicv_activated(struct kvm * kvm)10242 bool kvm_apicv_activated(struct kvm *kvm)
10243 {
10244 	return (READ_ONCE(kvm->arch.apicv_inhibit_reasons) == 0);
10245 }
10246 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_apicv_activated);
10247 
kvm_vcpu_apicv_activated(struct kvm_vcpu * vcpu)10248 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu)
10249 {
10250 	ulong vm_reasons = READ_ONCE(vcpu->kvm->arch.apicv_inhibit_reasons);
10251 	ulong vcpu_reasons =
10252 			kvm_x86_call(vcpu_get_apicv_inhibit_reasons)(vcpu);
10253 
10254 	return (vm_reasons | vcpu_reasons) == 0;
10255 }
10256 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_apicv_activated);
10257 
set_or_clear_apicv_inhibit(unsigned long * inhibits,enum kvm_apicv_inhibit reason,bool set)10258 static void set_or_clear_apicv_inhibit(unsigned long *inhibits,
10259 				       enum kvm_apicv_inhibit reason, bool set)
10260 {
10261 	const struct trace_print_flags apicv_inhibits[] = { APICV_INHIBIT_REASONS };
10262 
10263 	BUILD_BUG_ON(ARRAY_SIZE(apicv_inhibits) != NR_APICV_INHIBIT_REASONS);
10264 
10265 	if (set)
10266 		__set_bit(reason, inhibits);
10267 	else
10268 		__clear_bit(reason, inhibits);
10269 
10270 	trace_kvm_apicv_inhibit_changed(reason, set, *inhibits);
10271 }
10272 
kvm_apicv_init(struct kvm * kvm)10273 static void kvm_apicv_init(struct kvm *kvm)
10274 {
10275 	enum kvm_apicv_inhibit reason = enable_apicv ? APICV_INHIBIT_REASON_ABSENT :
10276 						       APICV_INHIBIT_REASON_DISABLED;
10277 
10278 	set_or_clear_apicv_inhibit(&kvm->arch.apicv_inhibit_reasons, reason, true);
10279 
10280 	init_rwsem(&kvm->arch.apicv_update_lock);
10281 }
10282 
kvm_sched_yield(struct kvm_vcpu * vcpu,unsigned long dest_id)10283 static void kvm_sched_yield(struct kvm_vcpu *vcpu, unsigned long dest_id)
10284 {
10285 	struct kvm_vcpu *target = NULL;
10286 	struct kvm_apic_map *map;
10287 
10288 	vcpu->stat.directed_yield_attempted++;
10289 
10290 	if (single_task_running())
10291 		goto no_yield;
10292 
10293 	rcu_read_lock();
10294 	map = rcu_dereference(vcpu->kvm->arch.apic_map);
10295 
10296 	if (likely(map) && dest_id <= map->max_apic_id) {
10297 		dest_id = array_index_nospec(dest_id, map->max_apic_id + 1);
10298 		if (map->phys_map[dest_id])
10299 			target = map->phys_map[dest_id]->vcpu;
10300 	}
10301 
10302 	rcu_read_unlock();
10303 
10304 	if (!target || !READ_ONCE(target->ready))
10305 		goto no_yield;
10306 
10307 	/* Ignore requests to yield to self */
10308 	if (vcpu == target)
10309 		goto no_yield;
10310 
10311 	if (kvm_vcpu_yield_to(target) <= 0)
10312 		goto no_yield;
10313 
10314 	vcpu->stat.directed_yield_successful++;
10315 
10316 no_yield:
10317 	return;
10318 }
10319 
complete_hypercall_exit(struct kvm_vcpu * vcpu)10320 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
10321 {
10322 	u64 ret = vcpu->run->hypercall.ret;
10323 
10324 	if (!is_64_bit_hypercall(vcpu))
10325 		ret = (u32)ret;
10326 	kvm_rax_write(vcpu, ret);
10327 	return kvm_skip_emulated_instruction(vcpu);
10328 }
10329 
____kvm_emulate_hypercall(struct kvm_vcpu * vcpu,int cpl,int (* complete_hypercall)(struct kvm_vcpu *))10330 int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
10331 			      int (*complete_hypercall)(struct kvm_vcpu *))
10332 {
10333 	unsigned long ret;
10334 	unsigned long nr = kvm_rax_read(vcpu);
10335 	unsigned long a0 = kvm_rbx_read(vcpu);
10336 	unsigned long a1 = kvm_rcx_read(vcpu);
10337 	unsigned long a2 = kvm_rdx_read(vcpu);
10338 	unsigned long a3 = kvm_rsi_read(vcpu);
10339 	int op_64_bit = is_64_bit_hypercall(vcpu);
10340 
10341 	++vcpu->stat.hypercalls;
10342 
10343 	trace_kvm_hypercall(nr, a0, a1, a2, a3);
10344 
10345 	if (!op_64_bit) {
10346 		nr &= 0xFFFFFFFF;
10347 		a0 &= 0xFFFFFFFF;
10348 		a1 &= 0xFFFFFFFF;
10349 		a2 &= 0xFFFFFFFF;
10350 		a3 &= 0xFFFFFFFF;
10351 	}
10352 
10353 	if (cpl) {
10354 		ret = -KVM_EPERM;
10355 		goto out;
10356 	}
10357 
10358 	ret = -KVM_ENOSYS;
10359 
10360 	switch (nr) {
10361 	case KVM_HC_VAPIC_POLL_IRQ:
10362 		ret = 0;
10363 		break;
10364 	case KVM_HC_KICK_CPU:
10365 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_UNHALT))
10366 			break;
10367 
10368 		kvm_pv_kick_cpu_op(vcpu->kvm, a1);
10369 		kvm_sched_yield(vcpu, a1);
10370 		ret = 0;
10371 		break;
10372 #ifdef CONFIG_X86_64
10373 	case KVM_HC_CLOCK_PAIRING:
10374 		ret = kvm_pv_clock_pairing(vcpu, a0, a1);
10375 		break;
10376 #endif
10377 	case KVM_HC_SEND_IPI:
10378 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SEND_IPI))
10379 			break;
10380 
10381 		ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
10382 		break;
10383 	case KVM_HC_SCHED_YIELD:
10384 		if (!guest_pv_has(vcpu, KVM_FEATURE_PV_SCHED_YIELD))
10385 			break;
10386 
10387 		kvm_sched_yield(vcpu, a0);
10388 		ret = 0;
10389 		break;
10390 	case KVM_HC_MAP_GPA_RANGE: {
10391 		u64 gpa = a0, npages = a1, attrs = a2;
10392 
10393 		ret = -KVM_ENOSYS;
10394 		if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE))
10395 			break;
10396 
10397 		if (!PAGE_ALIGNED(gpa) || !npages ||
10398 		    gpa_to_gfn(gpa) + npages <= gpa_to_gfn(gpa)) {
10399 			ret = -KVM_EINVAL;
10400 			break;
10401 		}
10402 
10403 		vcpu->run->exit_reason        = KVM_EXIT_HYPERCALL;
10404 		vcpu->run->hypercall.nr       = KVM_HC_MAP_GPA_RANGE;
10405 		/*
10406 		 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
10407 		 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
10408 		 * it was always zero on KVM_EXIT_HYPERCALL.  Since KVM is now overwriting
10409 		 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
10410 		 */
10411 		vcpu->run->hypercall.ret = 0;
10412 		vcpu->run->hypercall.args[0]  = gpa;
10413 		vcpu->run->hypercall.args[1]  = npages;
10414 		vcpu->run->hypercall.args[2]  = attrs;
10415 		vcpu->run->hypercall.flags    = 0;
10416 		if (op_64_bit)
10417 			vcpu->run->hypercall.flags |= KVM_EXIT_HYPERCALL_LONG_MODE;
10418 
10419 		WARN_ON_ONCE(vcpu->run->hypercall.flags & KVM_EXIT_HYPERCALL_MBZ);
10420 		vcpu->arch.complete_userspace_io = complete_hypercall;
10421 		return 0;
10422 	}
10423 	default:
10424 		ret = -KVM_ENOSYS;
10425 		break;
10426 	}
10427 
10428 out:
10429 	vcpu->run->hypercall.ret = ret;
10430 	return 1;
10431 }
10432 EXPORT_SYMBOL_FOR_KVM_INTERNAL(____kvm_emulate_hypercall);
10433 
kvm_emulate_hypercall(struct kvm_vcpu * vcpu)10434 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
10435 {
10436 	if (kvm_xen_hypercall_enabled(vcpu->kvm))
10437 		return kvm_xen_hypercall(vcpu);
10438 
10439 	if (kvm_hv_hypercall_enabled(vcpu))
10440 		return kvm_hv_hypercall(vcpu);
10441 
10442 	return __kvm_emulate_hypercall(vcpu, kvm_x86_call(get_cpl)(vcpu),
10443 				       complete_hypercall_exit);
10444 }
10445 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_hypercall);
10446 
emulator_fix_hypercall(struct x86_emulate_ctxt * ctxt)10447 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
10448 {
10449 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
10450 	char instruction[3];
10451 	unsigned long rip = kvm_rip_read(vcpu);
10452 
10453 	/*
10454 	 * If the quirk is disabled, synthesize a #UD and let the guest pick up
10455 	 * the pieces.
10456 	 */
10457 	if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_FIX_HYPERCALL_INSN)) {
10458 		ctxt->exception.error_code_valid = false;
10459 		ctxt->exception.vector = UD_VECTOR;
10460 		ctxt->have_exception = true;
10461 		return X86EMUL_PROPAGATE_FAULT;
10462 	}
10463 
10464 	kvm_x86_call(patch_hypercall)(vcpu, instruction);
10465 
10466 	return emulator_write_emulated(ctxt, rip, instruction, 3,
10467 		&ctxt->exception);
10468 }
10469 
dm_request_for_irq_injection(struct kvm_vcpu * vcpu)10470 static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
10471 {
10472 	return vcpu->run->request_interrupt_window &&
10473 		likely(!pic_in_kernel(vcpu->kvm));
10474 }
10475 
10476 /* Called within kvm->srcu read side.  */
post_kvm_run_save(struct kvm_vcpu * vcpu)10477 static void post_kvm_run_save(struct kvm_vcpu *vcpu)
10478 {
10479 	struct kvm_run *kvm_run = vcpu->run;
10480 
10481 	kvm_run->if_flag = kvm_x86_call(get_if_flag)(vcpu);
10482 	kvm_run->cr8 = kvm_get_cr8(vcpu);
10483 	kvm_run->apic_base = vcpu->arch.apic_base;
10484 
10485 	kvm_run->ready_for_interrupt_injection =
10486 		pic_in_kernel(vcpu->kvm) ||
10487 		kvm_vcpu_ready_for_interrupt_injection(vcpu);
10488 
10489 	if (is_smm(vcpu))
10490 		kvm_run->flags |= KVM_RUN_X86_SMM;
10491 	if (is_guest_mode(vcpu))
10492 		kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
10493 }
10494 
update_cr8_intercept(struct kvm_vcpu * vcpu)10495 static void update_cr8_intercept(struct kvm_vcpu *vcpu)
10496 {
10497 	int max_irr, tpr;
10498 
10499 	if (!kvm_x86_ops.update_cr8_intercept)
10500 		return;
10501 
10502 	if (!lapic_in_kernel(vcpu))
10503 		return;
10504 
10505 	if (vcpu->arch.apic->apicv_active)
10506 		return;
10507 
10508 	if (!vcpu->arch.apic->vapic_addr)
10509 		max_irr = kvm_lapic_find_highest_irr(vcpu);
10510 	else
10511 		max_irr = -1;
10512 
10513 	if (max_irr != -1)
10514 		max_irr >>= 4;
10515 
10516 	tpr = kvm_lapic_get_cr8(vcpu);
10517 
10518 	kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
10519 }
10520 
10521 
kvm_check_nested_events(struct kvm_vcpu * vcpu)10522 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
10523 {
10524 	if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
10525 		kvm_x86_ops.nested_ops->triple_fault(vcpu);
10526 		return 1;
10527 	}
10528 
10529 	return kvm_x86_ops.nested_ops->check_events(vcpu);
10530 }
10531 
kvm_inject_exception(struct kvm_vcpu * vcpu)10532 static void kvm_inject_exception(struct kvm_vcpu *vcpu)
10533 {
10534 	/*
10535 	 * Suppress the error code if the vCPU is in Real Mode, as Real Mode
10536 	 * exceptions don't report error codes.  The presence of an error code
10537 	 * is carried with the exception and only stripped when the exception
10538 	 * is injected as intercepted #PF VM-Exits for AMD's Paged Real Mode do
10539 	 * report an error code despite the CPU being in Real Mode.
10540 	 */
10541 	vcpu->arch.exception.has_error_code &= is_protmode(vcpu);
10542 
10543 	trace_kvm_inj_exception(vcpu->arch.exception.vector,
10544 				vcpu->arch.exception.has_error_code,
10545 				vcpu->arch.exception.error_code,
10546 				vcpu->arch.exception.injected);
10547 
10548 	kvm_x86_call(inject_exception)(vcpu);
10549 }
10550 
10551 /*
10552  * Check for any event (interrupt or exception) that is ready to be injected,
10553  * and if there is at least one event, inject the event with the highest
10554  * priority.  This handles both "pending" events, i.e. events that have never
10555  * been injected into the guest, and "injected" events, i.e. events that were
10556  * injected as part of a previous VM-Enter, but weren't successfully delivered
10557  * and need to be re-injected.
10558  *
10559  * Note, this is not guaranteed to be invoked on a guest instruction boundary,
10560  * i.e. doesn't guarantee that there's an event window in the guest.  KVM must
10561  * be able to inject exceptions in the "middle" of an instruction, and so must
10562  * also be able to re-inject NMIs and IRQs in the middle of an instruction.
10563  * I.e. for exceptions and re-injected events, NOT invoking this on instruction
10564  * boundaries is necessary and correct.
10565  *
10566  * For simplicity, KVM uses a single path to inject all events (except events
10567  * that are injected directly from L1 to L2) and doesn't explicitly track
10568  * instruction boundaries for asynchronous events.  However, because VM-Exits
10569  * that can occur during instruction execution typically result in KVM skipping
10570  * the instruction or injecting an exception, e.g. instruction and exception
10571  * intercepts, and because pending exceptions have higher priority than pending
10572  * interrupts, KVM still honors instruction boundaries in most scenarios.
10573  *
10574  * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
10575  * the instruction or inject an exception, then KVM can incorrecty inject a new
10576  * asynchronous event if the event became pending after the CPU fetched the
10577  * instruction (in the guest).  E.g. if a page fault (#PF, #NPF, EPT violation)
10578  * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
10579  * injected on the restarted instruction instead of being deferred until the
10580  * instruction completes.
10581  *
10582  * In practice, this virtualization hole is unlikely to be observed by the
10583  * guest, and even less likely to cause functional problems.  To detect the
10584  * hole, the guest would have to trigger an event on a side effect of an early
10585  * phase of instruction execution, e.g. on the instruction fetch from memory.
10586  * And for it to be a functional problem, the guest would need to depend on the
10587  * ordering between that side effect, the instruction completing, _and_ the
10588  * delivery of the asynchronous event.
10589  */
kvm_check_and_inject_events(struct kvm_vcpu * vcpu,bool * req_immediate_exit)10590 static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
10591 				       bool *req_immediate_exit)
10592 {
10593 	bool can_inject;
10594 	int r;
10595 
10596 	/*
10597 	 * Process nested events first, as nested VM-Exit supersedes event
10598 	 * re-injection.  If there's an event queued for re-injection, it will
10599 	 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
10600 	 */
10601 	if (is_guest_mode(vcpu))
10602 		r = kvm_check_nested_events(vcpu);
10603 	else
10604 		r = 0;
10605 
10606 	/*
10607 	 * Re-inject exceptions and events *especially* if immediate entry+exit
10608 	 * to/from L2 is needed, as any event that has already been injected
10609 	 * into L2 needs to complete its lifecycle before injecting a new event.
10610 	 *
10611 	 * Don't re-inject an NMI or interrupt if there is a pending exception.
10612 	 * This collision arises if an exception occurred while vectoring the
10613 	 * injected event, KVM intercepted said exception, and KVM ultimately
10614 	 * determined the fault belongs to the guest and queues the exception
10615 	 * for injection back into the guest.
10616 	 *
10617 	 * "Injected" interrupts can also collide with pending exceptions if
10618 	 * userspace ignores the "ready for injection" flag and blindly queues
10619 	 * an interrupt.  In that case, prioritizing the exception is correct,
10620 	 * as the exception "occurred" before the exit to userspace.  Trap-like
10621 	 * exceptions, e.g. most #DBs, have higher priority than interrupts.
10622 	 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
10623 	 * priority, they're only generated (pended) during instruction
10624 	 * execution, and interrupts are recognized at instruction boundaries.
10625 	 * Thus a pending fault-like exception means the fault occurred on the
10626 	 * *previous* instruction and must be serviced prior to recognizing any
10627 	 * new events in order to fully complete the previous instruction.
10628 	 */
10629 	if (vcpu->arch.exception.injected)
10630 		kvm_inject_exception(vcpu);
10631 	else if (kvm_is_exception_pending(vcpu))
10632 		; /* see above */
10633 	else if (vcpu->arch.nmi_injected)
10634 		kvm_x86_call(inject_nmi)(vcpu);
10635 	else if (vcpu->arch.interrupt.injected)
10636 		kvm_x86_call(inject_irq)(vcpu, true);
10637 
10638 	/*
10639 	 * Exceptions that morph to VM-Exits are handled above, and pending
10640 	 * exceptions on top of injected exceptions that do not VM-Exit should
10641 	 * either morph to #DF or, sadly, override the injected exception.
10642 	 */
10643 	WARN_ON_ONCE(vcpu->arch.exception.injected &&
10644 		     vcpu->arch.exception.pending);
10645 
10646 	/*
10647 	 * Bail if immediate entry+exit to/from the guest is needed to complete
10648 	 * nested VM-Enter or event re-injection so that a different pending
10649 	 * event can be serviced (or if KVM needs to exit to userspace).
10650 	 *
10651 	 * Otherwise, continue processing events even if VM-Exit occurred.  The
10652 	 * VM-Exit will have cleared exceptions that were meant for L2, but
10653 	 * there may now be events that can be injected into L1.
10654 	 */
10655 	if (r < 0)
10656 		goto out;
10657 
10658 	/*
10659 	 * A pending exception VM-Exit should either result in nested VM-Exit
10660 	 * or force an immediate re-entry and exit to/from L2, and exception
10661 	 * VM-Exits cannot be injected (flag should _never_ be set).
10662 	 */
10663 	WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
10664 		     vcpu->arch.exception_vmexit.pending);
10665 
10666 	/*
10667 	 * New events, other than exceptions, cannot be injected if KVM needs
10668 	 * to re-inject a previous event.  See above comments on re-injecting
10669 	 * for why pending exceptions get priority.
10670 	 */
10671 	can_inject = !kvm_event_needs_reinjection(vcpu);
10672 
10673 	if (vcpu->arch.exception.pending) {
10674 		/*
10675 		 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
10676 		 * value pushed on the stack.  Trap-like exception and all #DBs
10677 		 * leave RF as-is (KVM follows Intel's behavior in this regard;
10678 		 * AMD states that code breakpoint #DBs excplitly clear RF=0).
10679 		 *
10680 		 * Note, most versions of Intel's SDM and AMD's APM incorrectly
10681 		 * describe the behavior of General Detect #DBs, which are
10682 		 * fault-like.  They do _not_ set RF, a la code breakpoints.
10683 		 */
10684 		if (exception_type(vcpu->arch.exception.vector) == EXCPT_FAULT)
10685 			__kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
10686 					     X86_EFLAGS_RF);
10687 
10688 		if (vcpu->arch.exception.vector == DB_VECTOR) {
10689 			kvm_deliver_exception_payload(vcpu, &vcpu->arch.exception);
10690 			if (vcpu->arch.dr7 & DR7_GD) {
10691 				vcpu->arch.dr7 &= ~DR7_GD;
10692 				kvm_update_dr7(vcpu);
10693 			}
10694 		}
10695 
10696 		kvm_inject_exception(vcpu);
10697 
10698 		vcpu->arch.exception.pending = false;
10699 		vcpu->arch.exception.injected = true;
10700 
10701 		can_inject = false;
10702 	}
10703 
10704 	/* Don't inject interrupts if the user asked to avoid doing so */
10705 	if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ)
10706 		return 0;
10707 
10708 	/*
10709 	 * Finally, inject interrupt events.  If an event cannot be injected
10710 	 * due to architectural conditions (e.g. IF=0) a window-open exit
10711 	 * will re-request KVM_REQ_EVENT.  Sometimes however an event is pending
10712 	 * and can architecturally be injected, but we cannot do it right now:
10713 	 * an interrupt could have arrived just now and we have to inject it
10714 	 * as a vmexit, or there could already an event in the queue, which is
10715 	 * indicated by can_inject.  In that case we request an immediate exit
10716 	 * in order to make progress and get back here for another iteration.
10717 	 * The kvm_x86_ops hooks communicate this by returning -EBUSY.
10718 	 */
10719 #ifdef CONFIG_KVM_SMM
10720 	if (vcpu->arch.smi_pending) {
10721 		r = can_inject ? kvm_x86_call(smi_allowed)(vcpu, true) :
10722 				 -EBUSY;
10723 		if (r < 0)
10724 			goto out;
10725 		if (r) {
10726 			vcpu->arch.smi_pending = false;
10727 			++vcpu->arch.smi_count;
10728 			enter_smm(vcpu);
10729 			can_inject = false;
10730 		} else
10731 			kvm_x86_call(enable_smi_window)(vcpu);
10732 	}
10733 #endif
10734 
10735 	if (vcpu->arch.nmi_pending) {
10736 		r = can_inject ? kvm_x86_call(nmi_allowed)(vcpu, true) :
10737 				 -EBUSY;
10738 		if (r < 0)
10739 			goto out;
10740 		if (r) {
10741 			--vcpu->arch.nmi_pending;
10742 			vcpu->arch.nmi_injected = true;
10743 			kvm_x86_call(inject_nmi)(vcpu);
10744 			can_inject = false;
10745 			WARN_ON(kvm_x86_call(nmi_allowed)(vcpu, true) < 0);
10746 		}
10747 		if (vcpu->arch.nmi_pending)
10748 			kvm_x86_call(enable_nmi_window)(vcpu);
10749 	}
10750 
10751 	if (kvm_cpu_has_injectable_intr(vcpu)) {
10752 		r = can_inject ? kvm_x86_call(interrupt_allowed)(vcpu, true) :
10753 				 -EBUSY;
10754 		if (r < 0)
10755 			goto out;
10756 		if (r) {
10757 			int irq = kvm_cpu_get_interrupt(vcpu);
10758 
10759 			if (!WARN_ON_ONCE(irq == -1)) {
10760 				kvm_queue_interrupt(vcpu, irq, false);
10761 				kvm_x86_call(inject_irq)(vcpu, false);
10762 				WARN_ON(kvm_x86_call(interrupt_allowed)(vcpu, true) < 0);
10763 			}
10764 		}
10765 		if (kvm_cpu_has_injectable_intr(vcpu))
10766 			kvm_x86_call(enable_irq_window)(vcpu);
10767 	}
10768 
10769 	if (is_guest_mode(vcpu) &&
10770 	    kvm_x86_ops.nested_ops->has_events &&
10771 	    kvm_x86_ops.nested_ops->has_events(vcpu, true))
10772 		*req_immediate_exit = true;
10773 
10774 	/*
10775 	 * KVM must never queue a new exception while injecting an event; KVM
10776 	 * is done emulating and should only propagate the to-be-injected event
10777 	 * to the VMCS/VMCB.  Queueing a new exception can put the vCPU into an
10778 	 * infinite loop as KVM will bail from VM-Enter to inject the pending
10779 	 * exception and start the cycle all over.
10780 	 *
10781 	 * Exempt triple faults as they have special handling and won't put the
10782 	 * vCPU into an infinite loop.  Triple fault can be queued when running
10783 	 * VMX without unrestricted guest, as that requires KVM to emulate Real
10784 	 * Mode events (see kvm_inject_realmode_interrupt()).
10785 	 */
10786 	WARN_ON_ONCE(vcpu->arch.exception.pending ||
10787 		     vcpu->arch.exception_vmexit.pending);
10788 	return 0;
10789 
10790 out:
10791 	if (r == -EBUSY) {
10792 		*req_immediate_exit = true;
10793 		r = 0;
10794 	}
10795 	return r;
10796 }
10797 
process_nmi(struct kvm_vcpu * vcpu)10798 static void process_nmi(struct kvm_vcpu *vcpu)
10799 {
10800 	unsigned int limit;
10801 
10802 	/*
10803 	 * x86 is limited to one NMI pending, but because KVM can't react to
10804 	 * incoming NMIs as quickly as bare metal, e.g. if the vCPU is
10805 	 * scheduled out, KVM needs to play nice with two queued NMIs showing
10806 	 * up at the same time.  To handle this scenario, allow two NMIs to be
10807 	 * (temporarily) pending so long as NMIs are not blocked and KVM is not
10808 	 * waiting for a previous NMI injection to complete (which effectively
10809 	 * blocks NMIs).  KVM will immediately inject one of the two NMIs, and
10810 	 * will request an NMI window to handle the second NMI.
10811 	 */
10812 	if (kvm_x86_call(get_nmi_mask)(vcpu) || vcpu->arch.nmi_injected)
10813 		limit = 1;
10814 	else
10815 		limit = 2;
10816 
10817 	/*
10818 	 * Adjust the limit to account for pending virtual NMIs, which aren't
10819 	 * tracked in vcpu->arch.nmi_pending.
10820 	 */
10821 	if (kvm_x86_call(is_vnmi_pending)(vcpu))
10822 		limit--;
10823 
10824 	vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
10825 	vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
10826 
10827 	if (vcpu->arch.nmi_pending &&
10828 	    (kvm_x86_call(set_vnmi_pending)(vcpu)))
10829 		vcpu->arch.nmi_pending--;
10830 
10831 	if (vcpu->arch.nmi_pending)
10832 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10833 }
10834 
10835 /* Return total number of NMIs pending injection to the VM */
kvm_get_nr_pending_nmis(struct kvm_vcpu * vcpu)10836 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu)
10837 {
10838 	return vcpu->arch.nmi_pending +
10839 	       kvm_x86_call(is_vnmi_pending)(vcpu);
10840 }
10841 
kvm_make_scan_ioapic_request_mask(struct kvm * kvm,unsigned long * vcpu_bitmap)10842 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
10843 				       unsigned long *vcpu_bitmap)
10844 {
10845 	kvm_make_vcpus_request_mask(kvm, KVM_REQ_SCAN_IOAPIC, vcpu_bitmap);
10846 }
10847 
kvm_make_scan_ioapic_request(struct kvm * kvm)10848 void kvm_make_scan_ioapic_request(struct kvm *kvm)
10849 {
10850 	kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
10851 }
10852 
__kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10853 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10854 {
10855 	struct kvm_lapic *apic = vcpu->arch.apic;
10856 	bool activate;
10857 
10858 	if (!lapic_in_kernel(vcpu))
10859 		return;
10860 
10861 	down_read(&vcpu->kvm->arch.apicv_update_lock);
10862 	preempt_disable();
10863 
10864 	/* Do not activate APICV when APIC is disabled */
10865 	activate = kvm_vcpu_apicv_activated(vcpu) &&
10866 		   (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED);
10867 
10868 	if (apic->apicv_active == activate)
10869 		goto out;
10870 
10871 	apic->apicv_active = activate;
10872 	kvm_apic_update_apicv(vcpu);
10873 	kvm_x86_call(refresh_apicv_exec_ctrl)(vcpu);
10874 
10875 	/*
10876 	 * When APICv gets disabled, we may still have injected interrupts
10877 	 * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
10878 	 * still active when the interrupt got accepted. Make sure
10879 	 * kvm_check_and_inject_events() is called to check for that.
10880 	 */
10881 	if (!apic->apicv_active)
10882 		kvm_make_request(KVM_REQ_EVENT, vcpu);
10883 
10884 out:
10885 	preempt_enable();
10886 	up_read(&vcpu->kvm->arch.apicv_update_lock);
10887 }
10888 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_vcpu_update_apicv);
10889 
kvm_vcpu_update_apicv(struct kvm_vcpu * vcpu)10890 static void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
10891 {
10892 	if (!lapic_in_kernel(vcpu))
10893 		return;
10894 
10895 	/*
10896 	 * Due to sharing page tables across vCPUs, the xAPIC memslot must be
10897 	 * deleted if any vCPU has xAPIC virtualization and x2APIC enabled, but
10898 	 * and hardware doesn't support x2APIC virtualization.  E.g. some AMD
10899 	 * CPUs support AVIC but not x2APIC.  KVM still allows enabling AVIC in
10900 	 * this case so that KVM can use the AVIC doorbell to inject interrupts
10901 	 * to running vCPUs, but KVM must not create SPTEs for the APIC base as
10902 	 * the vCPU would incorrectly be able to access the vAPIC page via MMIO
10903 	 * despite being in x2APIC mode.  For simplicity, inhibiting the APIC
10904 	 * access page is sticky.
10905 	 */
10906 	if (apic_x2apic_mode(vcpu->arch.apic) &&
10907 	    kvm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization)
10908 		kvm_inhibit_apic_access_page(vcpu);
10909 
10910 	__kvm_vcpu_update_apicv(vcpu);
10911 }
10912 
__kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10913 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10914 				      enum kvm_apicv_inhibit reason, bool set)
10915 {
10916 	unsigned long old, new;
10917 
10918 	lockdep_assert_held_write(&kvm->arch.apicv_update_lock);
10919 
10920 	if (!(kvm_x86_ops.required_apicv_inhibits & BIT(reason)))
10921 		return;
10922 
10923 	old = new = kvm->arch.apicv_inhibit_reasons;
10924 
10925 	set_or_clear_apicv_inhibit(&new, reason, set);
10926 
10927 	if (!!old != !!new) {
10928 		/*
10929 		 * Kick all vCPUs before setting apicv_inhibit_reasons to avoid
10930 		 * false positives in the sanity check WARN in vcpu_enter_guest().
10931 		 * This task will wait for all vCPUs to ack the kick IRQ before
10932 		 * updating apicv_inhibit_reasons, and all other vCPUs will
10933 		 * block on acquiring apicv_update_lock so that vCPUs can't
10934 		 * redo vcpu_enter_guest() without seeing the new inhibit state.
10935 		 *
10936 		 * Note, holding apicv_update_lock and taking it in the read
10937 		 * side (handling the request) also prevents other vCPUs from
10938 		 * servicing the request with a stale apicv_inhibit_reasons.
10939 		 */
10940 		kvm_make_all_cpus_request(kvm, KVM_REQ_APICV_UPDATE);
10941 		kvm->arch.apicv_inhibit_reasons = new;
10942 		if (new) {
10943 			unsigned long gfn = gpa_to_gfn(APIC_DEFAULT_PHYS_BASE);
10944 			int idx = srcu_read_lock(&kvm->srcu);
10945 
10946 			kvm_zap_gfn_range(kvm, gfn, gfn+1);
10947 			srcu_read_unlock(&kvm->srcu, idx);
10948 		}
10949 	} else {
10950 		kvm->arch.apicv_inhibit_reasons = new;
10951 	}
10952 }
10953 
kvm_set_or_clear_apicv_inhibit(struct kvm * kvm,enum kvm_apicv_inhibit reason,bool set)10954 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
10955 				    enum kvm_apicv_inhibit reason, bool set)
10956 {
10957 	if (!enable_apicv)
10958 		return;
10959 
10960 	down_write(&kvm->arch.apicv_update_lock);
10961 	__kvm_set_or_clear_apicv_inhibit(kvm, reason, set);
10962 	up_write(&kvm->arch.apicv_update_lock);
10963 }
10964 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_or_clear_apicv_inhibit);
10965 
vcpu_scan_ioapic(struct kvm_vcpu * vcpu)10966 static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
10967 {
10968 	if (!kvm_apic_present(vcpu))
10969 		return;
10970 
10971 	bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
10972 	vcpu->arch.highest_stale_pending_ioapic_eoi = -1;
10973 
10974 	kvm_x86_call(sync_pir_to_irr)(vcpu);
10975 
10976 	if (irqchip_split(vcpu->kvm))
10977 		kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
10978 #ifdef CONFIG_KVM_IOAPIC
10979 	else if (ioapic_in_kernel(vcpu->kvm))
10980 		kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
10981 #endif
10982 
10983 	if (is_guest_mode(vcpu))
10984 		vcpu->arch.load_eoi_exitmap_pending = true;
10985 	else
10986 		kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
10987 }
10988 
vcpu_load_eoi_exitmap(struct kvm_vcpu * vcpu)10989 static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
10990 {
10991 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
10992 		return;
10993 
10994 #ifdef CONFIG_KVM_HYPERV
10995 	if (to_hv_vcpu(vcpu)) {
10996 		u64 eoi_exit_bitmap[4];
10997 
10998 		bitmap_or((ulong *)eoi_exit_bitmap,
10999 			  vcpu->arch.ioapic_handled_vectors,
11000 			  to_hv_synic(vcpu)->vec_bitmap, 256);
11001 		kvm_x86_call(load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
11002 		return;
11003 	}
11004 #endif
11005 	kvm_x86_call(load_eoi_exitmap)(
11006 		vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
11007 }
11008 
kvm_arch_guest_memory_reclaimed(struct kvm * kvm)11009 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm)
11010 {
11011 	kvm_x86_call(guest_memory_reclaimed)(kvm);
11012 }
11013 
kvm_vcpu_reload_apic_access_page(struct kvm_vcpu * vcpu)11014 static void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
11015 {
11016 	if (!lapic_in_kernel(vcpu))
11017 		return;
11018 
11019 	kvm_x86_call(set_apic_access_page_addr)(vcpu);
11020 }
11021 
11022 /*
11023  * Called within kvm->srcu read side.
11024  * Returns 1 to let vcpu_run() continue the guest execution loop without
11025  * exiting to the userspace.  Otherwise, the value will be returned to the
11026  * userspace.
11027  */
vcpu_enter_guest(struct kvm_vcpu * vcpu)11028 static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
11029 {
11030 	int r;
11031 	bool req_int_win =
11032 		dm_request_for_irq_injection(vcpu) &&
11033 		kvm_cpu_accept_dm_intr(vcpu);
11034 	fastpath_t exit_fastpath;
11035 	u64 run_flags, debug_ctl;
11036 
11037 	bool req_immediate_exit = false;
11038 
11039 	if (kvm_request_pending(vcpu)) {
11040 		if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu)) {
11041 			r = -EIO;
11042 			goto out;
11043 		}
11044 
11045 		if (kvm_dirty_ring_check_request(vcpu)) {
11046 			r = 0;
11047 			goto out;
11048 		}
11049 
11050 		if (kvm_check_request(KVM_REQ_GET_NESTED_STATE_PAGES, vcpu)) {
11051 			if (unlikely(!kvm_x86_ops.nested_ops->get_nested_state_pages(vcpu))) {
11052 				r = 0;
11053 				goto out;
11054 			}
11055 		}
11056 		if (kvm_check_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
11057 			kvm_mmu_free_obsolete_roots(vcpu);
11058 		if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
11059 			__kvm_migrate_timers(vcpu);
11060 		if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
11061 			kvm_update_masterclock(vcpu->kvm);
11062 		if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
11063 			kvm_gen_kvmclock_update(vcpu);
11064 		if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
11065 			r = kvm_guest_time_update(vcpu);
11066 			if (unlikely(r))
11067 				goto out;
11068 		}
11069 		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
11070 			kvm_mmu_sync_roots(vcpu);
11071 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
11072 			kvm_mmu_load_pgd(vcpu);
11073 
11074 		/*
11075 		 * Note, the order matters here, as flushing "all" TLB entries
11076 		 * also flushes the "current" TLB entries, i.e. servicing the
11077 		 * flush "all" will clear any request to flush "current".
11078 		 */
11079 		if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
11080 			kvm_vcpu_flush_tlb_all(vcpu);
11081 
11082 		kvm_service_local_tlb_flush_requests(vcpu);
11083 
11084 		/*
11085 		 * Fall back to a "full" guest flush if Hyper-V's precise
11086 		 * flushing fails.  Note, Hyper-V's flushing is per-vCPU, but
11087 		 * the flushes are considered "remote" and not "local" because
11088 		 * the requests can be initiated from other vCPUs.
11089 		 */
11090 #ifdef CONFIG_KVM_HYPERV
11091 		if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
11092 		    kvm_hv_vcpu_flush_tlb(vcpu))
11093 			kvm_vcpu_flush_tlb_guest(vcpu);
11094 #endif
11095 
11096 		if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
11097 			vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
11098 			r = 0;
11099 			goto out;
11100 		}
11101 		if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
11102 			if (is_guest_mode(vcpu))
11103 				kvm_x86_ops.nested_ops->triple_fault(vcpu);
11104 
11105 			if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
11106 				vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
11107 				vcpu->mmio_needed = 0;
11108 				r = 0;
11109 				goto out;
11110 			}
11111 		}
11112 		if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
11113 			/* Page is swapped out. Do synthetic halt */
11114 			vcpu->arch.apf.halted = true;
11115 			r = 1;
11116 			goto out;
11117 		}
11118 		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
11119 			record_steal_time(vcpu);
11120 		if (kvm_check_request(KVM_REQ_PMU, vcpu))
11121 			kvm_pmu_handle_event(vcpu);
11122 		if (kvm_check_request(KVM_REQ_PMI, vcpu))
11123 			kvm_pmu_deliver_pmi(vcpu);
11124 #ifdef CONFIG_KVM_SMM
11125 		if (kvm_check_request(KVM_REQ_SMI, vcpu))
11126 			process_smi(vcpu);
11127 #endif
11128 		if (kvm_check_request(KVM_REQ_NMI, vcpu))
11129 			process_nmi(vcpu);
11130 		if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
11131 			BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
11132 			if (test_bit(vcpu->arch.pending_ioapic_eoi,
11133 				     vcpu->arch.ioapic_handled_vectors)) {
11134 				vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
11135 				vcpu->run->eoi.vector =
11136 						vcpu->arch.pending_ioapic_eoi;
11137 				r = 0;
11138 				goto out;
11139 			}
11140 		}
11141 		if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
11142 			vcpu_scan_ioapic(vcpu);
11143 		if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
11144 			vcpu_load_eoi_exitmap(vcpu);
11145 		if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
11146 			kvm_vcpu_reload_apic_access_page(vcpu);
11147 #ifdef CONFIG_KVM_HYPERV
11148 		if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
11149 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
11150 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
11151 			vcpu->run->system_event.ndata = 0;
11152 			r = 0;
11153 			goto out;
11154 		}
11155 		if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
11156 			vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
11157 			vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
11158 			vcpu->run->system_event.ndata = 0;
11159 			r = 0;
11160 			goto out;
11161 		}
11162 		if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
11163 			struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
11164 
11165 			vcpu->run->exit_reason = KVM_EXIT_HYPERV;
11166 			vcpu->run->hyperv = hv_vcpu->exit;
11167 			r = 0;
11168 			goto out;
11169 		}
11170 
11171 		/*
11172 		 * KVM_REQ_HV_STIMER has to be processed after
11173 		 * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
11174 		 * depend on the guest clock being up-to-date
11175 		 */
11176 		if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
11177 			kvm_hv_process_stimers(vcpu);
11178 #endif
11179 		if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
11180 			kvm_vcpu_update_apicv(vcpu);
11181 		if (kvm_check_request(KVM_REQ_APF_READY, vcpu))
11182 			kvm_check_async_pf_completion(vcpu);
11183 
11184 		if (kvm_check_request(KVM_REQ_RECALC_INTERCEPTS, vcpu))
11185 			kvm_x86_call(recalc_intercepts)(vcpu);
11186 
11187 		if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
11188 			kvm_x86_call(update_cpu_dirty_logging)(vcpu);
11189 
11190 		if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
11191 			kvm_vcpu_reset(vcpu, true);
11192 			if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
11193 				r = 1;
11194 				goto out;
11195 			}
11196 		}
11197 	}
11198 
11199 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
11200 	    kvm_xen_has_interrupt(vcpu)) {
11201 		++vcpu->stat.req_event;
11202 		r = kvm_apic_accept_events(vcpu);
11203 		if (r < 0) {
11204 			r = 0;
11205 			goto out;
11206 		}
11207 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
11208 			r = 1;
11209 			goto out;
11210 		}
11211 
11212 		r = kvm_check_and_inject_events(vcpu, &req_immediate_exit);
11213 		if (r < 0) {
11214 			r = 0;
11215 			goto out;
11216 		}
11217 		if (req_int_win)
11218 			kvm_x86_call(enable_irq_window)(vcpu);
11219 
11220 		if (kvm_lapic_enabled(vcpu)) {
11221 			update_cr8_intercept(vcpu);
11222 			kvm_lapic_sync_to_vapic(vcpu);
11223 		}
11224 	}
11225 
11226 	r = kvm_mmu_reload(vcpu);
11227 	if (unlikely(r)) {
11228 		goto cancel_injection;
11229 	}
11230 
11231 	preempt_disable();
11232 
11233 	kvm_x86_call(prepare_switch_to_guest)(vcpu);
11234 
11235 	/*
11236 	 * Disable IRQs before setting IN_GUEST_MODE.  Posted interrupt
11237 	 * IPI are then delayed after guest entry, which ensures that they
11238 	 * result in virtual interrupt delivery.
11239 	 */
11240 	local_irq_disable();
11241 
11242 	/* Store vcpu->apicv_active before vcpu->mode.  */
11243 	smp_store_release(&vcpu->mode, IN_GUEST_MODE);
11244 
11245 	kvm_vcpu_srcu_read_unlock(vcpu);
11246 
11247 	/*
11248 	 * 1) We should set ->mode before checking ->requests.  Please see
11249 	 * the comment in kvm_vcpu_exiting_guest_mode().
11250 	 *
11251 	 * 2) For APICv, we should set ->mode before checking PID.ON. This
11252 	 * pairs with the memory barrier implicit in pi_test_and_set_on
11253 	 * (see vmx_deliver_posted_interrupt).
11254 	 *
11255 	 * 3) This also orders the write to mode from any reads to the page
11256 	 * tables done while the VCPU is running.  Please see the comment
11257 	 * in kvm_flush_remote_tlbs.
11258 	 */
11259 	smp_mb__after_srcu_read_unlock();
11260 
11261 	/*
11262 	 * Process pending posted interrupts to handle the case where the
11263 	 * notification IRQ arrived in the host, or was never sent (because the
11264 	 * target vCPU wasn't running).  Do this regardless of the vCPU's APICv
11265 	 * status, KVM doesn't update assigned devices when APICv is inhibited,
11266 	 * i.e. they can post interrupts even if APICv is temporarily disabled.
11267 	 */
11268 	if (kvm_lapic_enabled(vcpu))
11269 		kvm_x86_call(sync_pir_to_irr)(vcpu);
11270 
11271 	if (kvm_vcpu_exit_request(vcpu)) {
11272 		vcpu->mode = OUTSIDE_GUEST_MODE;
11273 		smp_wmb();
11274 		local_irq_enable();
11275 		preempt_enable();
11276 		kvm_vcpu_srcu_read_lock(vcpu);
11277 		r = 1;
11278 		goto cancel_injection;
11279 	}
11280 
11281 	run_flags = 0;
11282 	if (req_immediate_exit) {
11283 		run_flags |= KVM_RUN_FORCE_IMMEDIATE_EXIT;
11284 		kvm_make_request(KVM_REQ_EVENT, vcpu);
11285 	}
11286 
11287 	fpregs_assert_state_consistent();
11288 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
11289 		switch_fpu_return();
11290 
11291 	if (vcpu->arch.guest_fpu.xfd_err)
11292 		wrmsrq(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
11293 
11294 	if (unlikely(vcpu->arch.switch_db_regs &&
11295 		     !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
11296 		set_debugreg(DR7_FIXED_1, 7);
11297 		set_debugreg(vcpu->arch.eff_db[0], 0);
11298 		set_debugreg(vcpu->arch.eff_db[1], 1);
11299 		set_debugreg(vcpu->arch.eff_db[2], 2);
11300 		set_debugreg(vcpu->arch.eff_db[3], 3);
11301 		/* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
11302 		if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
11303 			run_flags |= KVM_RUN_LOAD_GUEST_DR6;
11304 	} else if (unlikely(hw_breakpoint_active())) {
11305 		set_debugreg(DR7_FIXED_1, 7);
11306 	}
11307 
11308 	/*
11309 	 * Refresh the host DEBUGCTL snapshot after disabling IRQs, as DEBUGCTL
11310 	 * can be modified in IRQ context, e.g. via SMP function calls.  Inform
11311 	 * vendor code if any host-owned bits were changed, e.g. so that the
11312 	 * value loaded into hardware while running the guest can be updated.
11313 	 */
11314 	debug_ctl = get_debugctlmsr();
11315 	if ((debug_ctl ^ vcpu->arch.host_debugctl) & kvm_x86_ops.HOST_OWNED_DEBUGCTL &&
11316 	    !vcpu->arch.guest_state_protected)
11317 		run_flags |= KVM_RUN_LOAD_DEBUGCTL;
11318 	vcpu->arch.host_debugctl = debug_ctl;
11319 
11320 	guest_timing_enter_irqoff();
11321 
11322 	for (;;) {
11323 		/*
11324 		 * Assert that vCPU vs. VM APICv state is consistent.  An APICv
11325 		 * update must kick and wait for all vCPUs before toggling the
11326 		 * per-VM state, and responding vCPUs must wait for the update
11327 		 * to complete before servicing KVM_REQ_APICV_UPDATE.
11328 		 */
11329 		WARN_ON_ONCE((kvm_vcpu_apicv_activated(vcpu) != kvm_vcpu_apicv_active(vcpu)) &&
11330 			     (kvm_get_apic_mode(vcpu) != LAPIC_MODE_DISABLED));
11331 
11332 		exit_fastpath = kvm_x86_call(vcpu_run)(vcpu, run_flags);
11333 		if (likely(exit_fastpath != EXIT_FASTPATH_REENTER_GUEST))
11334 			break;
11335 
11336 		if (kvm_lapic_enabled(vcpu))
11337 			kvm_x86_call(sync_pir_to_irr)(vcpu);
11338 
11339 		if (unlikely(kvm_vcpu_exit_request(vcpu))) {
11340 			exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
11341 			break;
11342 		}
11343 
11344 		run_flags = 0;
11345 
11346 		/* Note, VM-Exits that go down the "slow" path are accounted below. */
11347 		++vcpu->stat.exits;
11348 	}
11349 
11350 	/*
11351 	 * Do this here before restoring debug registers on the host.  And
11352 	 * since we do this before handling the vmexit, a DR access vmexit
11353 	 * can (a) read the correct value of the debug registers, (b) set
11354 	 * KVM_DEBUGREG_WONT_EXIT again.
11355 	 */
11356 	if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
11357 		WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
11358 		WARN_ON(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH);
11359 		kvm_x86_call(sync_dirty_debug_regs)(vcpu);
11360 		kvm_update_dr0123(vcpu);
11361 		kvm_update_dr7(vcpu);
11362 	}
11363 
11364 	/*
11365 	 * If the guest has used debug registers, at least dr7
11366 	 * will be disabled while returning to the host.
11367 	 * If we don't have active breakpoints in the host, we don't
11368 	 * care about the messed up debug address registers. But if
11369 	 * we have some of them active, restore the old state.
11370 	 */
11371 	if (hw_breakpoint_active())
11372 		hw_breakpoint_restore();
11373 
11374 	vcpu->arch.last_vmentry_cpu = vcpu->cpu;
11375 	vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
11376 
11377 	vcpu->mode = OUTSIDE_GUEST_MODE;
11378 	smp_wmb();
11379 
11380 	/*
11381 	 * Sync xfd before calling handle_exit_irqoff() which may
11382 	 * rely on the fact that guest_fpu::xfd is up-to-date (e.g.
11383 	 * in #NM irqoff handler).
11384 	 */
11385 	if (vcpu->arch.xfd_no_write_intercept)
11386 		fpu_sync_guest_vmexit_xfd_state();
11387 
11388 	kvm_x86_call(handle_exit_irqoff)(vcpu);
11389 
11390 	if (vcpu->arch.guest_fpu.xfd_err)
11391 		wrmsrq(MSR_IA32_XFD_ERR, 0);
11392 
11393 	/*
11394 	 * Mark this CPU as needing a branch predictor flush before running
11395 	 * userspace. Must be done before enabling preemption to ensure it gets
11396 	 * set for the CPU that actually ran the guest, and not the CPU that it
11397 	 * may migrate to.
11398 	 */
11399 	if (cpu_feature_enabled(X86_FEATURE_IBPB_EXIT_TO_USER))
11400 		this_cpu_write(x86_ibpb_exit_to_user, true);
11401 
11402 	/*
11403 	 * Consume any pending interrupts, including the possible source of
11404 	 * VM-Exit on SVM and any ticks that occur between VM-Exit and now.
11405 	 * An instruction is required after local_irq_enable() to fully unblock
11406 	 * interrupts on processors that implement an interrupt shadow, the
11407 	 * stat.exits increment will do nicely.
11408 	 */
11409 	kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ);
11410 	local_irq_enable();
11411 	++vcpu->stat.exits;
11412 	local_irq_disable();
11413 	kvm_after_interrupt(vcpu);
11414 
11415 	/*
11416 	 * Wait until after servicing IRQs to account guest time so that any
11417 	 * ticks that occurred while running the guest are properly accounted
11418 	 * to the guest.  Waiting until IRQs are enabled degrades the accuracy
11419 	 * of accounting via context tracking, but the loss of accuracy is
11420 	 * acceptable for all known use cases.
11421 	 */
11422 	guest_timing_exit_irqoff();
11423 
11424 	local_irq_enable();
11425 	preempt_enable();
11426 
11427 	kvm_vcpu_srcu_read_lock(vcpu);
11428 
11429 	/*
11430 	 * Call this to ensure WC buffers in guest are evicted after each VM
11431 	 * Exit, so that the evicted WC writes can be snooped across all cpus
11432 	 */
11433 	smp_mb__after_srcu_read_lock();
11434 
11435 	/*
11436 	 * Profile KVM exit RIPs:
11437 	 */
11438 	if (unlikely(prof_on == KVM_PROFILING &&
11439 		     !vcpu->arch.guest_state_protected)) {
11440 		unsigned long rip = kvm_rip_read(vcpu);
11441 		profile_hit(KVM_PROFILING, (void *)rip);
11442 	}
11443 
11444 	if (unlikely(vcpu->arch.tsc_always_catchup))
11445 		kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
11446 
11447 	if (vcpu->arch.apic_attention)
11448 		kvm_lapic_sync_from_vapic(vcpu);
11449 
11450 	if (unlikely(exit_fastpath == EXIT_FASTPATH_EXIT_USERSPACE))
11451 		return 0;
11452 
11453 	r = kvm_x86_call(handle_exit)(vcpu, exit_fastpath);
11454 	return r;
11455 
11456 cancel_injection:
11457 	if (req_immediate_exit)
11458 		kvm_make_request(KVM_REQ_EVENT, vcpu);
11459 	kvm_x86_call(cancel_injection)(vcpu);
11460 	if (unlikely(vcpu->arch.apic_attention))
11461 		kvm_lapic_sync_from_vapic(vcpu);
11462 out:
11463 	return r;
11464 }
11465 
kvm_vcpu_running(struct kvm_vcpu * vcpu)11466 static bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
11467 {
11468 	return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
11469 		!vcpu->arch.apf.halted);
11470 }
11471 
kvm_vcpu_has_events(struct kvm_vcpu * vcpu)11472 bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
11473 {
11474 	if (!list_empty_careful(&vcpu->async_pf.done))
11475 		return true;
11476 
11477 	if (kvm_apic_has_pending_init_or_sipi(vcpu) &&
11478 	    kvm_apic_init_sipi_allowed(vcpu))
11479 		return true;
11480 
11481 	if (kvm_is_exception_pending(vcpu))
11482 		return true;
11483 
11484 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11485 	    (vcpu->arch.nmi_pending &&
11486 	     kvm_x86_call(nmi_allowed)(vcpu, false)))
11487 		return true;
11488 
11489 #ifdef CONFIG_KVM_SMM
11490 	if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
11491 	    (vcpu->arch.smi_pending &&
11492 	     kvm_x86_call(smi_allowed)(vcpu, false)))
11493 		return true;
11494 #endif
11495 
11496 	if (kvm_test_request(KVM_REQ_PMI, vcpu))
11497 		return true;
11498 
11499 	if (kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
11500 		return true;
11501 
11502 	if (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_has_interrupt(vcpu))
11503 		return true;
11504 
11505 	if (kvm_hv_has_stimer_pending(vcpu))
11506 		return true;
11507 
11508 	if (is_guest_mode(vcpu) &&
11509 	    kvm_x86_ops.nested_ops->has_events &&
11510 	    kvm_x86_ops.nested_ops->has_events(vcpu, false))
11511 		return true;
11512 
11513 	if (kvm_xen_has_pending_events(vcpu))
11514 		return true;
11515 
11516 	return false;
11517 }
11518 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_has_events);
11519 
kvm_arch_vcpu_runnable(struct kvm_vcpu * vcpu)11520 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
11521 {
11522 	return kvm_vcpu_running(vcpu) || vcpu->arch.pv.pv_unhalted ||
11523 	       kvm_vcpu_has_events(vcpu);
11524 }
11525 
11526 /* Called within kvm->srcu read side.  */
vcpu_block(struct kvm_vcpu * vcpu)11527 static inline int vcpu_block(struct kvm_vcpu *vcpu)
11528 {
11529 	bool hv_timer;
11530 
11531 	if (!kvm_arch_vcpu_runnable(vcpu)) {
11532 		/*
11533 		 * Switch to the software timer before halt-polling/blocking as
11534 		 * the guest's timer may be a break event for the vCPU, and the
11535 		 * hypervisor timer runs only when the CPU is in guest mode.
11536 		 * Switch before halt-polling so that KVM recognizes an expired
11537 		 * timer before blocking.
11538 		 */
11539 		hv_timer = kvm_lapic_hv_timer_in_use(vcpu);
11540 		if (hv_timer)
11541 			kvm_lapic_switch_to_sw_timer(vcpu);
11542 
11543 		kvm_vcpu_srcu_read_unlock(vcpu);
11544 		if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11545 			kvm_vcpu_halt(vcpu);
11546 		else
11547 			kvm_vcpu_block(vcpu);
11548 		kvm_vcpu_srcu_read_lock(vcpu);
11549 
11550 		if (hv_timer)
11551 			kvm_lapic_switch_to_hv_timer(vcpu);
11552 
11553 		/*
11554 		 * If the vCPU is not runnable, a signal or another host event
11555 		 * of some kind is pending; service it without changing the
11556 		 * vCPU's activity state.
11557 		 */
11558 		if (!kvm_arch_vcpu_runnable(vcpu))
11559 			return 1;
11560 	}
11561 
11562 	/*
11563 	 * Evaluate nested events before exiting the halted state.  This allows
11564 	 * the halt state to be recorded properly in the VMCS12's activity
11565 	 * state field (AMD does not have a similar field and a VM-Exit always
11566 	 * causes a spurious wakeup from HLT).
11567 	 */
11568 	if (is_guest_mode(vcpu)) {
11569 		int r = kvm_check_nested_events(vcpu);
11570 
11571 		WARN_ON_ONCE(r == -EBUSY);
11572 		if (r < 0)
11573 			return 0;
11574 	}
11575 
11576 	if (kvm_apic_accept_events(vcpu) < 0)
11577 		return 0;
11578 	switch(vcpu->arch.mp_state) {
11579 	case KVM_MP_STATE_HALTED:
11580 	case KVM_MP_STATE_AP_RESET_HOLD:
11581 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
11582 		fallthrough;
11583 	case KVM_MP_STATE_RUNNABLE:
11584 		vcpu->arch.apf.halted = false;
11585 		break;
11586 	case KVM_MP_STATE_INIT_RECEIVED:
11587 		break;
11588 	default:
11589 		WARN_ON_ONCE(1);
11590 		break;
11591 	}
11592 	return 1;
11593 }
11594 
11595 /* Called within kvm->srcu read side.  */
vcpu_run(struct kvm_vcpu * vcpu)11596 static int vcpu_run(struct kvm_vcpu *vcpu)
11597 {
11598 	int r;
11599 
11600 	vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
11601 
11602 	for (;;) {
11603 		/*
11604 		 * If another guest vCPU requests a PV TLB flush in the middle
11605 		 * of instruction emulation, the rest of the emulation could
11606 		 * use a stale page translation. Assume that any code after
11607 		 * this point can start executing an instruction.
11608 		 */
11609 		vcpu->arch.at_instruction_boundary = false;
11610 		if (kvm_vcpu_running(vcpu)) {
11611 			r = vcpu_enter_guest(vcpu);
11612 		} else {
11613 			r = vcpu_block(vcpu);
11614 		}
11615 
11616 		if (r <= 0)
11617 			break;
11618 
11619 		kvm_clear_request(KVM_REQ_UNBLOCK, vcpu);
11620 		if (kvm_xen_has_pending_events(vcpu))
11621 			kvm_xen_inject_pending_events(vcpu);
11622 
11623 		if (kvm_cpu_has_pending_timer(vcpu))
11624 			kvm_inject_pending_timer_irqs(vcpu);
11625 
11626 		if (dm_request_for_irq_injection(vcpu) &&
11627 			kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
11628 			r = 0;
11629 			vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
11630 			++vcpu->stat.request_irq_exits;
11631 			break;
11632 		}
11633 
11634 		if (__xfer_to_guest_mode_work_pending()) {
11635 			kvm_vcpu_srcu_read_unlock(vcpu);
11636 			r = kvm_xfer_to_guest_mode_handle_work(vcpu);
11637 			kvm_vcpu_srcu_read_lock(vcpu);
11638 			if (r)
11639 				return r;
11640 		}
11641 	}
11642 
11643 	return r;
11644 }
11645 
__kvm_emulate_halt(struct kvm_vcpu * vcpu,int state,int reason)11646 static int __kvm_emulate_halt(struct kvm_vcpu *vcpu, int state, int reason)
11647 {
11648 	/*
11649 	 * The vCPU has halted, e.g. executed HLT.  Update the run state if the
11650 	 * local APIC is in-kernel, the run loop will detect the non-runnable
11651 	 * state and halt the vCPU.  Exit to userspace if the local APIC is
11652 	 * managed by userspace, in which case userspace is responsible for
11653 	 * handling wake events.
11654 	 */
11655 	++vcpu->stat.halt_exits;
11656 	if (lapic_in_kernel(vcpu)) {
11657 		if (kvm_vcpu_has_events(vcpu) || vcpu->arch.pv.pv_unhalted)
11658 			state = KVM_MP_STATE_RUNNABLE;
11659 		kvm_set_mp_state(vcpu, state);
11660 		return 1;
11661 	} else {
11662 		vcpu->run->exit_reason = reason;
11663 		return 0;
11664 	}
11665 }
11666 
kvm_emulate_halt_noskip(struct kvm_vcpu * vcpu)11667 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu)
11668 {
11669 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_HALTED, KVM_EXIT_HLT);
11670 }
11671 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt_noskip);
11672 
kvm_emulate_halt(struct kvm_vcpu * vcpu)11673 int kvm_emulate_halt(struct kvm_vcpu *vcpu)
11674 {
11675 	int ret = kvm_skip_emulated_instruction(vcpu);
11676 	/*
11677 	 * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
11678 	 * KVM_EXIT_DEBUG here.
11679 	 */
11680 	return kvm_emulate_halt_noskip(vcpu) && ret;
11681 }
11682 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt);
11683 
handle_fastpath_hlt(struct kvm_vcpu * vcpu)11684 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
11685 {
11686 	if (!kvm_emulate_halt(vcpu))
11687 		return EXIT_FASTPATH_EXIT_USERSPACE;
11688 
11689 	if (kvm_vcpu_running(vcpu))
11690 		return EXIT_FASTPATH_REENTER_GUEST;
11691 
11692 	return EXIT_FASTPATH_EXIT_HANDLED;
11693 }
11694 EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_hlt);
11695 
kvm_emulate_ap_reset_hold(struct kvm_vcpu * vcpu)11696 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu)
11697 {
11698 	int ret = kvm_skip_emulated_instruction(vcpu);
11699 
11700 	return __kvm_emulate_halt(vcpu, KVM_MP_STATE_AP_RESET_HOLD,
11701 					KVM_EXIT_AP_RESET_HOLD) && ret;
11702 }
11703 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_ap_reset_hold);
11704 
kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu * vcpu)11705 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
11706 {
11707 	return kvm_vcpu_apicv_active(vcpu) &&
11708 	       kvm_x86_call(dy_apicv_has_pending_interrupt)(vcpu);
11709 }
11710 
kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu * vcpu)11711 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu)
11712 {
11713 	return vcpu->arch.preempted_in_kernel;
11714 }
11715 
kvm_arch_dy_runnable(struct kvm_vcpu * vcpu)11716 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
11717 {
11718 	if (READ_ONCE(vcpu->arch.pv.pv_unhalted))
11719 		return true;
11720 
11721 	if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
11722 #ifdef CONFIG_KVM_SMM
11723 		kvm_test_request(KVM_REQ_SMI, vcpu) ||
11724 #endif
11725 		 kvm_test_request(KVM_REQ_EVENT, vcpu))
11726 		return true;
11727 
11728 	return kvm_arch_dy_has_pending_interrupt(vcpu);
11729 }
11730 
complete_emulated_io(struct kvm_vcpu * vcpu)11731 static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
11732 {
11733 	return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
11734 }
11735 
complete_emulated_pio(struct kvm_vcpu * vcpu)11736 static int complete_emulated_pio(struct kvm_vcpu *vcpu)
11737 {
11738 	BUG_ON(!vcpu->arch.pio.count);
11739 
11740 	return complete_emulated_io(vcpu);
11741 }
11742 
11743 /*
11744  * Implements the following, as a state machine:
11745  *
11746  * read:
11747  *   for each fragment
11748  *     for each mmio piece in the fragment
11749  *       write gpa, len
11750  *       exit
11751  *       copy data
11752  *   execute insn
11753  *
11754  * write:
11755  *   for each fragment
11756  *     for each mmio piece in the fragment
11757  *       write gpa, len
11758  *       copy data
11759  *       exit
11760  */
complete_emulated_mmio(struct kvm_vcpu * vcpu)11761 static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
11762 {
11763 	struct kvm_run *run = vcpu->run;
11764 	struct kvm_mmio_fragment *frag;
11765 	unsigned len;
11766 
11767 	BUG_ON(!vcpu->mmio_needed);
11768 
11769 	/* Complete previous fragment */
11770 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
11771 	len = min(8u, frag->len);
11772 	if (!vcpu->mmio_is_write)
11773 		memcpy(frag->data, run->mmio.data, len);
11774 
11775 	if (frag->len <= 8) {
11776 		/* Switch to the next fragment. */
11777 		frag++;
11778 		vcpu->mmio_cur_fragment++;
11779 	} else {
11780 		/* Go forward to the next mmio piece. */
11781 		frag->data += len;
11782 		frag->gpa += len;
11783 		frag->len -= len;
11784 	}
11785 
11786 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
11787 		vcpu->mmio_needed = 0;
11788 
11789 		/* FIXME: return into emulator if single-stepping.  */
11790 		if (vcpu->mmio_is_write)
11791 			return 1;
11792 		vcpu->mmio_read_completed = 1;
11793 		return complete_emulated_io(vcpu);
11794 	}
11795 
11796 	run->exit_reason = KVM_EXIT_MMIO;
11797 	run->mmio.phys_addr = frag->gpa;
11798 	if (vcpu->mmio_is_write)
11799 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
11800 	run->mmio.len = min(8u, frag->len);
11801 	run->mmio.is_write = vcpu->mmio_is_write;
11802 	vcpu->arch.complete_userspace_io = complete_emulated_mmio;
11803 	return 0;
11804 }
11805 
11806 /* Swap (qemu) user FPU context for the guest FPU context. */
kvm_load_guest_fpu(struct kvm_vcpu * vcpu)11807 static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
11808 {
11809 	if (KVM_BUG_ON(vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
11810 		return;
11811 
11812 	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
11813 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
11814 	trace_kvm_fpu(1);
11815 }
11816 
11817 /* When vcpu_run ends, restore user space FPU context. */
kvm_put_guest_fpu(struct kvm_vcpu * vcpu)11818 static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
11819 {
11820 	if (KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
11821 		return;
11822 
11823 	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
11824 	++vcpu->stat.fpu_reload;
11825 	trace_kvm_fpu(0);
11826 }
11827 
kvm_x86_vcpu_pre_run(struct kvm_vcpu * vcpu)11828 static int kvm_x86_vcpu_pre_run(struct kvm_vcpu *vcpu)
11829 {
11830 	/*
11831 	 * SIPI_RECEIVED is obsolete; KVM leaves the vCPU in Wait-For-SIPI and
11832 	 * tracks the pending SIPI separately.  SIPI_RECEIVED is still accepted
11833 	 * by KVM_SET_VCPU_EVENTS for backwards compatibility, but should be
11834 	 * converted to INIT_RECEIVED.
11835 	 */
11836 	if (WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED))
11837 		return -EINVAL;
11838 
11839 	/*
11840 	 * Disallow running the vCPU if userspace forced it into an impossible
11841 	 * MP_STATE, e.g. if the vCPU is in WFS but SIPI is blocked.
11842 	 */
11843 	if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED &&
11844 	    !kvm_apic_init_sipi_allowed(vcpu))
11845 		return -EINVAL;
11846 
11847 	return kvm_x86_call(vcpu_pre_run)(vcpu);
11848 }
11849 
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)11850 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
11851 {
11852 	struct kvm_queued_exception *ex = &vcpu->arch.exception;
11853 	struct kvm_run *kvm_run = vcpu->run;
11854 	u64 sync_valid_fields;
11855 	int r;
11856 
11857 	r = kvm_mmu_post_init_vm(vcpu->kvm);
11858 	if (r)
11859 		return r;
11860 
11861 	vcpu_load(vcpu);
11862 	kvm_sigset_activate(vcpu);
11863 	kvm_run->flags = 0;
11864 	kvm_load_guest_fpu(vcpu);
11865 
11866 	kvm_vcpu_srcu_read_lock(vcpu);
11867 	if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
11868 		if (!vcpu->wants_to_run) {
11869 			r = -EINTR;
11870 			goto out;
11871 		}
11872 
11873 		/*
11874 		 * Don't bother switching APIC timer emulation from the
11875 		 * hypervisor timer to the software timer, the only way for the
11876 		 * APIC timer to be active is if userspace stuffed vCPU state,
11877 		 * i.e. put the vCPU into a nonsensical state.  Only an INIT
11878 		 * will transition the vCPU out of UNINITIALIZED (without more
11879 		 * state stuffing from userspace), which will reset the local
11880 		 * APIC and thus cancel the timer or drop the IRQ (if the timer
11881 		 * already expired).
11882 		 */
11883 		kvm_vcpu_srcu_read_unlock(vcpu);
11884 		kvm_vcpu_block(vcpu);
11885 		kvm_vcpu_srcu_read_lock(vcpu);
11886 
11887 		if (kvm_apic_accept_events(vcpu) < 0) {
11888 			r = 0;
11889 			goto out;
11890 		}
11891 		r = -EAGAIN;
11892 		if (signal_pending(current)) {
11893 			r = -EINTR;
11894 			kvm_run->exit_reason = KVM_EXIT_INTR;
11895 			++vcpu->stat.signal_exits;
11896 		}
11897 		goto out;
11898 	}
11899 
11900 	sync_valid_fields = kvm_sync_valid_fields(vcpu->kvm);
11901 	if ((kvm_run->kvm_valid_regs & ~sync_valid_fields) ||
11902 	    (kvm_run->kvm_dirty_regs & ~sync_valid_fields)) {
11903 		r = -EINVAL;
11904 		goto out;
11905 	}
11906 
11907 	if (kvm_run->kvm_dirty_regs) {
11908 		r = sync_regs(vcpu);
11909 		if (r != 0)
11910 			goto out;
11911 	}
11912 
11913 	/* re-sync apic's tpr */
11914 	if (!lapic_in_kernel(vcpu)) {
11915 		if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
11916 			r = -EINVAL;
11917 			goto out;
11918 		}
11919 	}
11920 
11921 	/*
11922 	 * If userspace set a pending exception and L2 is active, convert it to
11923 	 * a pending VM-Exit if L1 wants to intercept the exception.
11924 	 */
11925 	if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) &&
11926 	    kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector,
11927 							ex->error_code)) {
11928 		kvm_queue_exception_vmexit(vcpu, ex->vector,
11929 					   ex->has_error_code, ex->error_code,
11930 					   ex->has_payload, ex->payload);
11931 		ex->injected = false;
11932 		ex->pending = false;
11933 	}
11934 	vcpu->arch.exception_from_userspace = false;
11935 
11936 	if (unlikely(vcpu->arch.complete_userspace_io)) {
11937 		int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
11938 		vcpu->arch.complete_userspace_io = NULL;
11939 		r = cui(vcpu);
11940 		if (r <= 0)
11941 			goto out;
11942 	} else {
11943 		WARN_ON_ONCE(vcpu->arch.pio.count);
11944 		WARN_ON_ONCE(vcpu->mmio_needed);
11945 	}
11946 
11947 	if (!vcpu->wants_to_run) {
11948 		r = -EINTR;
11949 		goto out;
11950 	}
11951 
11952 	r = kvm_x86_vcpu_pre_run(vcpu);
11953 	if (r <= 0)
11954 		goto out;
11955 
11956 	r = vcpu_run(vcpu);
11957 
11958 out:
11959 	kvm_put_guest_fpu(vcpu);
11960 	if (kvm_run->kvm_valid_regs && likely(!vcpu->arch.guest_state_protected))
11961 		store_regs(vcpu);
11962 	post_kvm_run_save(vcpu);
11963 	kvm_vcpu_srcu_read_unlock(vcpu);
11964 
11965 	kvm_sigset_deactivate(vcpu);
11966 	vcpu_put(vcpu);
11967 	return r;
11968 }
11969 
__get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)11970 static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
11971 {
11972 	if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
11973 		/*
11974 		 * We are here if userspace calls get_regs() in the middle of
11975 		 * instruction emulation. Registers state needs to be copied
11976 		 * back from emulation context to vcpu. Userspace shouldn't do
11977 		 * that usually, but some bad designed PV devices (vmware
11978 		 * backdoor interface) need this to work
11979 		 */
11980 		emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
11981 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
11982 	}
11983 	regs->rax = kvm_rax_read(vcpu);
11984 	regs->rbx = kvm_rbx_read(vcpu);
11985 	regs->rcx = kvm_rcx_read(vcpu);
11986 	regs->rdx = kvm_rdx_read(vcpu);
11987 	regs->rsi = kvm_rsi_read(vcpu);
11988 	regs->rdi = kvm_rdi_read(vcpu);
11989 	regs->rsp = kvm_rsp_read(vcpu);
11990 	regs->rbp = kvm_rbp_read(vcpu);
11991 #ifdef CONFIG_X86_64
11992 	regs->r8 = kvm_r8_read(vcpu);
11993 	regs->r9 = kvm_r9_read(vcpu);
11994 	regs->r10 = kvm_r10_read(vcpu);
11995 	regs->r11 = kvm_r11_read(vcpu);
11996 	regs->r12 = kvm_r12_read(vcpu);
11997 	regs->r13 = kvm_r13_read(vcpu);
11998 	regs->r14 = kvm_r14_read(vcpu);
11999 	regs->r15 = kvm_r15_read(vcpu);
12000 #endif
12001 
12002 	regs->rip = kvm_rip_read(vcpu);
12003 	regs->rflags = kvm_get_rflags(vcpu);
12004 }
12005 
kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12006 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12007 {
12008 	if (vcpu->kvm->arch.has_protected_state &&
12009 	    vcpu->arch.guest_state_protected)
12010 		return -EINVAL;
12011 
12012 	vcpu_load(vcpu);
12013 	__get_regs(vcpu, regs);
12014 	vcpu_put(vcpu);
12015 	return 0;
12016 }
12017 
__set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12018 static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12019 {
12020 	vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
12021 	vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
12022 
12023 	kvm_rax_write(vcpu, regs->rax);
12024 	kvm_rbx_write(vcpu, regs->rbx);
12025 	kvm_rcx_write(vcpu, regs->rcx);
12026 	kvm_rdx_write(vcpu, regs->rdx);
12027 	kvm_rsi_write(vcpu, regs->rsi);
12028 	kvm_rdi_write(vcpu, regs->rdi);
12029 	kvm_rsp_write(vcpu, regs->rsp);
12030 	kvm_rbp_write(vcpu, regs->rbp);
12031 #ifdef CONFIG_X86_64
12032 	kvm_r8_write(vcpu, regs->r8);
12033 	kvm_r9_write(vcpu, regs->r9);
12034 	kvm_r10_write(vcpu, regs->r10);
12035 	kvm_r11_write(vcpu, regs->r11);
12036 	kvm_r12_write(vcpu, regs->r12);
12037 	kvm_r13_write(vcpu, regs->r13);
12038 	kvm_r14_write(vcpu, regs->r14);
12039 	kvm_r15_write(vcpu, regs->r15);
12040 #endif
12041 
12042 	kvm_rip_write(vcpu, regs->rip);
12043 	kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
12044 
12045 	vcpu->arch.exception.pending = false;
12046 	vcpu->arch.exception_vmexit.pending = false;
12047 
12048 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12049 }
12050 
kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu * vcpu,struct kvm_regs * regs)12051 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
12052 {
12053 	if (vcpu->kvm->arch.has_protected_state &&
12054 	    vcpu->arch.guest_state_protected)
12055 		return -EINVAL;
12056 
12057 	vcpu_load(vcpu);
12058 	__set_regs(vcpu, regs);
12059 	vcpu_put(vcpu);
12060 	return 0;
12061 }
12062 
__get_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12063 static void __get_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12064 {
12065 	struct desc_ptr dt;
12066 
12067 	if (vcpu->arch.guest_state_protected)
12068 		goto skip_protected_regs;
12069 
12070 	kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12071 	kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12072 	kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12073 	kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12074 	kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12075 	kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12076 
12077 	kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12078 	kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12079 
12080 	kvm_x86_call(get_idt)(vcpu, &dt);
12081 	sregs->idt.limit = dt.size;
12082 	sregs->idt.base = dt.address;
12083 	kvm_x86_call(get_gdt)(vcpu, &dt);
12084 	sregs->gdt.limit = dt.size;
12085 	sregs->gdt.base = dt.address;
12086 
12087 	sregs->cr2 = vcpu->arch.cr2;
12088 	sregs->cr3 = kvm_read_cr3(vcpu);
12089 
12090 skip_protected_regs:
12091 	sregs->cr0 = kvm_read_cr0(vcpu);
12092 	sregs->cr4 = kvm_read_cr4(vcpu);
12093 	sregs->cr8 = kvm_get_cr8(vcpu);
12094 	sregs->efer = vcpu->arch.efer;
12095 	sregs->apic_base = vcpu->arch.apic_base;
12096 }
12097 
__get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12098 static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12099 {
12100 	__get_sregs_common(vcpu, sregs);
12101 
12102 	if (vcpu->arch.guest_state_protected)
12103 		return;
12104 
12105 	if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
12106 		set_bit(vcpu->arch.interrupt.nr,
12107 			(unsigned long *)sregs->interrupt_bitmap);
12108 }
12109 
__get_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12110 static void __get_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12111 {
12112 	int i;
12113 
12114 	__get_sregs_common(vcpu, (struct kvm_sregs *)sregs2);
12115 
12116 	if (vcpu->arch.guest_state_protected)
12117 		return;
12118 
12119 	if (is_pae_paging(vcpu)) {
12120 		for (i = 0 ; i < 4 ; i++)
12121 			sregs2->pdptrs[i] = kvm_pdptr_read(vcpu, i);
12122 		sregs2->flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
12123 	}
12124 }
12125 
kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12126 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
12127 				  struct kvm_sregs *sregs)
12128 {
12129 	if (vcpu->kvm->arch.has_protected_state &&
12130 	    vcpu->arch.guest_state_protected)
12131 		return -EINVAL;
12132 
12133 	vcpu_load(vcpu);
12134 	__get_sregs(vcpu, sregs);
12135 	vcpu_put(vcpu);
12136 	return 0;
12137 }
12138 
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)12139 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
12140 				    struct kvm_mp_state *mp_state)
12141 {
12142 	int r;
12143 
12144 	vcpu_load(vcpu);
12145 	kvm_vcpu_srcu_read_lock(vcpu);
12146 
12147 	r = kvm_apic_accept_events(vcpu);
12148 	if (r < 0)
12149 		goto out;
12150 	r = 0;
12151 
12152 	if ((vcpu->arch.mp_state == KVM_MP_STATE_HALTED ||
12153 	     vcpu->arch.mp_state == KVM_MP_STATE_AP_RESET_HOLD) &&
12154 	    vcpu->arch.pv.pv_unhalted)
12155 		mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
12156 	else
12157 		mp_state->mp_state = vcpu->arch.mp_state;
12158 
12159 out:
12160 	kvm_vcpu_srcu_read_unlock(vcpu);
12161 	vcpu_put(vcpu);
12162 	return r;
12163 }
12164 
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)12165 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
12166 				    struct kvm_mp_state *mp_state)
12167 {
12168 	int ret = -EINVAL;
12169 
12170 	vcpu_load(vcpu);
12171 
12172 	switch (mp_state->mp_state) {
12173 	case KVM_MP_STATE_UNINITIALIZED:
12174 	case KVM_MP_STATE_HALTED:
12175 	case KVM_MP_STATE_AP_RESET_HOLD:
12176 	case KVM_MP_STATE_INIT_RECEIVED:
12177 	case KVM_MP_STATE_SIPI_RECEIVED:
12178 		if (!lapic_in_kernel(vcpu))
12179 			goto out;
12180 		break;
12181 
12182 	case KVM_MP_STATE_RUNNABLE:
12183 		break;
12184 
12185 	default:
12186 		goto out;
12187 	}
12188 
12189 	/*
12190 	 * SIPI_RECEIVED is obsolete and no longer used internally; KVM instead
12191 	 * leaves the vCPU in INIT_RECIEVED (Wait-For-SIPI) and pends the SIPI.
12192 	 * Translate SIPI_RECEIVED as appropriate for backwards compatibility.
12193 	 */
12194 	if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
12195 		mp_state->mp_state = KVM_MP_STATE_INIT_RECEIVED;
12196 		set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
12197 	}
12198 
12199 	kvm_set_mp_state(vcpu, mp_state->mp_state);
12200 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12201 
12202 	ret = 0;
12203 out:
12204 	vcpu_put(vcpu);
12205 	return ret;
12206 }
12207 
kvm_task_switch(struct kvm_vcpu * vcpu,u16 tss_selector,int idt_index,int reason,bool has_error_code,u32 error_code)12208 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
12209 		    int reason, bool has_error_code, u32 error_code)
12210 {
12211 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
12212 	int ret;
12213 
12214 	if (kvm_is_cr4_bit_set(vcpu, X86_CR4_CET)) {
12215 		u64 u_cet, s_cet;
12216 
12217 		/*
12218 		 * Check both User and Supervisor on task switches as inter-
12219 		 * privilege level task switches are impacted by CET at both
12220 		 * the current privilege level and the new privilege level, and
12221 		 * that information is not known at this time.  The expectation
12222 		 * is that the guest won't require emulation of task switches
12223 		 * while using IBT or Shadow Stacks.
12224 		 */
12225 		if (__kvm_emulate_msr_read(vcpu, MSR_IA32_U_CET, &u_cet) ||
12226 		    __kvm_emulate_msr_read(vcpu, MSR_IA32_S_CET, &s_cet))
12227 			goto unhandled_task_switch;
12228 
12229 		if ((u_cet | s_cet) & (CET_ENDBR_EN | CET_SHSTK_EN))
12230 			goto unhandled_task_switch;
12231 	}
12232 
12233 	init_emulate_ctxt(vcpu);
12234 
12235 	ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
12236 				   has_error_code, error_code);
12237 
12238 	/*
12239 	 * Report an error userspace if MMIO is needed, as KVM doesn't support
12240 	 * MMIO during a task switch (or any other complex operation).
12241 	 */
12242 	if (ret || vcpu->mmio_needed)
12243 		goto unhandled_task_switch;
12244 
12245 	kvm_rip_write(vcpu, ctxt->eip);
12246 	kvm_set_rflags(vcpu, ctxt->eflags);
12247 	return 1;
12248 
12249 unhandled_task_switch:
12250 	vcpu->mmio_needed = false;
12251 	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
12252 	vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
12253 	vcpu->run->internal.ndata = 0;
12254 	return 0;
12255 }
12256 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_task_switch);
12257 
kvm_is_valid_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12258 static bool kvm_is_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12259 {
12260 	if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
12261 		/*
12262 		 * When EFER.LME and CR0.PG are set, the processor is in
12263 		 * 64-bit mode (though maybe in a 32-bit code segment).
12264 		 * CR4.PAE and EFER.LMA must be set.
12265 		 */
12266 		if (!(sregs->cr4 & X86_CR4_PAE) || !(sregs->efer & EFER_LMA))
12267 			return false;
12268 		if (!kvm_vcpu_is_legal_cr3(vcpu, sregs->cr3))
12269 			return false;
12270 	} else {
12271 		/*
12272 		 * Not in 64-bit mode: EFER.LMA is clear and the code
12273 		 * segment cannot be 64-bit.
12274 		 */
12275 		if (sregs->efer & EFER_LMA || sregs->cs.l)
12276 			return false;
12277 	}
12278 
12279 	return kvm_is_valid_cr4(vcpu, sregs->cr4) &&
12280 	       kvm_is_valid_cr0(vcpu, sregs->cr0);
12281 }
12282 
__set_sregs_common(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs,int * mmu_reset_needed,bool update_pdptrs)12283 static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
12284 		int *mmu_reset_needed, bool update_pdptrs)
12285 {
12286 	int idx;
12287 	struct desc_ptr dt;
12288 
12289 	if (!kvm_is_valid_sregs(vcpu, sregs))
12290 		return -EINVAL;
12291 
12292 	if (kvm_apic_set_base(vcpu, sregs->apic_base, true))
12293 		return -EINVAL;
12294 
12295 	if (vcpu->arch.guest_state_protected)
12296 		return 0;
12297 
12298 	dt.size = sregs->idt.limit;
12299 	dt.address = sregs->idt.base;
12300 	kvm_x86_call(set_idt)(vcpu, &dt);
12301 	dt.size = sregs->gdt.limit;
12302 	dt.address = sregs->gdt.base;
12303 	kvm_x86_call(set_gdt)(vcpu, &dt);
12304 
12305 	vcpu->arch.cr2 = sregs->cr2;
12306 	*mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
12307 	vcpu->arch.cr3 = sregs->cr3;
12308 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12309 	kvm_x86_call(post_set_cr3)(vcpu, sregs->cr3);
12310 
12311 	kvm_set_cr8(vcpu, sregs->cr8);
12312 
12313 	*mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
12314 	kvm_x86_call(set_efer)(vcpu, sregs->efer);
12315 
12316 	*mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
12317 	kvm_x86_call(set_cr0)(vcpu, sregs->cr0);
12318 
12319 	*mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
12320 	kvm_x86_call(set_cr4)(vcpu, sregs->cr4);
12321 
12322 	if (update_pdptrs) {
12323 		idx = srcu_read_lock(&vcpu->kvm->srcu);
12324 		if (is_pae_paging(vcpu)) {
12325 			load_pdptrs(vcpu, kvm_read_cr3(vcpu));
12326 			*mmu_reset_needed = 1;
12327 		}
12328 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
12329 	}
12330 
12331 	kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
12332 	kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
12333 	kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
12334 	kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
12335 	kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
12336 	kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
12337 
12338 	kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
12339 	kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
12340 
12341 	update_cr8_intercept(vcpu);
12342 
12343 	/* Older userspace won't unhalt the vcpu on reset. */
12344 	if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
12345 	    sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
12346 	    !is_protmode(vcpu))
12347 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12348 
12349 	return 0;
12350 }
12351 
__set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12352 static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
12353 {
12354 	int pending_vec, max_bits;
12355 	int mmu_reset_needed = 0;
12356 	int ret = __set_sregs_common(vcpu, sregs, &mmu_reset_needed, true);
12357 
12358 	if (ret)
12359 		return ret;
12360 
12361 	if (mmu_reset_needed) {
12362 		kvm_mmu_reset_context(vcpu);
12363 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12364 	}
12365 
12366 	max_bits = KVM_NR_INTERRUPTS;
12367 	pending_vec = find_first_bit(
12368 		(const unsigned long *)sregs->interrupt_bitmap, max_bits);
12369 
12370 	if (pending_vec < max_bits) {
12371 		kvm_queue_interrupt(vcpu, pending_vec, false);
12372 		pr_debug("Set back pending irq %d\n", pending_vec);
12373 		kvm_make_request(KVM_REQ_EVENT, vcpu);
12374 	}
12375 	return 0;
12376 }
12377 
__set_sregs2(struct kvm_vcpu * vcpu,struct kvm_sregs2 * sregs2)12378 static int __set_sregs2(struct kvm_vcpu *vcpu, struct kvm_sregs2 *sregs2)
12379 {
12380 	int mmu_reset_needed = 0;
12381 	bool valid_pdptrs = sregs2->flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
12382 	bool pae = (sregs2->cr0 & X86_CR0_PG) && (sregs2->cr4 & X86_CR4_PAE) &&
12383 		!(sregs2->efer & EFER_LMA);
12384 	int i, ret;
12385 
12386 	if (sregs2->flags & ~KVM_SREGS2_FLAGS_PDPTRS_VALID)
12387 		return -EINVAL;
12388 
12389 	if (valid_pdptrs && (!pae || vcpu->arch.guest_state_protected))
12390 		return -EINVAL;
12391 
12392 	ret = __set_sregs_common(vcpu, (struct kvm_sregs *)sregs2,
12393 				 &mmu_reset_needed, !valid_pdptrs);
12394 	if (ret)
12395 		return ret;
12396 
12397 	if (valid_pdptrs) {
12398 		for (i = 0; i < 4 ; i++)
12399 			kvm_pdptr_write(vcpu, i, sregs2->pdptrs[i]);
12400 
12401 		kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
12402 		mmu_reset_needed = 1;
12403 		vcpu->arch.pdptrs_from_userspace = true;
12404 	}
12405 	if (mmu_reset_needed) {
12406 		kvm_mmu_reset_context(vcpu);
12407 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12408 	}
12409 	return 0;
12410 }
12411 
kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu * vcpu,struct kvm_sregs * sregs)12412 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
12413 				  struct kvm_sregs *sregs)
12414 {
12415 	int ret;
12416 
12417 	if (vcpu->kvm->arch.has_protected_state &&
12418 	    vcpu->arch.guest_state_protected)
12419 		return -EINVAL;
12420 
12421 	vcpu_load(vcpu);
12422 	ret = __set_sregs(vcpu, sregs);
12423 	vcpu_put(vcpu);
12424 	return ret;
12425 }
12426 
kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm * kvm)12427 static void kvm_arch_vcpu_guestdbg_update_apicv_inhibit(struct kvm *kvm)
12428 {
12429 	bool set = false;
12430 	struct kvm_vcpu *vcpu;
12431 	unsigned long i;
12432 
12433 	if (!enable_apicv)
12434 		return;
12435 
12436 	down_write(&kvm->arch.apicv_update_lock);
12437 
12438 	kvm_for_each_vcpu(i, vcpu, kvm) {
12439 		if (vcpu->guest_debug & KVM_GUESTDBG_BLOCKIRQ) {
12440 			set = true;
12441 			break;
12442 		}
12443 	}
12444 	__kvm_set_or_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_BLOCKIRQ, set);
12445 	up_write(&kvm->arch.apicv_update_lock);
12446 }
12447 
kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu * vcpu,struct kvm_guest_debug * dbg)12448 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
12449 					struct kvm_guest_debug *dbg)
12450 {
12451 	unsigned long rflags;
12452 	int i, r;
12453 
12454 	if (vcpu->arch.guest_state_protected)
12455 		return -EINVAL;
12456 
12457 	vcpu_load(vcpu);
12458 
12459 	if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
12460 		r = -EBUSY;
12461 		if (kvm_is_exception_pending(vcpu))
12462 			goto out;
12463 		if (dbg->control & KVM_GUESTDBG_INJECT_DB)
12464 			kvm_queue_exception(vcpu, DB_VECTOR);
12465 		else
12466 			kvm_queue_exception(vcpu, BP_VECTOR);
12467 	}
12468 
12469 	/*
12470 	 * Read rflags as long as potentially injected trace flags are still
12471 	 * filtered out.
12472 	 */
12473 	rflags = kvm_get_rflags(vcpu);
12474 
12475 	vcpu->guest_debug = dbg->control;
12476 	if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
12477 		vcpu->guest_debug = 0;
12478 
12479 	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
12480 		for (i = 0; i < KVM_NR_DB_REGS; ++i)
12481 			vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
12482 		vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
12483 	} else {
12484 		for (i = 0; i < KVM_NR_DB_REGS; i++)
12485 			vcpu->arch.eff_db[i] = vcpu->arch.db[i];
12486 	}
12487 	kvm_update_dr7(vcpu);
12488 
12489 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
12490 		vcpu->arch.singlestep_rip = kvm_get_linear_rip(vcpu);
12491 
12492 	/*
12493 	 * Trigger an rflags update that will inject or remove the trace
12494 	 * flags.
12495 	 */
12496 	kvm_set_rflags(vcpu, rflags);
12497 
12498 	kvm_x86_call(update_exception_bitmap)(vcpu);
12499 
12500 	kvm_arch_vcpu_guestdbg_update_apicv_inhibit(vcpu->kvm);
12501 
12502 	r = 0;
12503 
12504 out:
12505 	vcpu_put(vcpu);
12506 	return r;
12507 }
12508 
12509 /*
12510  * Translate a guest virtual address to a guest physical address.
12511  */
kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu * vcpu,struct kvm_translation * tr)12512 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
12513 				    struct kvm_translation *tr)
12514 {
12515 	unsigned long vaddr = tr->linear_address;
12516 	gpa_t gpa;
12517 	int idx;
12518 
12519 	vcpu_load(vcpu);
12520 
12521 	idx = srcu_read_lock(&vcpu->kvm->srcu);
12522 	gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
12523 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
12524 	tr->physical_address = gpa;
12525 	tr->valid = gpa != INVALID_GPA;
12526 	tr->writeable = 1;
12527 	tr->usermode = 0;
12528 
12529 	vcpu_put(vcpu);
12530 	return 0;
12531 }
12532 
kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12533 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12534 {
12535 	struct fxregs_state *fxsave;
12536 
12537 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12538 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12539 
12540 	vcpu_load(vcpu);
12541 
12542 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12543 	memcpy(fpu->fpr, fxsave->st_space, 128);
12544 	fpu->fcw = fxsave->cwd;
12545 	fpu->fsw = fxsave->swd;
12546 	fpu->ftwx = fxsave->twd;
12547 	fpu->last_opcode = fxsave->fop;
12548 	fpu->last_ip = fxsave->rip;
12549 	fpu->last_dp = fxsave->rdp;
12550 	memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
12551 
12552 	vcpu_put(vcpu);
12553 	return 0;
12554 }
12555 
kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu * vcpu,struct kvm_fpu * fpu)12556 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
12557 {
12558 	struct fxregs_state *fxsave;
12559 
12560 	if (fpstate_is_confidential(&vcpu->arch.guest_fpu))
12561 		return vcpu->kvm->arch.has_protected_state ? -EINVAL : 0;
12562 
12563 	vcpu_load(vcpu);
12564 
12565 	fxsave = &vcpu->arch.guest_fpu.fpstate->regs.fxsave;
12566 
12567 	memcpy(fxsave->st_space, fpu->fpr, 128);
12568 	fxsave->cwd = fpu->fcw;
12569 	fxsave->swd = fpu->fsw;
12570 	fxsave->twd = fpu->ftwx;
12571 	fxsave->fop = fpu->last_opcode;
12572 	fxsave->rip = fpu->last_ip;
12573 	fxsave->rdp = fpu->last_dp;
12574 	memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
12575 
12576 	vcpu_put(vcpu);
12577 	return 0;
12578 }
12579 
store_regs(struct kvm_vcpu * vcpu)12580 static void store_regs(struct kvm_vcpu *vcpu)
12581 {
12582 	BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
12583 
12584 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
12585 		__get_regs(vcpu, &vcpu->run->s.regs.regs);
12586 
12587 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
12588 		__get_sregs(vcpu, &vcpu->run->s.regs.sregs);
12589 
12590 	if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
12591 		kvm_vcpu_ioctl_x86_get_vcpu_events(
12592 				vcpu, &vcpu->run->s.regs.events);
12593 }
12594 
sync_regs(struct kvm_vcpu * vcpu)12595 static int sync_regs(struct kvm_vcpu *vcpu)
12596 {
12597 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
12598 		__set_regs(vcpu, &vcpu->run->s.regs.regs);
12599 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
12600 	}
12601 
12602 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
12603 		struct kvm_sregs sregs = vcpu->run->s.regs.sregs;
12604 
12605 		if (__set_sregs(vcpu, &sregs))
12606 			return -EINVAL;
12607 
12608 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
12609 	}
12610 
12611 	if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
12612 		struct kvm_vcpu_events events = vcpu->run->s.regs.events;
12613 
12614 		if (kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events))
12615 			return -EINVAL;
12616 
12617 		vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
12618 	}
12619 
12620 	return 0;
12621 }
12622 
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)12623 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
12624 {
12625 	if (kvm_check_tsc_unstable() && kvm->created_vcpus)
12626 		pr_warn_once("SMP vm created on host with unstable TSC; "
12627 			     "guest TSC will not be reliable\n");
12628 
12629 	if (!kvm->arch.max_vcpu_ids)
12630 		kvm->arch.max_vcpu_ids = KVM_MAX_VCPU_IDS;
12631 
12632 	if (id >= kvm->arch.max_vcpu_ids)
12633 		return -EINVAL;
12634 
12635 	return kvm_x86_call(vcpu_precreate)(kvm);
12636 }
12637 
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)12638 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
12639 {
12640 	struct page *page;
12641 	int r;
12642 
12643 	vcpu->arch.last_vmentry_cpu = -1;
12644 	vcpu->arch.regs_avail = ~0;
12645 	vcpu->arch.regs_dirty = ~0;
12646 
12647 	kvm_gpc_init(&vcpu->arch.pv_time, vcpu->kvm);
12648 
12649 	if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
12650 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
12651 	else
12652 		kvm_set_mp_state(vcpu, KVM_MP_STATE_UNINITIALIZED);
12653 
12654 	r = kvm_mmu_create(vcpu);
12655 	if (r < 0)
12656 		return r;
12657 
12658 	r = kvm_create_lapic(vcpu);
12659 	if (r < 0)
12660 		goto fail_mmu_destroy;
12661 
12662 	r = -ENOMEM;
12663 
12664 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
12665 	if (!page)
12666 		goto fail_free_lapic;
12667 	vcpu->arch.pio_data = page_address(page);
12668 
12669 	vcpu->arch.mce_banks = kcalloc(KVM_MAX_MCE_BANKS * 4, sizeof(u64),
12670 				       GFP_KERNEL_ACCOUNT);
12671 	vcpu->arch.mci_ctl2_banks = kcalloc(KVM_MAX_MCE_BANKS, sizeof(u64),
12672 					    GFP_KERNEL_ACCOUNT);
12673 	if (!vcpu->arch.mce_banks || !vcpu->arch.mci_ctl2_banks)
12674 		goto fail_free_mce_banks;
12675 	vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
12676 
12677 	if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
12678 				GFP_KERNEL_ACCOUNT))
12679 		goto fail_free_mce_banks;
12680 
12681 	if (!alloc_emulate_ctxt(vcpu))
12682 		goto free_wbinvd_dirty_mask;
12683 
12684 	if (!fpu_alloc_guest_fpstate(&vcpu->arch.guest_fpu)) {
12685 		pr_err("failed to allocate vcpu's fpu\n");
12686 		goto free_emulate_ctxt;
12687 	}
12688 
12689 	kvm_async_pf_hash_reset(vcpu);
12690 
12691 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) {
12692 		vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
12693 		vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
12694 		vcpu->arch.perf_capabilities = kvm_caps.supported_perf_cap;
12695 	}
12696 	kvm_pmu_init(vcpu);
12697 
12698 	vcpu->arch.pending_external_vector = -1;
12699 	vcpu->arch.preempted_in_kernel = false;
12700 
12701 #if IS_ENABLED(CONFIG_HYPERV)
12702 	vcpu->arch.hv_root_tdp = INVALID_PAGE;
12703 #endif
12704 
12705 	r = kvm_x86_call(vcpu_create)(vcpu);
12706 	if (r)
12707 		goto free_guest_fpu;
12708 
12709 	kvm_xen_init_vcpu(vcpu);
12710 	vcpu_load(vcpu);
12711 	kvm_vcpu_after_set_cpuid(vcpu);
12712 	kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz);
12713 	kvm_vcpu_reset(vcpu, false);
12714 	kvm_init_mmu(vcpu);
12715 	vcpu_put(vcpu);
12716 	return 0;
12717 
12718 free_guest_fpu:
12719 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12720 free_emulate_ctxt:
12721 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12722 free_wbinvd_dirty_mask:
12723 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12724 fail_free_mce_banks:
12725 	kfree(vcpu->arch.mce_banks);
12726 	kfree(vcpu->arch.mci_ctl2_banks);
12727 	free_page((unsigned long)vcpu->arch.pio_data);
12728 fail_free_lapic:
12729 	kvm_free_lapic(vcpu);
12730 fail_mmu_destroy:
12731 	kvm_mmu_destroy(vcpu);
12732 	return r;
12733 }
12734 
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)12735 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
12736 {
12737 	struct kvm *kvm = vcpu->kvm;
12738 
12739 	if (mutex_lock_killable(&vcpu->mutex))
12740 		return;
12741 	vcpu_load(vcpu);
12742 	kvm_synchronize_tsc(vcpu, NULL);
12743 	vcpu_put(vcpu);
12744 
12745 	/* poll control enabled by default */
12746 	vcpu->arch.msr_kvm_poll_control = 1;
12747 
12748 	mutex_unlock(&vcpu->mutex);
12749 
12750 	if (kvmclock_periodic_sync && vcpu->vcpu_idx == 0)
12751 		schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
12752 						KVMCLOCK_SYNC_PERIOD);
12753 }
12754 
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)12755 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
12756 {
12757 	int idx, cpu;
12758 
12759 	kvm_clear_async_pf_completion_queue(vcpu);
12760 	kvm_mmu_unload(vcpu);
12761 
12762 	kvmclock_reset(vcpu);
12763 
12764 	for_each_possible_cpu(cpu)
12765 		cmpxchg(per_cpu_ptr(&last_vcpu, cpu), vcpu, NULL);
12766 
12767 	kvm_x86_call(vcpu_free)(vcpu);
12768 
12769 	kmem_cache_free(x86_emulator_cache, vcpu->arch.emulate_ctxt);
12770 	free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
12771 	fpu_free_guest_fpstate(&vcpu->arch.guest_fpu);
12772 
12773 	kvm_xen_destroy_vcpu(vcpu);
12774 	kvm_hv_vcpu_uninit(vcpu);
12775 	kvm_pmu_destroy(vcpu);
12776 	kfree(vcpu->arch.mce_banks);
12777 	kfree(vcpu->arch.mci_ctl2_banks);
12778 	kvm_free_lapic(vcpu);
12779 	idx = srcu_read_lock(&vcpu->kvm->srcu);
12780 	kvm_mmu_destroy(vcpu);
12781 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
12782 	free_page((unsigned long)vcpu->arch.pio_data);
12783 	kvfree(vcpu->arch.cpuid_entries);
12784 }
12785 
kvm_xstate_reset(struct kvm_vcpu * vcpu,bool init_event)12786 static void kvm_xstate_reset(struct kvm_vcpu *vcpu, bool init_event)
12787 {
12788 	struct fpstate *fpstate = vcpu->arch.guest_fpu.fpstate;
12789 	u64 xfeatures_mask;
12790 	bool fpu_in_use;
12791 	int i;
12792 
12793 	/*
12794 	 * Guest FPU state is zero allocated and so doesn't need to be manually
12795 	 * cleared on RESET, i.e. during vCPU creation.
12796 	 */
12797 	if (!init_event || !fpstate)
12798 		return;
12799 
12800 	/*
12801 	 * On INIT, only select XSTATE components are zeroed, most components
12802 	 * are unchanged.  Currently, the only components that are zeroed and
12803 	 * supported by KVM are MPX and CET related.
12804 	 */
12805 	xfeatures_mask = (kvm_caps.supported_xcr0 | kvm_caps.supported_xss) &
12806 			 (XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR |
12807 			  XFEATURE_MASK_CET_ALL);
12808 	if (!xfeatures_mask)
12809 		return;
12810 
12811 	BUILD_BUG_ON(sizeof(xfeatures_mask) * BITS_PER_BYTE <= XFEATURE_MAX);
12812 
12813 	/*
12814 	 * Unload guest FPU state (if necessary) before zeroing XSTATE fields
12815 	 * as the kernel can only modify the state when its resident in memory,
12816 	 * i.e. when it's not loaded into hardware.
12817 	 *
12818 	 * WARN if the vCPU's desire to run, i.e. whether or not its in KVM_RUN,
12819 	 * doesn't match the loaded/in-use state of the FPU, as KVM_RUN is the
12820 	 * only path that can trigger INIT emulation _and_ loads FPU state, and
12821 	 * KVM_RUN should _always_ load FPU state.
12822 	 */
12823 	WARN_ON_ONCE(vcpu->wants_to_run != fpstate->in_use);
12824 	fpu_in_use = fpstate->in_use;
12825 	if (fpu_in_use)
12826 		kvm_put_guest_fpu(vcpu);
12827 	for_each_set_bit(i, (unsigned long *)&xfeatures_mask, XFEATURE_MAX)
12828 		fpstate_clear_xstate_component(fpstate, i);
12829 	if (fpu_in_use)
12830 		kvm_load_guest_fpu(vcpu);
12831 }
12832 
kvm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)12833 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
12834 {
12835 	struct kvm_cpuid_entry2 *cpuid_0x1;
12836 	unsigned long old_cr0 = kvm_read_cr0(vcpu);
12837 	unsigned long new_cr0;
12838 
12839 	/*
12840 	 * Several of the "set" flows, e.g. ->set_cr0(), read other registers
12841 	 * to handle side effects.  RESET emulation hits those flows and relies
12842 	 * on emulated/virtualized registers, including those that are loaded
12843 	 * into hardware, to be zeroed at vCPU creation.  Use CRs as a sentinel
12844 	 * to detect improper or missing initialization.
12845 	 */
12846 	WARN_ON_ONCE(!init_event &&
12847 		     (old_cr0 || kvm_read_cr3(vcpu) || kvm_read_cr4(vcpu)));
12848 
12849 	/*
12850 	 * SVM doesn't unconditionally VM-Exit on INIT and SHUTDOWN, thus it's
12851 	 * possible to INIT the vCPU while L2 is active.  Force the vCPU back
12852 	 * into L1 as EFER.SVME is cleared on INIT (along with all other EFER
12853 	 * bits), i.e. virtualization is disabled.
12854 	 */
12855 	if (is_guest_mode(vcpu))
12856 		kvm_leave_nested(vcpu);
12857 
12858 	kvm_lapic_reset(vcpu, init_event);
12859 
12860 	WARN_ON_ONCE(is_guest_mode(vcpu) || is_smm(vcpu));
12861 	vcpu->arch.hflags = 0;
12862 
12863 	vcpu->arch.smi_pending = 0;
12864 	vcpu->arch.smi_count = 0;
12865 	atomic_set(&vcpu->arch.nmi_queued, 0);
12866 	vcpu->arch.nmi_pending = 0;
12867 	vcpu->arch.nmi_injected = false;
12868 	kvm_clear_interrupt_queue(vcpu);
12869 	kvm_clear_exception_queue(vcpu);
12870 
12871 	memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
12872 	kvm_update_dr0123(vcpu);
12873 	vcpu->arch.dr6 = DR6_ACTIVE_LOW;
12874 	vcpu->arch.dr7 = DR7_FIXED_1;
12875 	kvm_update_dr7(vcpu);
12876 
12877 	vcpu->arch.cr2 = 0;
12878 
12879 	kvm_make_request(KVM_REQ_EVENT, vcpu);
12880 	vcpu->arch.apf.msr_en_val = 0;
12881 	vcpu->arch.apf.msr_int_val = 0;
12882 	vcpu->arch.st.msr_val = 0;
12883 
12884 	kvmclock_reset(vcpu);
12885 
12886 	kvm_clear_async_pf_completion_queue(vcpu);
12887 	kvm_async_pf_hash_reset(vcpu);
12888 	vcpu->arch.apf.halted = false;
12889 
12890 	kvm_xstate_reset(vcpu, init_event);
12891 
12892 	if (!init_event) {
12893 		vcpu->arch.smbase = 0x30000;
12894 
12895 		vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
12896 
12897 		vcpu->arch.msr_misc_features_enables = 0;
12898 		vcpu->arch.ia32_misc_enable_msr = MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL |
12899 						  MSR_IA32_MISC_ENABLE_BTS_UNAVAIL;
12900 
12901 		__kvm_set_xcr(vcpu, 0, XFEATURE_MASK_FP);
12902 		kvm_msr_write(vcpu, MSR_IA32_XSS, 0);
12903 	}
12904 
12905 	/* All GPRs except RDX (handled below) are zeroed on RESET/INIT. */
12906 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
12907 	kvm_register_mark_dirty(vcpu, VCPU_REGS_RSP);
12908 
12909 	/*
12910 	 * Fall back to KVM's default Family/Model/Stepping of 0x600 (P6/Athlon)
12911 	 * if no CPUID match is found.  Note, it's impossible to get a match at
12912 	 * RESET since KVM emulates RESET before exposing the vCPU to userspace,
12913 	 * i.e. it's impossible for kvm_find_cpuid_entry() to find a valid entry
12914 	 * on RESET.  But, go through the motions in case that's ever remedied.
12915 	 */
12916 	cpuid_0x1 = kvm_find_cpuid_entry(vcpu, 1);
12917 	kvm_rdx_write(vcpu, cpuid_0x1 ? cpuid_0x1->eax : 0x600);
12918 
12919 	kvm_x86_call(vcpu_reset)(vcpu, init_event);
12920 
12921 	kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
12922 	kvm_rip_write(vcpu, 0xfff0);
12923 
12924 	vcpu->arch.cr3 = 0;
12925 	kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
12926 
12927 	/*
12928 	 * CR0.CD/NW are set on RESET, preserved on INIT.  Note, some versions
12929 	 * of Intel's SDM list CD/NW as being set on INIT, but they contradict
12930 	 * (or qualify) that with a footnote stating that CD/NW are preserved.
12931 	 */
12932 	new_cr0 = X86_CR0_ET;
12933 	if (init_event)
12934 		new_cr0 |= (old_cr0 & (X86_CR0_NW | X86_CR0_CD));
12935 	else
12936 		new_cr0 |= X86_CR0_NW | X86_CR0_CD;
12937 
12938 	kvm_x86_call(set_cr0)(vcpu, new_cr0);
12939 	kvm_x86_call(set_cr4)(vcpu, 0);
12940 	kvm_x86_call(set_efer)(vcpu, 0);
12941 	kvm_x86_call(update_exception_bitmap)(vcpu);
12942 
12943 	/*
12944 	 * On the standard CR0/CR4/EFER modification paths, there are several
12945 	 * complex conditions determining whether the MMU has to be reset and/or
12946 	 * which PCIDs have to be flushed.  However, CR0.WP and the paging-related
12947 	 * bits in CR4 and EFER are irrelevant if CR0.PG was '0'; and a reset+flush
12948 	 * is needed anyway if CR0.PG was '1' (which can only happen for INIT, as
12949 	 * CR0 will be '0' prior to RESET).  So we only need to check CR0.PG here.
12950 	 */
12951 	if (old_cr0 & X86_CR0_PG) {
12952 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12953 		kvm_mmu_reset_context(vcpu);
12954 	}
12955 
12956 	/*
12957 	 * Intel's SDM states that all TLB entries are flushed on INIT.  AMD's
12958 	 * APM states the TLBs are untouched by INIT, but it also states that
12959 	 * the TLBs are flushed on "External initialization of the processor."
12960 	 * Flush the guest TLB regardless of vendor, there is no meaningful
12961 	 * benefit in relying on the guest to flush the TLB immediately after
12962 	 * INIT.  A spurious TLB flush is benign and likely negligible from a
12963 	 * performance perspective.
12964 	 */
12965 	if (init_event)
12966 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
12967 }
12968 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_reset);
12969 
kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)12970 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
12971 {
12972 	struct kvm_segment cs;
12973 
12974 	kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
12975 	cs.selector = vector << 8;
12976 	cs.base = vector << 12;
12977 	kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
12978 	kvm_rip_write(vcpu, 0);
12979 }
12980 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_deliver_sipi_vector);
12981 
kvm_arch_enable_virtualization(void)12982 void kvm_arch_enable_virtualization(void)
12983 {
12984 	cpu_emergency_register_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12985 }
12986 
kvm_arch_disable_virtualization(void)12987 void kvm_arch_disable_virtualization(void)
12988 {
12989 	cpu_emergency_unregister_virt_callback(kvm_x86_ops.emergency_disable_virtualization_cpu);
12990 }
12991 
kvm_arch_enable_virtualization_cpu(void)12992 int kvm_arch_enable_virtualization_cpu(void)
12993 {
12994 	struct kvm *kvm;
12995 	struct kvm_vcpu *vcpu;
12996 	unsigned long i;
12997 	int ret;
12998 	u64 local_tsc;
12999 	u64 max_tsc = 0;
13000 	bool stable, backwards_tsc = false;
13001 
13002 	kvm_user_return_msr_cpu_online();
13003 
13004 	ret = kvm_x86_check_processor_compatibility();
13005 	if (ret)
13006 		return ret;
13007 
13008 	ret = kvm_x86_call(enable_virtualization_cpu)();
13009 	if (ret != 0)
13010 		return ret;
13011 
13012 	local_tsc = rdtsc();
13013 	stable = !kvm_check_tsc_unstable();
13014 	list_for_each_entry(kvm, &vm_list, vm_list) {
13015 		kvm_for_each_vcpu(i, vcpu, kvm) {
13016 			if (!stable && vcpu->cpu == smp_processor_id())
13017 				kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
13018 			if (stable && vcpu->arch.last_host_tsc > local_tsc) {
13019 				backwards_tsc = true;
13020 				if (vcpu->arch.last_host_tsc > max_tsc)
13021 					max_tsc = vcpu->arch.last_host_tsc;
13022 			}
13023 		}
13024 	}
13025 
13026 	/*
13027 	 * Sometimes, even reliable TSCs go backwards.  This happens on
13028 	 * platforms that reset TSC during suspend or hibernate actions, but
13029 	 * maintain synchronization.  We must compensate.  Fortunately, we can
13030 	 * detect that condition here, which happens early in CPU bringup,
13031 	 * before any KVM threads can be running.  Unfortunately, we can't
13032 	 * bring the TSCs fully up to date with real time, as we aren't yet far
13033 	 * enough into CPU bringup that we know how much real time has actually
13034 	 * elapsed; our helper function, ktime_get_boottime_ns() will be using boot
13035 	 * variables that haven't been updated yet.
13036 	 *
13037 	 * So we simply find the maximum observed TSC above, then record the
13038 	 * adjustment to TSC in each VCPU.  When the VCPU later gets loaded,
13039 	 * the adjustment will be applied.  Note that we accumulate
13040 	 * adjustments, in case multiple suspend cycles happen before some VCPU
13041 	 * gets a chance to run again.  In the event that no KVM threads get a
13042 	 * chance to run, we will miss the entire elapsed period, as we'll have
13043 	 * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
13044 	 * loose cycle time.  This isn't too big a deal, since the loss will be
13045 	 * uniform across all VCPUs (not to mention the scenario is extremely
13046 	 * unlikely). It is possible that a second hibernate recovery happens
13047 	 * much faster than a first, causing the observed TSC here to be
13048 	 * smaller; this would require additional padding adjustment, which is
13049 	 * why we set last_host_tsc to the local tsc observed here.
13050 	 *
13051 	 * N.B. - this code below runs only on platforms with reliable TSC,
13052 	 * as that is the only way backwards_tsc is set above.  Also note
13053 	 * that this runs for ALL vcpus, which is not a bug; all VCPUs should
13054 	 * have the same delta_cyc adjustment applied if backwards_tsc
13055 	 * is detected.  Note further, this adjustment is only done once,
13056 	 * as we reset last_host_tsc on all VCPUs to stop this from being
13057 	 * called multiple times (one for each physical CPU bringup).
13058 	 *
13059 	 * Platforms with unreliable TSCs don't have to deal with this, they
13060 	 * will be compensated by the logic in vcpu_load, which sets the TSC to
13061 	 * catchup mode.  This will catchup all VCPUs to real time, but cannot
13062 	 * guarantee that they stay in perfect synchronization.
13063 	 */
13064 	if (backwards_tsc) {
13065 		u64 delta_cyc = max_tsc - local_tsc;
13066 		list_for_each_entry(kvm, &vm_list, vm_list) {
13067 			kvm->arch.backwards_tsc_observed = true;
13068 			kvm_for_each_vcpu(i, vcpu, kvm) {
13069 				vcpu->arch.tsc_offset_adjustment += delta_cyc;
13070 				vcpu->arch.last_host_tsc = local_tsc;
13071 				kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
13072 			}
13073 
13074 			/*
13075 			 * We have to disable TSC offset matching.. if you were
13076 			 * booting a VM while issuing an S4 host suspend....
13077 			 * you may have some problem.  Solving this issue is
13078 			 * left as an exercise to the reader.
13079 			 */
13080 			kvm->arch.last_tsc_nsec = 0;
13081 			kvm->arch.last_tsc_write = 0;
13082 		}
13083 
13084 	}
13085 	return 0;
13086 }
13087 
kvm_arch_disable_virtualization_cpu(void)13088 void kvm_arch_disable_virtualization_cpu(void)
13089 {
13090 	kvm_x86_call(disable_virtualization_cpu)();
13091 	drop_user_return_notifiers();
13092 }
13093 
kvm_vcpu_is_reset_bsp(struct kvm_vcpu * vcpu)13094 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
13095 {
13096 	return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
13097 }
13098 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_is_reset_bsp);
13099 
kvm_vcpu_is_bsp(struct kvm_vcpu * vcpu)13100 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
13101 {
13102 	return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
13103 }
13104 
kvm_arch_free_vm(struct kvm * kvm)13105 void kvm_arch_free_vm(struct kvm *kvm)
13106 {
13107 #if IS_ENABLED(CONFIG_HYPERV)
13108 	kfree(kvm->arch.hv_pa_pg);
13109 #endif
13110 	__kvm_arch_free_vm(kvm);
13111 }
13112 
13113 
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)13114 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
13115 {
13116 	int ret;
13117 	unsigned long flags;
13118 
13119 	if (!kvm_is_vm_type_supported(type))
13120 		return -EINVAL;
13121 
13122 	kvm->arch.vm_type = type;
13123 	kvm->arch.has_private_mem =
13124 		(type == KVM_X86_SW_PROTECTED_VM);
13125 	/* Decided by the vendor code for other VM types.  */
13126 	kvm->arch.pre_fault_allowed =
13127 		type == KVM_X86_DEFAULT_VM || type == KVM_X86_SW_PROTECTED_VM;
13128 	kvm->arch.disabled_quirks = kvm_caps.inapplicable_quirks & kvm_caps.supported_quirks;
13129 
13130 	ret = kvm_page_track_init(kvm);
13131 	if (ret)
13132 		goto out;
13133 
13134 	ret = kvm_mmu_init_vm(kvm);
13135 	if (ret)
13136 		goto out_cleanup_page_track;
13137 
13138 	ret = kvm_x86_call(vm_init)(kvm);
13139 	if (ret)
13140 		goto out_uninit_mmu;
13141 
13142 	atomic_set(&kvm->arch.noncoherent_dma_count, 0);
13143 
13144 	raw_spin_lock_init(&kvm->arch.tsc_write_lock);
13145 	mutex_init(&kvm->arch.apic_map_lock);
13146 	seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lock);
13147 	kvm->arch.kvmclock_offset = -get_kvmclock_base_ns();
13148 
13149 	raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
13150 	pvclock_update_vm_gtod_copy(kvm);
13151 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
13152 
13153 	kvm->arch.default_tsc_khz = max_tsc_khz ? : tsc_khz;
13154 	kvm->arch.apic_bus_cycle_ns = APIC_BUS_CYCLE_NS_DEFAULT;
13155 	kvm->arch.guest_can_read_msr_platform_info = true;
13156 	kvm->arch.enable_pmu = enable_pmu;
13157 
13158 #if IS_ENABLED(CONFIG_HYPERV)
13159 	spin_lock_init(&kvm->arch.hv_root_tdp_lock);
13160 	kvm->arch.hv_root_tdp = INVALID_PAGE;
13161 #endif
13162 
13163 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
13164 	INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
13165 
13166 	kvm_apicv_init(kvm);
13167 	kvm_hv_init_vm(kvm);
13168 	kvm_xen_init_vm(kvm);
13169 
13170 	if (ignore_msrs && !report_ignored_msrs) {
13171 		pr_warn_once("Running KVM with ignore_msrs=1 and report_ignored_msrs=0 is not a\n"
13172 			     "a supported configuration.  Lying to the guest about the existence of MSRs\n"
13173 			     "may cause the guest operating system to hang or produce errors.  If a guest\n"
13174 			     "does not run without ignore_msrs=1, please report it to kvm@vger.kernel.org.\n");
13175 	}
13176 
13177 	once_init(&kvm->arch.nx_once);
13178 	return 0;
13179 
13180 out_uninit_mmu:
13181 	kvm_mmu_uninit_vm(kvm);
13182 out_cleanup_page_track:
13183 	kvm_page_track_cleanup(kvm);
13184 out:
13185 	return ret;
13186 }
13187 
13188 /**
13189  * __x86_set_memory_region: Setup KVM internal memory slot
13190  *
13191  * @kvm: the kvm pointer to the VM.
13192  * @id: the slot ID to setup.
13193  * @gpa: the GPA to install the slot (unused when @size == 0).
13194  * @size: the size of the slot. Set to zero to uninstall a slot.
13195  *
13196  * This function helps to setup a KVM internal memory slot.  Specify
13197  * @size > 0 to install a new slot, while @size == 0 to uninstall a
13198  * slot.  The return code can be one of the following:
13199  *
13200  *   HVA:           on success (uninstall will return a bogus HVA)
13201  *   -errno:        on error
13202  *
13203  * The caller should always use IS_ERR() to check the return value
13204  * before use.  Note, the KVM internal memory slots are guaranteed to
13205  * remain valid and unchanged until the VM is destroyed, i.e., the
13206  * GPA->HVA translation will not change.  However, the HVA is a user
13207  * address, i.e. its accessibility is not guaranteed, and must be
13208  * accessed via __copy_{to,from}_user().
13209  */
__x86_set_memory_region(struct kvm * kvm,int id,gpa_t gpa,u32 size)13210 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
13211 				      u32 size)
13212 {
13213 	int i, r;
13214 	unsigned long hva, old_npages;
13215 	struct kvm_memslots *slots = kvm_memslots(kvm);
13216 	struct kvm_memory_slot *slot;
13217 
13218 	lockdep_assert_held(&kvm->slots_lock);
13219 
13220 	if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
13221 		return ERR_PTR_USR(-EINVAL);
13222 
13223 	slot = id_to_memslot(slots, id);
13224 	if (size) {
13225 		if (slot && slot->npages)
13226 			return ERR_PTR_USR(-EEXIST);
13227 
13228 		/*
13229 		 * MAP_SHARED to prevent internal slot pages from being moved
13230 		 * by fork()/COW.
13231 		 */
13232 		hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
13233 			      MAP_SHARED | MAP_ANONYMOUS, 0);
13234 		if (IS_ERR_VALUE(hva))
13235 			return (void __user *)hva;
13236 	} else {
13237 		if (!slot || !slot->npages)
13238 			return NULL;
13239 
13240 		old_npages = slot->npages;
13241 		hva = slot->userspace_addr;
13242 	}
13243 
13244 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
13245 		struct kvm_userspace_memory_region2 m;
13246 
13247 		m.slot = id | (i << 16);
13248 		m.flags = 0;
13249 		m.guest_phys_addr = gpa;
13250 		m.userspace_addr = hva;
13251 		m.memory_size = size;
13252 		r = kvm_set_internal_memslot(kvm, &m);
13253 		if (r < 0)
13254 			return ERR_PTR_USR(r);
13255 	}
13256 
13257 	if (!size)
13258 		vm_munmap(hva, old_npages * PAGE_SIZE);
13259 
13260 	return (void __user *)hva;
13261 }
13262 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__x86_set_memory_region);
13263 
kvm_arch_pre_destroy_vm(struct kvm * kvm)13264 void kvm_arch_pre_destroy_vm(struct kvm *kvm)
13265 {
13266 	/*
13267 	 * Stop all background workers and kthreads before destroying vCPUs, as
13268 	 * iterating over vCPUs in a different task while vCPUs are being freed
13269 	 * is unsafe, i.e. will lead to use-after-free.  The PIT also needs to
13270 	 * be stopped before IRQ routing is freed.
13271 	 */
13272 	cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
13273 	cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
13274 
13275 #ifdef CONFIG_KVM_IOAPIC
13276 	kvm_free_pit(kvm);
13277 #endif
13278 
13279 	kvm_mmu_pre_destroy_vm(kvm);
13280 	static_call_cond(kvm_x86_vm_pre_destroy)(kvm);
13281 }
13282 
kvm_arch_destroy_vm(struct kvm * kvm)13283 void kvm_arch_destroy_vm(struct kvm *kvm)
13284 {
13285 	if (current->mm == kvm->mm) {
13286 		/*
13287 		 * Free memory regions allocated on behalf of userspace,
13288 		 * unless the memory map has changed due to process exit
13289 		 * or fd copying.
13290 		 */
13291 		mutex_lock(&kvm->slots_lock);
13292 		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
13293 					0, 0);
13294 		__x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
13295 					0, 0);
13296 		__x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
13297 		mutex_unlock(&kvm->slots_lock);
13298 	}
13299 	kvm_destroy_vcpus(kvm);
13300 	kvm_free_msr_filter(srcu_dereference_check(kvm->arch.msr_filter, &kvm->srcu, 1));
13301 #ifdef CONFIG_KVM_IOAPIC
13302 	kvm_pic_destroy(kvm);
13303 	kvm_ioapic_destroy(kvm);
13304 #endif
13305 	kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
13306 	kfree(srcu_dereference_check(kvm->arch.pmu_event_filter, &kvm->srcu, 1));
13307 	kvm_mmu_uninit_vm(kvm);
13308 	kvm_page_track_cleanup(kvm);
13309 	kvm_xen_destroy_vm(kvm);
13310 	kvm_hv_destroy_vm(kvm);
13311 	kvm_x86_call(vm_destroy)(kvm);
13312 }
13313 
memslot_rmap_free(struct kvm_memory_slot * slot)13314 static void memslot_rmap_free(struct kvm_memory_slot *slot)
13315 {
13316 	int i;
13317 
13318 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13319 		vfree(slot->arch.rmap[i]);
13320 		slot->arch.rmap[i] = NULL;
13321 	}
13322 }
13323 
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)13324 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
13325 {
13326 	int i;
13327 
13328 	memslot_rmap_free(slot);
13329 
13330 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13331 		vfree(slot->arch.lpage_info[i - 1]);
13332 		slot->arch.lpage_info[i - 1] = NULL;
13333 	}
13334 
13335 	kvm_page_track_free_memslot(slot);
13336 }
13337 
memslot_rmap_alloc(struct kvm_memory_slot * slot,unsigned long npages)13338 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
13339 {
13340 	const int sz = sizeof(*slot->arch.rmap[0]);
13341 	int i;
13342 
13343 	for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
13344 		int level = i + 1;
13345 		int lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13346 
13347 		if (slot->arch.rmap[i])
13348 			continue;
13349 
13350 		slot->arch.rmap[i] = __vcalloc(lpages, sz, GFP_KERNEL_ACCOUNT);
13351 		if (!slot->arch.rmap[i]) {
13352 			memslot_rmap_free(slot);
13353 			return -ENOMEM;
13354 		}
13355 	}
13356 
13357 	return 0;
13358 }
13359 
kvm_alloc_memslot_metadata(struct kvm * kvm,struct kvm_memory_slot * slot)13360 static int kvm_alloc_memslot_metadata(struct kvm *kvm,
13361 				      struct kvm_memory_slot *slot)
13362 {
13363 	unsigned long npages = slot->npages;
13364 	int i, r;
13365 
13366 	/*
13367 	 * Clear out the previous array pointers for the KVM_MR_MOVE case.  The
13368 	 * old arrays will be freed by kvm_set_memory_region() if installing
13369 	 * the new memslot is successful.
13370 	 */
13371 	memset(&slot->arch, 0, sizeof(slot->arch));
13372 
13373 	if (kvm_memslots_have_rmaps(kvm)) {
13374 		r = memslot_rmap_alloc(slot, npages);
13375 		if (r)
13376 			return r;
13377 	}
13378 
13379 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13380 		struct kvm_lpage_info *linfo;
13381 		unsigned long ugfn;
13382 		int lpages;
13383 		int level = i + 1;
13384 
13385 		lpages = __kvm_mmu_slot_lpages(slot, npages, level);
13386 
13387 		linfo = __vcalloc(lpages, sizeof(*linfo), GFP_KERNEL_ACCOUNT);
13388 		if (!linfo)
13389 			goto out_free;
13390 
13391 		slot->arch.lpage_info[i - 1] = linfo;
13392 
13393 		if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
13394 			linfo[0].disallow_lpage = 1;
13395 		if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
13396 			linfo[lpages - 1].disallow_lpage = 1;
13397 		ugfn = slot->userspace_addr >> PAGE_SHIFT;
13398 		/*
13399 		 * If the gfn and userspace address are not aligned wrt each
13400 		 * other, disable large page support for this slot.
13401 		 */
13402 		if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1)) {
13403 			unsigned long j;
13404 
13405 			for (j = 0; j < lpages; ++j)
13406 				linfo[j].disallow_lpage = 1;
13407 		}
13408 	}
13409 
13410 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
13411 	kvm_mmu_init_memslot_memory_attributes(kvm, slot);
13412 #endif
13413 
13414 	if (kvm_page_track_create_memslot(kvm, slot, npages))
13415 		goto out_free;
13416 
13417 	return 0;
13418 
13419 out_free:
13420 	memslot_rmap_free(slot);
13421 
13422 	for (i = 1; i < KVM_NR_PAGE_SIZES; ++i) {
13423 		vfree(slot->arch.lpage_info[i - 1]);
13424 		slot->arch.lpage_info[i - 1] = NULL;
13425 	}
13426 	return -ENOMEM;
13427 }
13428 
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)13429 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
13430 {
13431 	struct kvm_vcpu *vcpu;
13432 	unsigned long i;
13433 
13434 	/*
13435 	 * memslots->generation has been incremented.
13436 	 * mmio generation may have reached its maximum value.
13437 	 */
13438 	kvm_mmu_invalidate_mmio_sptes(kvm, gen);
13439 
13440 	/* Force re-initialization of steal_time cache */
13441 	kvm_for_each_vcpu(i, vcpu, kvm)
13442 		kvm_vcpu_kick(vcpu);
13443 }
13444 
kvm_arch_prepare_memory_region(struct kvm * kvm,const struct kvm_memory_slot * old,struct kvm_memory_slot * new,enum kvm_mr_change change)13445 int kvm_arch_prepare_memory_region(struct kvm *kvm,
13446 				   const struct kvm_memory_slot *old,
13447 				   struct kvm_memory_slot *new,
13448 				   enum kvm_mr_change change)
13449 {
13450 	/*
13451 	 * KVM doesn't support moving memslots when there are external page
13452 	 * trackers attached to the VM, i.e. if KVMGT is in use.
13453 	 */
13454 	if (change == KVM_MR_MOVE && kvm_page_track_has_external_user(kvm))
13455 		return -EINVAL;
13456 
13457 	if (change == KVM_MR_CREATE || change == KVM_MR_MOVE) {
13458 		if ((new->base_gfn + new->npages - 1) > kvm_mmu_max_gfn())
13459 			return -EINVAL;
13460 
13461 		if (kvm_is_gfn_alias(kvm, new->base_gfn + new->npages - 1))
13462 			return -EINVAL;
13463 
13464 		return kvm_alloc_memslot_metadata(kvm, new);
13465 	}
13466 
13467 	if (change == KVM_MR_FLAGS_ONLY)
13468 		memcpy(&new->arch, &old->arch, sizeof(old->arch));
13469 	else if (WARN_ON_ONCE(change != KVM_MR_DELETE))
13470 		return -EIO;
13471 
13472 	return 0;
13473 }
13474 
13475 
kvm_mmu_update_cpu_dirty_logging(struct kvm * kvm,bool enable)13476 static void kvm_mmu_update_cpu_dirty_logging(struct kvm *kvm, bool enable)
13477 {
13478 	int nr_slots;
13479 
13480 	if (!kvm->arch.cpu_dirty_log_size)
13481 		return;
13482 
13483 	nr_slots = atomic_read(&kvm->nr_memslots_dirty_logging);
13484 	if ((enable && nr_slots == 1) || !nr_slots)
13485 		kvm_make_all_cpus_request(kvm, KVM_REQ_UPDATE_CPU_DIRTY_LOGGING);
13486 }
13487 
kvm_mmu_slot_apply_flags(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13488 static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
13489 				     struct kvm_memory_slot *old,
13490 				     const struct kvm_memory_slot *new,
13491 				     enum kvm_mr_change change)
13492 {
13493 	u32 old_flags = old ? old->flags : 0;
13494 	u32 new_flags = new ? new->flags : 0;
13495 	bool log_dirty_pages = new_flags & KVM_MEM_LOG_DIRTY_PAGES;
13496 
13497 	/*
13498 	 * Update CPU dirty logging if dirty logging is being toggled.  This
13499 	 * applies to all operations.
13500 	 */
13501 	if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)
13502 		kvm_mmu_update_cpu_dirty_logging(kvm, log_dirty_pages);
13503 
13504 	/*
13505 	 * Nothing more to do for RO slots (which can't be dirtied and can't be
13506 	 * made writable) or CREATE/MOVE/DELETE of a slot.
13507 	 *
13508 	 * For a memslot with dirty logging disabled:
13509 	 * CREATE:      No dirty mappings will already exist.
13510 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
13511 	 *		kvm_arch_flush_shadow_memslot()
13512 	 *
13513 	 * For a memslot with dirty logging enabled:
13514 	 * CREATE:      No shadow pages exist, thus nothing to write-protect
13515 	 *		and no dirty bits to clear.
13516 	 * MOVE/DELETE: The old mappings will already have been cleaned up by
13517 	 *		kvm_arch_flush_shadow_memslot().
13518 	 */
13519 	if ((change != KVM_MR_FLAGS_ONLY) || (new_flags & KVM_MEM_READONLY))
13520 		return;
13521 
13522 	/*
13523 	 * READONLY and non-flags changes were filtered out above, and the only
13524 	 * other flag is LOG_DIRTY_PAGES, i.e. something is wrong if dirty
13525 	 * logging isn't being toggled on or off.
13526 	 */
13527 	if (WARN_ON_ONCE(!((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES)))
13528 		return;
13529 
13530 	if (!log_dirty_pages) {
13531 		/*
13532 		 * Recover huge page mappings in the slot now that dirty logging
13533 		 * is disabled, i.e. now that KVM does not have to track guest
13534 		 * writes at 4KiB granularity.
13535 		 *
13536 		 * Dirty logging might be disabled by userspace if an ongoing VM
13537 		 * live migration is cancelled and the VM must continue running
13538 		 * on the source.
13539 		 */
13540 		kvm_mmu_recover_huge_pages(kvm, new);
13541 	} else {
13542 		/*
13543 		 * Initially-all-set does not require write protecting any page,
13544 		 * because they're all assumed to be dirty.
13545 		 */
13546 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
13547 			return;
13548 
13549 		if (READ_ONCE(eager_page_split))
13550 			kvm_mmu_slot_try_split_huge_pages(kvm, new, PG_LEVEL_4K);
13551 
13552 		if (kvm->arch.cpu_dirty_log_size) {
13553 			kvm_mmu_slot_leaf_clear_dirty(kvm, new);
13554 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_2M);
13555 		} else {
13556 			kvm_mmu_slot_remove_write_access(kvm, new, PG_LEVEL_4K);
13557 		}
13558 
13559 		/*
13560 		 * Unconditionally flush the TLBs after enabling dirty logging.
13561 		 * A flush is almost always going to be necessary (see below),
13562 		 * and unconditionally flushing allows the helpers to omit
13563 		 * the subtly complex checks when removing write access.
13564 		 *
13565 		 * Do the flush outside of mmu_lock to reduce the amount of
13566 		 * time mmu_lock is held.  Flushing after dropping mmu_lock is
13567 		 * safe as KVM only needs to guarantee the slot is fully
13568 		 * write-protected before returning to userspace, i.e. before
13569 		 * userspace can consume the dirty status.
13570 		 *
13571 		 * Flushing outside of mmu_lock requires KVM to be careful when
13572 		 * making decisions based on writable status of an SPTE, e.g. a
13573 		 * !writable SPTE doesn't guarantee a CPU can't perform writes.
13574 		 *
13575 		 * Specifically, KVM also write-protects guest page tables to
13576 		 * monitor changes when using shadow paging, and must guarantee
13577 		 * no CPUs can write to those page before mmu_lock is dropped.
13578 		 * Because CPUs may have stale TLB entries at this point, a
13579 		 * !writable SPTE doesn't guarantee CPUs can't perform writes.
13580 		 *
13581 		 * KVM also allows making SPTES writable outside of mmu_lock,
13582 		 * e.g. to allow dirty logging without taking mmu_lock.
13583 		 *
13584 		 * To handle these scenarios, KVM uses a separate software-only
13585 		 * bit (MMU-writable) to track if a SPTE is !writable due to
13586 		 * a guest page table being write-protected (KVM clears the
13587 		 * MMU-writable flag when write-protecting for shadow paging).
13588 		 *
13589 		 * The use of MMU-writable is also the primary motivation for
13590 		 * the unconditional flush.  Because KVM must guarantee that a
13591 		 * CPU doesn't contain stale, writable TLB entries for a
13592 		 * !MMU-writable SPTE, KVM must flush if it encounters any
13593 		 * MMU-writable SPTE regardless of whether the actual hardware
13594 		 * writable bit was set.  I.e. KVM is almost guaranteed to need
13595 		 * to flush, while unconditionally flushing allows the "remove
13596 		 * write access" helpers to ignore MMU-writable entirely.
13597 		 *
13598 		 * See is_writable_pte() for more details (the case involving
13599 		 * access-tracked SPTEs is particularly relevant).
13600 		 */
13601 		kvm_flush_remote_tlbs_memslot(kvm, new);
13602 	}
13603 }
13604 
kvm_arch_commit_memory_region(struct kvm * kvm,struct kvm_memory_slot * old,const struct kvm_memory_slot * new,enum kvm_mr_change change)13605 void kvm_arch_commit_memory_region(struct kvm *kvm,
13606 				struct kvm_memory_slot *old,
13607 				const struct kvm_memory_slot *new,
13608 				enum kvm_mr_change change)
13609 {
13610 	if (change == KVM_MR_DELETE)
13611 		kvm_page_track_delete_slot(kvm, old);
13612 
13613 	if (!kvm->arch.n_requested_mmu_pages &&
13614 	    (change == KVM_MR_CREATE || change == KVM_MR_DELETE)) {
13615 		unsigned long nr_mmu_pages;
13616 
13617 		nr_mmu_pages = kvm->nr_memslot_pages / KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO;
13618 		nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
13619 		kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
13620 	}
13621 
13622 	kvm_mmu_slot_apply_flags(kvm, old, new, change);
13623 
13624 	/* Free the arrays associated with the old memslot. */
13625 	if (change == KVM_MR_MOVE)
13626 		kvm_arch_free_memslot(kvm, old);
13627 }
13628 
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)13629 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
13630 {
13631 	WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13632 
13633 	if (vcpu->arch.guest_state_protected)
13634 		return true;
13635 
13636 	return kvm_x86_call(get_cpl)(vcpu) == 0;
13637 }
13638 
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)13639 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
13640 {
13641 	WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu));
13642 
13643 	if (vcpu->arch.guest_state_protected)
13644 		return 0;
13645 
13646 	return kvm_rip_read(vcpu);
13647 }
13648 
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)13649 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
13650 {
13651 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
13652 }
13653 
kvm_arch_interrupt_allowed(struct kvm_vcpu * vcpu)13654 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
13655 {
13656 	return kvm_x86_call(interrupt_allowed)(vcpu, false);
13657 }
13658 
kvm_get_linear_rip(struct kvm_vcpu * vcpu)13659 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
13660 {
13661 	/* Can't read the RIP when guest state is protected, just return 0 */
13662 	if (vcpu->arch.guest_state_protected)
13663 		return 0;
13664 
13665 	if (is_64_bit_mode(vcpu))
13666 		return kvm_rip_read(vcpu);
13667 	return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
13668 		     kvm_rip_read(vcpu));
13669 }
13670 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_linear_rip);
13671 
kvm_is_linear_rip(struct kvm_vcpu * vcpu,unsigned long linear_rip)13672 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
13673 {
13674 	return kvm_get_linear_rip(vcpu) == linear_rip;
13675 }
13676 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_is_linear_rip);
13677 
kvm_get_rflags(struct kvm_vcpu * vcpu)13678 unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
13679 {
13680 	unsigned long rflags;
13681 
13682 	rflags = kvm_x86_call(get_rflags)(vcpu);
13683 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
13684 		rflags &= ~X86_EFLAGS_TF;
13685 	return rflags;
13686 }
13687 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_rflags);
13688 
__kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13689 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13690 {
13691 	if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
13692 	    kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
13693 		rflags |= X86_EFLAGS_TF;
13694 	kvm_x86_call(set_rflags)(vcpu, rflags);
13695 }
13696 
kvm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)13697 void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
13698 {
13699 	__kvm_set_rflags(vcpu, rflags);
13700 	kvm_make_request(KVM_REQ_EVENT, vcpu);
13701 }
13702 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_set_rflags);
13703 
kvm_async_pf_hash_fn(gfn_t gfn)13704 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
13705 {
13706 	BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU));
13707 
13708 	return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
13709 }
13710 
kvm_async_pf_next_probe(u32 key)13711 static inline u32 kvm_async_pf_next_probe(u32 key)
13712 {
13713 	return (key + 1) & (ASYNC_PF_PER_VCPU - 1);
13714 }
13715 
kvm_add_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13716 static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13717 {
13718 	u32 key = kvm_async_pf_hash_fn(gfn);
13719 
13720 	while (vcpu->arch.apf.gfns[key] != ~0)
13721 		key = kvm_async_pf_next_probe(key);
13722 
13723 	vcpu->arch.apf.gfns[key] = gfn;
13724 }
13725 
kvm_async_pf_gfn_slot(struct kvm_vcpu * vcpu,gfn_t gfn)13726 static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
13727 {
13728 	int i;
13729 	u32 key = kvm_async_pf_hash_fn(gfn);
13730 
13731 	for (i = 0; i < ASYNC_PF_PER_VCPU &&
13732 		     (vcpu->arch.apf.gfns[key] != gfn &&
13733 		      vcpu->arch.apf.gfns[key] != ~0); i++)
13734 		key = kvm_async_pf_next_probe(key);
13735 
13736 	return key;
13737 }
13738 
kvm_find_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13739 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13740 {
13741 	return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
13742 }
13743 
kvm_del_async_pf_gfn(struct kvm_vcpu * vcpu,gfn_t gfn)13744 static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
13745 {
13746 	u32 i, j, k;
13747 
13748 	i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
13749 
13750 	if (WARN_ON_ONCE(vcpu->arch.apf.gfns[i] != gfn))
13751 		return;
13752 
13753 	while (true) {
13754 		vcpu->arch.apf.gfns[i] = ~0;
13755 		do {
13756 			j = kvm_async_pf_next_probe(j);
13757 			if (vcpu->arch.apf.gfns[j] == ~0)
13758 				return;
13759 			k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
13760 			/*
13761 			 * k lies cyclically in ]i,j]
13762 			 * |    i.k.j |
13763 			 * |....j i.k.| or  |.k..j i...|
13764 			 */
13765 		} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
13766 		vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
13767 		i = j;
13768 	}
13769 }
13770 
apf_put_user_notpresent(struct kvm_vcpu * vcpu)13771 static inline int apf_put_user_notpresent(struct kvm_vcpu *vcpu)
13772 {
13773 	u32 reason = KVM_PV_REASON_PAGE_NOT_PRESENT;
13774 
13775 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &reason,
13776 				      sizeof(reason));
13777 }
13778 
apf_put_user_ready(struct kvm_vcpu * vcpu,u32 token)13779 static inline int apf_put_user_ready(struct kvm_vcpu *vcpu, u32 token)
13780 {
13781 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13782 
13783 	return kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13784 					     &token, offset, sizeof(token));
13785 }
13786 
apf_pageready_slot_free(struct kvm_vcpu * vcpu)13787 static inline bool apf_pageready_slot_free(struct kvm_vcpu *vcpu)
13788 {
13789 	unsigned int offset = offsetof(struct kvm_vcpu_pv_apf_data, token);
13790 	u32 val;
13791 
13792 	if (kvm_read_guest_offset_cached(vcpu->kvm, &vcpu->arch.apf.data,
13793 					 &val, offset, sizeof(val)))
13794 		return false;
13795 
13796 	return !val;
13797 }
13798 
kvm_can_deliver_async_pf(struct kvm_vcpu * vcpu)13799 static bool kvm_can_deliver_async_pf(struct kvm_vcpu *vcpu)
13800 {
13801 
13802 	if (!kvm_pv_async_pf_enabled(vcpu))
13803 		return false;
13804 
13805 	if (!vcpu->arch.apf.send_always &&
13806 	    (vcpu->arch.guest_state_protected || !kvm_x86_call(get_cpl)(vcpu)))
13807 		return false;
13808 
13809 	if (is_guest_mode(vcpu)) {
13810 		/*
13811 		 * L1 needs to opt into the special #PF vmexits that are
13812 		 * used to deliver async page faults.
13813 		 */
13814 		return vcpu->arch.apf.delivery_as_pf_vmexit;
13815 	} else {
13816 		/*
13817 		 * Play it safe in case the guest temporarily disables paging.
13818 		 * The real mode IDT in particular is unlikely to have a #PF
13819 		 * exception setup.
13820 		 */
13821 		return is_paging(vcpu);
13822 	}
13823 }
13824 
kvm_can_do_async_pf(struct kvm_vcpu * vcpu)13825 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
13826 {
13827 	if (unlikely(!lapic_in_kernel(vcpu) ||
13828 		     kvm_event_needs_reinjection(vcpu) ||
13829 		     kvm_is_exception_pending(vcpu)))
13830 		return false;
13831 
13832 	if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))
13833 		return false;
13834 
13835 	/*
13836 	 * If interrupts are off we cannot even use an artificial
13837 	 * halt state.
13838 	 */
13839 	return kvm_arch_interrupt_allowed(vcpu);
13840 }
13841 
kvm_arch_async_page_not_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13842 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
13843 				     struct kvm_async_pf *work)
13844 {
13845 	struct x86_exception fault;
13846 
13847 	trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
13848 	kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
13849 
13850 	if (kvm_can_deliver_async_pf(vcpu) &&
13851 	    !apf_put_user_notpresent(vcpu)) {
13852 		fault.vector = PF_VECTOR;
13853 		fault.error_code_valid = true;
13854 		fault.error_code = 0;
13855 		fault.nested_page_fault = false;
13856 		fault.address = work->arch.token;
13857 		fault.async_page_fault = true;
13858 		kvm_inject_page_fault(vcpu, &fault);
13859 		return true;
13860 	} else {
13861 		/*
13862 		 * It is not possible to deliver a paravirtualized asynchronous
13863 		 * page fault, but putting the guest in an artificial halt state
13864 		 * can be beneficial nevertheless: if an interrupt arrives, we
13865 		 * can deliver it timely and perhaps the guest will schedule
13866 		 * another process.  When the instruction that triggered a page
13867 		 * fault is retried, hopefully the page will be ready in the host.
13868 		 */
13869 		kvm_make_request(KVM_REQ_APF_HALT, vcpu);
13870 		return false;
13871 	}
13872 }
13873 
kvm_arch_async_page_present(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)13874 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
13875 				 struct kvm_async_pf *work)
13876 {
13877 	struct kvm_lapic_irq irq = {
13878 		.delivery_mode = APIC_DM_FIXED,
13879 		.vector = vcpu->arch.apf.vec
13880 	};
13881 
13882 	if (work->wakeup_all)
13883 		work->arch.token = ~0; /* broadcast wakeup */
13884 	else
13885 		kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
13886 	trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
13887 
13888 	if ((work->wakeup_all || work->notpresent_injected) &&
13889 	    kvm_pv_async_pf_enabled(vcpu) &&
13890 	    !apf_put_user_ready(vcpu, work->arch.token)) {
13891 		vcpu->arch.apf.pageready_pending = true;
13892 		kvm_apic_set_irq(vcpu, &irq, NULL);
13893 	}
13894 
13895 	vcpu->arch.apf.halted = false;
13896 	kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
13897 }
13898 
kvm_arch_async_page_present_queued(struct kvm_vcpu * vcpu)13899 void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu)
13900 {
13901 	kvm_make_request(KVM_REQ_APF_READY, vcpu);
13902 	if (!vcpu->arch.apf.pageready_pending)
13903 		kvm_vcpu_kick(vcpu);
13904 }
13905 
kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu * vcpu)13906 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu)
13907 {
13908 	if (!kvm_pv_async_pf_enabled(vcpu))
13909 		return true;
13910 	else
13911 		return kvm_lapic_enabled(vcpu) && apf_pageready_slot_free(vcpu);
13912 }
13913 
kvm_noncoherent_dma_assignment_start_or_stop(struct kvm * kvm)13914 static void kvm_noncoherent_dma_assignment_start_or_stop(struct kvm *kvm)
13915 {
13916 	/*
13917 	 * Non-coherent DMA assignment and de-assignment may affect whether or
13918 	 * not KVM honors guest PAT, and thus may cause changes in EPT SPTEs
13919 	 * due to toggling the "ignore PAT" bit.  Zap all SPTEs when the first
13920 	 * (or last) non-coherent device is (un)registered to so that new SPTEs
13921 	 * with the correct "ignore guest PAT" setting are created.
13922 	 *
13923 	 * If KVM always honors guest PAT, however, there is nothing to do.
13924 	 */
13925 	if (kvm_check_has_quirk(kvm, KVM_X86_QUIRK_IGNORE_GUEST_PAT))
13926 		kvm_zap_gfn_range(kvm, gpa_to_gfn(0), gpa_to_gfn(~0ULL));
13927 }
13928 
kvm_arch_register_noncoherent_dma(struct kvm * kvm)13929 void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
13930 {
13931 	if (atomic_inc_return(&kvm->arch.noncoherent_dma_count) == 1)
13932 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13933 }
13934 
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)13935 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
13936 {
13937 	if (!atomic_dec_return(&kvm->arch.noncoherent_dma_count))
13938 		kvm_noncoherent_dma_assignment_start_or_stop(kvm);
13939 }
13940 
kvm_arch_has_noncoherent_dma(struct kvm * kvm)13941 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
13942 {
13943 	return atomic_read(&kvm->arch.noncoherent_dma_count);
13944 }
13945 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_arch_has_noncoherent_dma);
13946 
kvm_arch_no_poll(struct kvm_vcpu * vcpu)13947 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
13948 {
13949 	return (vcpu->arch.msr_kvm_poll_control & 1) == 0;
13950 }
13951 
13952 #ifdef CONFIG_KVM_GUEST_MEMFD
13953 /*
13954  * KVM doesn't yet support initializing guest_memfd memory as shared for VMs
13955  * with private memory (the private vs. shared tracking needs to be moved into
13956  * guest_memfd).
13957  */
kvm_arch_supports_gmem_init_shared(struct kvm * kvm)13958 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm)
13959 {
13960 	return !kvm_arch_has_private_mem(kvm);
13961 }
13962 
13963 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
kvm_arch_gmem_prepare(struct kvm * kvm,gfn_t gfn,kvm_pfn_t pfn,int max_order)13964 int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order)
13965 {
13966 	return kvm_x86_call(gmem_prepare)(kvm, pfn, gfn, max_order);
13967 }
13968 #endif
13969 
13970 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
kvm_arch_gmem_invalidate(kvm_pfn_t start,kvm_pfn_t end)13971 void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
13972 {
13973 	kvm_x86_call(gmem_invalidate)(start, end);
13974 }
13975 #endif
13976 #endif
13977 
kvm_spec_ctrl_test_value(u64 value)13978 int kvm_spec_ctrl_test_value(u64 value)
13979 {
13980 	/*
13981 	 * test that setting IA32_SPEC_CTRL to given value
13982 	 * is allowed by the host processor
13983 	 */
13984 
13985 	u64 saved_value;
13986 	unsigned long flags;
13987 	int ret = 0;
13988 
13989 	local_irq_save(flags);
13990 
13991 	if (rdmsrq_safe(MSR_IA32_SPEC_CTRL, &saved_value))
13992 		ret = 1;
13993 	else if (wrmsrq_safe(MSR_IA32_SPEC_CTRL, value))
13994 		ret = 1;
13995 	else
13996 		wrmsrq(MSR_IA32_SPEC_CTRL, saved_value);
13997 
13998 	local_irq_restore(flags);
13999 
14000 	return ret;
14001 }
14002 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_spec_ctrl_test_value);
14003 
kvm_fixup_and_inject_pf_error(struct kvm_vcpu * vcpu,gva_t gva,u16 error_code)14004 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code)
14005 {
14006 	struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
14007 	struct x86_exception fault;
14008 	u64 access = error_code &
14009 		(PFERR_WRITE_MASK | PFERR_FETCH_MASK | PFERR_USER_MASK);
14010 
14011 	if (!(error_code & PFERR_PRESENT_MASK) ||
14012 	    mmu->gva_to_gpa(vcpu, mmu, gva, access, &fault) != INVALID_GPA) {
14013 		/*
14014 		 * If vcpu->arch.walk_mmu->gva_to_gpa succeeded, the page
14015 		 * tables probably do not match the TLB.  Just proceed
14016 		 * with the error code that the processor gave.
14017 		 */
14018 		fault.vector = PF_VECTOR;
14019 		fault.error_code_valid = true;
14020 		fault.error_code = error_code;
14021 		fault.nested_page_fault = false;
14022 		fault.address = gva;
14023 		fault.async_page_fault = false;
14024 	}
14025 	vcpu->arch.walk_mmu->inject_page_fault(vcpu, &fault);
14026 }
14027 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_fixup_and_inject_pf_error);
14028 
14029 /*
14030  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
14031  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
14032  * indicates whether exit to userspace is needed.
14033  */
kvm_handle_memory_failure(struct kvm_vcpu * vcpu,int r,struct x86_exception * e)14034 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
14035 			      struct x86_exception *e)
14036 {
14037 	if (r == X86EMUL_PROPAGATE_FAULT) {
14038 		if (KVM_BUG_ON(!e, vcpu->kvm))
14039 			return -EIO;
14040 
14041 		kvm_inject_emulated_page_fault(vcpu, e);
14042 		return 1;
14043 	}
14044 
14045 	/*
14046 	 * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
14047 	 * while handling a VMX instruction KVM could've handled the request
14048 	 * correctly by exiting to userspace and performing I/O but there
14049 	 * doesn't seem to be a real use-case behind such requests, just return
14050 	 * KVM_EXIT_INTERNAL_ERROR for now.
14051 	 */
14052 	kvm_prepare_emulation_failure_exit(vcpu);
14053 
14054 	return 0;
14055 }
14056 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_memory_failure);
14057 
kvm_handle_invpcid(struct kvm_vcpu * vcpu,unsigned long type,gva_t gva)14058 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva)
14059 {
14060 	bool pcid_enabled;
14061 	struct x86_exception e;
14062 	struct {
14063 		u64 pcid;
14064 		u64 gla;
14065 	} operand;
14066 	int r;
14067 
14068 	r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
14069 	if (r != X86EMUL_CONTINUE)
14070 		return kvm_handle_memory_failure(vcpu, r, &e);
14071 
14072 	if (operand.pcid >> 12 != 0) {
14073 		kvm_inject_gp(vcpu, 0);
14074 		return 1;
14075 	}
14076 
14077 	pcid_enabled = kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE);
14078 
14079 	switch (type) {
14080 	case INVPCID_TYPE_INDIV_ADDR:
14081 		/*
14082 		 * LAM doesn't apply to addresses that are inputs to TLB
14083 		 * invalidation.
14084 		 */
14085 		if ((!pcid_enabled && (operand.pcid != 0)) ||
14086 		    is_noncanonical_invlpg_address(operand.gla, vcpu)) {
14087 			kvm_inject_gp(vcpu, 0);
14088 			return 1;
14089 		}
14090 		kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
14091 		return kvm_skip_emulated_instruction(vcpu);
14092 
14093 	case INVPCID_TYPE_SINGLE_CTXT:
14094 		if (!pcid_enabled && (operand.pcid != 0)) {
14095 			kvm_inject_gp(vcpu, 0);
14096 			return 1;
14097 		}
14098 
14099 		kvm_invalidate_pcid(vcpu, operand.pcid);
14100 		return kvm_skip_emulated_instruction(vcpu);
14101 
14102 	case INVPCID_TYPE_ALL_NON_GLOBAL:
14103 		/*
14104 		 * Currently, KVM doesn't mark global entries in the shadow
14105 		 * page tables, so a non-global flush just degenerates to a
14106 		 * global flush. If needed, we could optimize this later by
14107 		 * keeping track of global entries in shadow page tables.
14108 		 */
14109 
14110 		fallthrough;
14111 	case INVPCID_TYPE_ALL_INCL_GLOBAL:
14112 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
14113 		return kvm_skip_emulated_instruction(vcpu);
14114 
14115 	default:
14116 		kvm_inject_gp(vcpu, 0);
14117 		return 1;
14118 	}
14119 }
14120 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_handle_invpcid);
14121 
complete_sev_es_emulated_mmio(struct kvm_vcpu * vcpu)14122 static int complete_sev_es_emulated_mmio(struct kvm_vcpu *vcpu)
14123 {
14124 	struct kvm_run *run = vcpu->run;
14125 	struct kvm_mmio_fragment *frag;
14126 	unsigned int len;
14127 
14128 	BUG_ON(!vcpu->mmio_needed);
14129 
14130 	/* Complete previous fragment */
14131 	frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
14132 	len = min(8u, frag->len);
14133 	if (!vcpu->mmio_is_write)
14134 		memcpy(frag->data, run->mmio.data, len);
14135 
14136 	if (frag->len <= 8) {
14137 		/* Switch to the next fragment. */
14138 		frag++;
14139 		vcpu->mmio_cur_fragment++;
14140 	} else {
14141 		/* Go forward to the next mmio piece. */
14142 		frag->data += len;
14143 		frag->gpa += len;
14144 		frag->len -= len;
14145 	}
14146 
14147 	if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
14148 		vcpu->mmio_needed = 0;
14149 
14150 		// VMG change, at this point, we're always done
14151 		// RIP has already been advanced
14152 		return 1;
14153 	}
14154 
14155 	// More MMIO is needed
14156 	run->mmio.phys_addr = frag->gpa;
14157 	run->mmio.len = min(8u, frag->len);
14158 	run->mmio.is_write = vcpu->mmio_is_write;
14159 	if (run->mmio.is_write)
14160 		memcpy(run->mmio.data, frag->data, min(8u, frag->len));
14161 	run->exit_reason = KVM_EXIT_MMIO;
14162 
14163 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14164 
14165 	return 0;
14166 }
14167 
kvm_sev_es_mmio_write(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)14168 int kvm_sev_es_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
14169 			  void *data)
14170 {
14171 	int handled;
14172 	struct kvm_mmio_fragment *frag;
14173 
14174 	if (!data)
14175 		return -EINVAL;
14176 
14177 	handled = write_emultor.read_write_mmio(vcpu, gpa, bytes, data);
14178 	if (handled == bytes)
14179 		return 1;
14180 
14181 	bytes -= handled;
14182 	gpa += handled;
14183 	data += handled;
14184 
14185 	/*TODO: Check if need to increment number of frags */
14186 	frag = vcpu->mmio_fragments;
14187 	vcpu->mmio_nr_fragments = 1;
14188 	frag->len = bytes;
14189 	frag->gpa = gpa;
14190 	frag->data = data;
14191 
14192 	vcpu->mmio_needed = 1;
14193 	vcpu->mmio_cur_fragment = 0;
14194 
14195 	vcpu->run->mmio.phys_addr = gpa;
14196 	vcpu->run->mmio.len = min(8u, frag->len);
14197 	vcpu->run->mmio.is_write = 1;
14198 	memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
14199 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
14200 
14201 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14202 
14203 	return 0;
14204 }
14205 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_mmio_write);
14206 
kvm_sev_es_mmio_read(struct kvm_vcpu * vcpu,gpa_t gpa,unsigned int bytes,void * data)14207 int kvm_sev_es_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned int bytes,
14208 			 void *data)
14209 {
14210 	int handled;
14211 	struct kvm_mmio_fragment *frag;
14212 
14213 	if (!data)
14214 		return -EINVAL;
14215 
14216 	handled = read_emultor.read_write_mmio(vcpu, gpa, bytes, data);
14217 	if (handled == bytes)
14218 		return 1;
14219 
14220 	bytes -= handled;
14221 	gpa += handled;
14222 	data += handled;
14223 
14224 	/*TODO: Check if need to increment number of frags */
14225 	frag = vcpu->mmio_fragments;
14226 	vcpu->mmio_nr_fragments = 1;
14227 	frag->len = bytes;
14228 	frag->gpa = gpa;
14229 	frag->data = data;
14230 
14231 	vcpu->mmio_needed = 1;
14232 	vcpu->mmio_cur_fragment = 0;
14233 
14234 	vcpu->run->mmio.phys_addr = gpa;
14235 	vcpu->run->mmio.len = min(8u, frag->len);
14236 	vcpu->run->mmio.is_write = 0;
14237 	vcpu->run->exit_reason = KVM_EXIT_MMIO;
14238 
14239 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_mmio;
14240 
14241 	return 0;
14242 }
14243 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_mmio_read);
14244 
advance_sev_es_emulated_pio(struct kvm_vcpu * vcpu,unsigned count,int size)14245 static void advance_sev_es_emulated_pio(struct kvm_vcpu *vcpu, unsigned count, int size)
14246 {
14247 	vcpu->arch.sev_pio_count -= count;
14248 	vcpu->arch.sev_pio_data += count * size;
14249 }
14250 
14251 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14252 			   unsigned int port);
14253 
complete_sev_es_emulated_outs(struct kvm_vcpu * vcpu)14254 static int complete_sev_es_emulated_outs(struct kvm_vcpu *vcpu)
14255 {
14256 	int size = vcpu->arch.pio.size;
14257 	int port = vcpu->arch.pio.port;
14258 
14259 	vcpu->arch.pio.count = 0;
14260 	if (vcpu->arch.sev_pio_count)
14261 		return kvm_sev_es_outs(vcpu, size, port);
14262 	return 1;
14263 }
14264 
kvm_sev_es_outs(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14265 static int kvm_sev_es_outs(struct kvm_vcpu *vcpu, unsigned int size,
14266 			   unsigned int port)
14267 {
14268 	for (;;) {
14269 		unsigned int count =
14270 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14271 		int ret = emulator_pio_out(vcpu, size, port, vcpu->arch.sev_pio_data, count);
14272 
14273 		/* memcpy done already by emulator_pio_out.  */
14274 		advance_sev_es_emulated_pio(vcpu, count, size);
14275 		if (!ret)
14276 			break;
14277 
14278 		/* Emulation done by the kernel.  */
14279 		if (!vcpu->arch.sev_pio_count)
14280 			return 1;
14281 	}
14282 
14283 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_outs;
14284 	return 0;
14285 }
14286 
14287 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14288 			  unsigned int port);
14289 
complete_sev_es_emulated_ins(struct kvm_vcpu * vcpu)14290 static int complete_sev_es_emulated_ins(struct kvm_vcpu *vcpu)
14291 {
14292 	unsigned count = vcpu->arch.pio.count;
14293 	int size = vcpu->arch.pio.size;
14294 	int port = vcpu->arch.pio.port;
14295 
14296 	complete_emulator_pio_in(vcpu, vcpu->arch.sev_pio_data);
14297 	advance_sev_es_emulated_pio(vcpu, count, size);
14298 	if (vcpu->arch.sev_pio_count)
14299 		return kvm_sev_es_ins(vcpu, size, port);
14300 	return 1;
14301 }
14302 
kvm_sev_es_ins(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port)14303 static int kvm_sev_es_ins(struct kvm_vcpu *vcpu, unsigned int size,
14304 			  unsigned int port)
14305 {
14306 	for (;;) {
14307 		unsigned int count =
14308 			min_t(unsigned int, PAGE_SIZE / size, vcpu->arch.sev_pio_count);
14309 		if (!emulator_pio_in(vcpu, size, port, vcpu->arch.sev_pio_data, count))
14310 			break;
14311 
14312 		/* Emulation done by the kernel.  */
14313 		advance_sev_es_emulated_pio(vcpu, count, size);
14314 		if (!vcpu->arch.sev_pio_count)
14315 			return 1;
14316 	}
14317 
14318 	vcpu->arch.complete_userspace_io = complete_sev_es_emulated_ins;
14319 	return 0;
14320 }
14321 
kvm_sev_es_string_io(struct kvm_vcpu * vcpu,unsigned int size,unsigned int port,void * data,unsigned int count,int in)14322 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
14323 			 unsigned int port, void *data,  unsigned int count,
14324 			 int in)
14325 {
14326 	vcpu->arch.sev_pio_data = data;
14327 	vcpu->arch.sev_pio_count = count;
14328 	return in ? kvm_sev_es_ins(vcpu, size, port)
14329 		  : kvm_sev_es_outs(vcpu, size, port);
14330 }
14331 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_sev_es_string_io);
14332 
14333 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_entry);
14334 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
14335 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_mmio);
14336 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
14337 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
14338 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
14339 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
14340 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
14341 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter);
14342 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
14343 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
14344 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
14345 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmenter_failed);
14346 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
14347 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
14348 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
14349 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
14350 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window_update);
14351 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
14352 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
14353 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);
14354 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_ga_log);
14355 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_kick_vcpu_slowpath);
14356 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_doorbell);
14357 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_apicv_accept_irq);
14358 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_enter);
14359 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_exit);
14360 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_enter);
14361 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_vmgexit_msr_protocol_exit);
14362 EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_rmp_fault);
14363 
kvm_x86_init(void)14364 static int __init kvm_x86_init(void)
14365 {
14366 	kvm_init_xstate_sizes();
14367 
14368 	kvm_mmu_x86_module_init();
14369 	mitigate_smt_rsb &= boot_cpu_has_bug(X86_BUG_SMT_RSB) && cpu_smt_possible();
14370 	return 0;
14371 }
14372 module_init(kvm_x86_init);
14373 
kvm_x86_exit(void)14374 static void __exit kvm_x86_exit(void)
14375 {
14376 	WARN_ON_ONCE(static_branch_unlikely(&kvm_has_noapic_vcpu));
14377 }
14378 module_exit(kvm_x86_exit);
14379